text:
How to use millis() in my code instead of delay()?
I'm having issues trying to convert my code to non-blocking.
I was able to do so in some parts, but the rest aren't the same.
When I try to replace delay with an if statement like the spinning and sensors debounce it doesn't work at the right time, because the variable I subtract from cur_ms is not updated.
What I'm trying to do is to always switch_dir() and update_code(), and when second_btn.released() I want the other two functions to keep running but also to run a sequence of actions (those with the delay) without blocking.
I would love to get your help.
Thanks in advance :)
void loop()
{
    uint32_t cur_ms = millis();

    if (cur_ms - spin_ms >= SPINNING_MS) {
        switch_dir();
        spin_ms = cur_ms;
    }

    if (cur_ms - read_ms >= SENSORS_DEBOUNCE_MS) {
        update_code(get_sensors_state());
        read_ms = cur_ms;
    }

    if (second_btn.released()) {
        ball_servo.write(BALL_SERVO_MAX);   // drop the ball
        digitalWrite(BLOWER_PIN, LOW);  // blower on
        delay(BALL_DOOR_MS);
        ball_servo.write(BALL_SERVO_MIN);   // close ball door
        delay(BLOWER_MS);
        digitalWrite(BLOWER_PIN, HIGH); // blower off
    }
}

if (second_btn.released()) { should only run the first two commands, store ball_door_ms and set a state variable, for example state = 2........ new if statement if (state == 2 and cur_ms - ball_door_ms >= BALL_DOOR_MS) { would close ball door, store blower-ms and set state = 3 .... an so on

You had the right idea with your first few if statements! Just keep checking if time has passed, don't delay()
uint32_t releasedTime = 0;
if (second_btn.released() && releasedTime == 0) {
    releasedTime = cur_ms; // remember that the button was pressed now
    ball_servo.write(BALL_SERVO_MAX);   // drop the ball
    digitalWrite(BLOWER_PIN, LOW);  // blower on
} else if ((cur_ms - releasedTime > BALL_DOOR_MS) && (cur_ms - releasedTime < BALL_DOOR_MS + BLOWER_MS)) {
    ball_servo.write(BALL_SERVO_MIN);   // close ball door
} else {
    // must be after BALL_DOOR_MS + BLOWER_MS, time to run
    digitalWrite(BLOWER_PIN, HIGH); // blower off
    releasedTime = 0; // so this doesn't keep running
}

Re “releasedTime = 0; // so this doesn't keep running”: this won't work as promised by the comment. The line above (digitalWrite(BLOWER_PIN, HIGH);) will run over and over in the idle state. You would have to condition on if (releasedTime != 0) in order to avoid that, but note that 0 is a perfectly valid timestamp periodically returned by millis(). Also, the line ball_servo.write(BALL_SERVO_MIN); will run repeatedly during BLOWER_MS ms. May not be a big deal, but it slows down other tasks in the loop(). Both issues would be solved by using a proper “state” variable.

When second_btn.released is true, its two delay() statements will block the whole loop.  You can avoid this by rewriting so that the delay() statements are handled like you already handle spin_ms and cur_ms, which will involve some state-machine-type logic so that (for example) you set a state when you enter the BALL_DOOR_MS delay, then return to the main loop which will have a branch that is taken only if the BALL_DOOR_MS state is active.  When that state ends it sets a new state that enables a separate branch of the main loop to do the BALL_SERVO_MIN and start the BLOWER_MS state, and so on.  A switch/case chain may be
the best way to handle this, replacing the present second_btn.released.

This link might be helpful: The Finite State Machine.

Switch-case will block the rest of the loop, isn't it?
Could you write a code sample to showcase your idea?

The link was very helpful. It works. Thank you very much :)

<To design in the millis() function, you have to think of it like using a stop watch. You record a time at which you started. Let's say you started at 10000mS. Then every so often, you check the current time. Let's say the current time is 10500mS. You then take the current time and subtract it by your start time to get the time elapsed since you started. This gives you 500mS. Let's say you're desired delay time is 1000mS. Since the elapsed time isn't 1000mS you keep doing other things until the Current time - Start time is greater than or equal to your delay time. Then you do what ever task you need to do, and then record a new start time and do the process all over again. It would look something like this.>
#define DELAY_TIME     1000   // the amount of time you want to delay `

unsigned long startTime = 0;
unsigned long currentTime = 0;

void setup()
{
   startTime = millis();  // Record starting time
   currentTime = startTime; // Set current time to start time so elapsed time would = 0
}

void loop()

{

currentTime = millis(); // update the current time value

if((currentTime - startTime) >= DELAY_TIME)) // check amount of time elapsed
  {
    // The amount of delay time has elapsed
    // Do what ever you need to do here that requires the delay

       startTime = millis(); // Reset the start time so that it waits another 1000ms
       currentTime = startTime; // Set the current time = to start time to avoid negatives
    }
  // Then put the rest of the code that you want to run continuously here

}

What you advise here is exactly what the OP is already doing. He knows how to do this. His issue is about combining this technique with a state machine for handling the ball door and blower.


text:
Use serial communication on Sparkfun SAMD21 mini board
I am working on an economic module to be able to use serial communication with the Sparkfun SAMD21 mini development card. And I have one, the DTR (of my CH340G) do I have to connect it to the reset of my MCU? I mean, to reset the board, do I just have to press the reset button on the module or both (the MCU and the USB / UART module)? I enclose the schematic of how I made the small module, if anyone has suggestions or recommendations, I appreciate them.

It occurred to me to review the diagram of the arduino nano, which has the integrated USB / UART bridge, and from what I see, the DTR connects to the reset of the microcontroller and then to the button.
Regards.

Why would you look at the schematic of the Nano which uses a completely different MCU and bootloader / programming system? You should look at a device that uses the same chip as the one you are using.

i search, but i only found the Arduino Zero, that dont use a USB/UART bridge in this format, that uses a  MCU.

the SAMD21 has native USB and Arduino core listens for 1200 baud short connection to invoke a reset to bootloader. nobody wires a USB chip to SAMD21. or a double reset activates the bootloader. what do you want to do with the CH340? do you have an UART bootloader for SAMD?

I was thinking that the D+ and D- on the SAMD21 are only to programm, (like the JTAG on FPGAs). So, i have a full COM connection with that same usb too?

look at Arduino SAMD21 boards schematics. Zero, MKR or Nano 33 IoT

source: Stack Exchange

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

sort: votes


text:
External RAM (23LC1024) and external Flash (W25Q64JVSSIQ) with Sparkfun SAMD21
i'm trying to extend the capabilities of the Sparkfun SAMD21. My question is, which pins do I have to share? I mean, I understand that MISO, MOSI and SCK are shared, but CS connects each to a different pin, am I correct?
My schematics:

I connect my CS_RAM to the D10(PA18 on SAMD21).
and i connect my CS_FLASH to the D6(PA20 on SAMD21)

Yes, you are correct.

Atmel SAMD21 is manufactured by Microchip. you have some Sparkfun board with SAMD21 MCU?

Im doing my design with this board as reference: https://www.sparkfun.com/products/13664 | Schematics: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/sparkfun-samd21-mini-breakout-v10.pdf

You are correct, MISO, MOSI and SCK are common to all the SPI devices. Be sure they are all set up for clock polarity etc. The CS\ line is the select line. If the device is not selected it does not matter what goes on with MISO, MOSI and SCK. There are chips such as the 74HC138 that will give you chip selects with just a few additional pins. 1 pin gives you 2 selects 2=4 and 3 gives you 8 selects.

Ok, but i can connect my CS to digital pins, right?

With polarity u mean put a litle power in the lines? like u can see on the image that i add, i have 10k resistors from +3.3V to CS and in one case MISO and MOSI. SCK no needs nothing, right?

Yes they are digital, and that is probably 3V3 in your system. It should work fine, the Arduino pins should be high during reset which will disable the CS\ (active low) chip select.

so, with a Mosfet connected to the RESET pin of my SAMD21, i connect my CS_RAM and CS_FLASH to 3.3v? or what do u mean? check that i have 10K resistors between CS and 3.3V.

Simple digital thoughts. Inputs can go to inputs or outputs or VCC or Ground but never floating. Outputs can go to inputs only (resistor in series with LED ok). Normally outputs can NOT go to outputs they have a maximum current beyond which they will fry In your case CS in an input. There are exceptions of course but this is not the time to enumerate them.

I dont get you, i have my CS connected with a 10k resistor to 3.3v and to the digital pin. What go to fry?

It sounds like it is connected correctly. Your software has to select and communicate with it. You need to select the device to communicate with it. SPI is simply a fancy shift register, you have to send something to it in order to receive. It clocks data out as you clock data in.

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


text:
Connect SDRAM to STM32
Well, first of all hello to everything and thanks for reading my question. I am designing a board with STM32F730R8T6 MCU, and I want to connect MT48LC16M16A2P-6A to it which is 4MB SDRAM chip. The connections are pretty basic from what I saw, the thing is, how can I access that memory from my MCU? I mean there is a library or something to use it? and, if someone can send me an example schematic, to connect the memory I would appreciate it. Greetings.

As far as I know, you have to choose variant with FMC module (Flexible Memory Controller) with SDRAM support - that means you have to use 144pin version STM32F730Z8. The 100pin version does have FMC but doesn't support SDRAM.
After resolving this issue, it should be about configuring FMC module for using SDRAM (in STM32CubeMX for example) and the RAM will be available at some memory location according to the MCUs memory layout.


text:
Arduino/ESP8266 How to give users updated compiled code without using Arduino IDE
I have an Arduino project using an ESP8266 dev board.
I want to be able to give users updates to my software in the future and I don't want them to have to download the code and the Arduino IDE to do so.
Is there a way to take the compiled code from the Arduino IDE and use some other software to upload the compiled code to the ESP8266 dev board?

There's a detailed console option (can't remember what it's called) that when enabled will show you how the board is being programmed. You can then run those commands outside of Arduino IDE to have the same effect.

I figured it out! After getting some comments, I have decided to got with Option B.
Firstly for both options, you will need to:

Using the Arduino IDE
Under the "Sketch" tab; click "Export compiled Binary", then click "Show Sketch Folder" (This is where your .bin file is)

Option A - Using an application

Download the ESPEasyFlasher code from below.
You will probably have to open this with Visual Studio and compile it yourself.
Make sure your .bin file and esptool.exe are included in your bin/release folder or  wherever you want to have the "FlashESP8266.exe" program permanently.
Run the "FlashESP8266.exe" program; select your com port, select your bin file, select the upload rate, then click flash.

So you just have to make sure that your user has;

Python installed
Provide them a copy of the "FlashESP8266.exe"
Provide them a copy of the "esptool.exe"

I don't know if this will work the exact same for an ESP32 as I believe they have two .bin files...
Resources:
https://nerdiy.de/en/howto-esp8266-mit-dem-esptool-bin-dateien-unter-windows-flashen/
https://github.com/BattloXX/ESPEasyFlasher
Option B - Using OTA Update
3.You will need to first implement OTA Updates as @StarCat has pointed out
in the comments.
4.Navigate to the URL you implemented.
5.Choose the File System, select your .bin file.
6.Click Update FileSytem
7.Should take a couple seconds or so and should be updated!
I can confirm this works when your ESP8266 is set to host a Soft Access Point.
Koudos to @StarCat.
Resources:
https://arduino-esp8266.readthedocs.io/en/latest/ota_updates/readme.html#web-browser

You could also use the ESP8266HTTPUpdateServer in your code to allow the user to update the dev module using a web browser and the .bin file you provide them.

i would use the OTA to avoid any need of software. there's a few examples built-in tpo the lib, i can't recall which one is best. i would use the one where the user browses to an html page served by the esp instead of relying on an internet connected push server, which can be prone to field problems that a dead-simple upload this file to this page option is.


text:
ESP8266 crashes when button is pressed
I'm building a wireless QLab Go button based on an ESP8266-01. There is a web UI to connect to a wireless network and setup the IP address of the computer running QLab. When a button is pressed, the ESP is meant to send an OSC message to that computer.
In fact, this works. But only a few times. After, let's say pressing five times the button, the ESP becomes unresponsive. The blue LED flashes, but apparently the OSC message is not sent. Also, the webserver is unreachable.
Also remarkable: my FTDI232 doesn't always communicate with the serial monitor of the Arduino IDE... Any ideas on what might be wrong here?
#define FIRMWARE "v0.4.3"
#define VERBOSE
//#define LOAD_DEFAULTS

#define BUTTONPIN 2

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <OSCMessage.h>

#include "globals.h"

void setup() {
  EEPROM.begin(128);

  #ifdef VERBOSE
    Serial.begin(9600);
    Serial.println("--------------------");
    Serial.println("QLab Spacebar Button");
    Serial.print("Firmware Version: ");
    Serial.println(FIRMWARE);
  #endif

  #ifdef LOAD_DEFAULTS
    #ifdef VERBOSE
      Serial.println("Load Default Settings:");
    #endif

    saveSettings();
    startHotSpot();
  #else
    // If we cant load settings from EEPROM, start the hotspot
    if (!loadSettings()) {
      startHotSpot();
    }
  #endif

  // Start hotspot if we're in standAlone mode otherwise we start the wifi
  if (standAlone == 1) {
    startHotSpot();
  } else {
    startWifi();
    allowHotSpot = 0; // Dont allow hotspot to run after this initial setup - must restart device to start it again
  }

  // Start WebServer
  startWebServer();

  // Start listening for UDP packets
  qUDP.begin(qlab_port);

  pinMode(BUTTONPIN, INPUT);
  attachInterrupt(BUTTONPIN, spacebar, RISING);
}

void loop() {
  webServer.handleClient();
}

void spacebar() {
  #ifdef VERBOSE
    Serial.println("Received a click -- will send OSC message now!");
  #endif
  OSCMessage msg("/go");
  qUDP.beginPacket(qlab_address,qlab_port);
  msg.send(qUDP);
  qUDP.endPacket();
  msg.empty();
  delay(500); //Safety measure: you can't press the spacebar twice
}

(Most of the other code is in other files, I think this is the only relevant part)
The wiring diagram for the ESP is as follows: (I don't know how to draw it so I'll just try to write it down...)
Gnd->Gnd
Tx -> Rx
Rx -> Tx
CH_PD -> 3.3v
Vcc -> 3.3v
GPIO2 -- 10k ohm resistor to 3.3v
      \_ Gnd (this is meant to be a button: pulled to Gnd when pressed)

How are you powering the ESP8266-01 ? A USB connection may not be able to supply sufficient power in all situations although a large value capacitor connected across the supply close to the ESP will help

You should not do too much in an interrupt routine. Ideally you would just set a flag and then poll that flag in loop() and do all the work there.

@Bra1n I'm powering the FTDI with the USB port from my laptop indeed... Do you think this draws too much current?
@Majenko I removed the interrupt and and put in the loop if(BUTTONPIN == HIGH) { spacebar(); } which seems to work better and consistently longer, although the webserver still isn't reachable all the time...

not sure if it applies to ESP's but with arduino, delay doesn't work inside an ISR, so that delay may be irrelevant anyway. But you're trying to do way too much inside the ISR as pointed out above

thanks for the comments -- moving the routine to the loop section seems to solve the problem. why is it that delays cause problems in an ISR?


text:
UNO's Internal EEPROM "read" returns incorrect values when it precedes "write"
I am an Arduino instructor and I was preparing some material on the utilization of the Arduino UNO's internal EEPROM when I encountered a problem.
The problem is, I am trying to show the original value on a specific EEPROM location using the EEPROM.read function, then I do write a new value to that location using the EEPROM.write function and try reading it again, please take a look at its code, I use the Serial Monitor to print those values.
#include <EEPROM.h>

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

  // Print to the Serial Monitor the value read from address 20. "Which should be 255"
  Serial.println(EEPROM.read(20));
  // Write to the EEPROM the value 143 in address 20.
  EEPROM.write(20, 143);
  // Print to the Serial Monitor the value read from address 20. "Which should be 143"
  Serial.println(EEPROM.read(20));
}

void loop() {

}

Now I have verified already that this location has a value of 255 using another sketch which basically does nothing but print the contents of the EEPROM on the Serial Monitor.
#include <EEPROM.h>

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

  for(int i = 0; i < 1024;i++)
  {
    Serial.print("Address: ");
    Serial.print(i);
    Serial.print(", Value: ");
    Serial.println(EEPROM.read(i));
  }

}

void loop() {

}

Now what is my problem?
My problem is in my first sketch, the EEPROM.read function does not return 255, instead it returns the value 143 which is not even supposed to be there until the next instruction.
I know the EEPROM.write takes around 3.3ms and the writing is what wears down the EEPROM cell, but I also do know that reading takes approximately 0ms and does not wear down the EEPROM cell.
Even though that in mind, I have deliberately placed a "delay(100);" after reading, still no result.
#include <EEPROM.h>

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

  // Print to the Serial Monitor the value read from address 20. "Which should be 255"
  Serial.println(EEPROM.read(20));
  delay(100);
  // Write to the EEPROM the value 143 in address 20.
  EEPROM.write(20, 143);
  // Print to the Serial Monitor the value read from address 20. "Which should be 143"
  Serial.println(EEPROM.read(20));
}

void loop() {

}

Further more, when I remove the EEPROM.write completely from the code and utilize the EEPROM.read only, I do read correct results, but of-course I do change the address as well to test it.
My setup is:
Windows 10 Pro 64-bit.
Arduino IDE 1.8.15
Arduino UNO china clone version. (not SMD)
My question is, what am I doing wrong here?
Do I have an invalid understanding of something around here?
I have worked with EEPROMs before (both internal and external) using PIC18F microcontrollers, so my experience (which may be incorrect) yields that this sketch should work perfectly.
Thank you in advance.

Try adding delay(5000); at the start of setup. What I think happens is; You upload your code. After uploading the code will run immediately. Then you open the serial console. Opening the serial console resets the Arduino. So now the code runs a second time, and will display the already written EEPROM data.

Excellent interpretation, but since I am not new into this I don't ever close my serial console so not to reset the Arduino, it is always open even before uploading the code, however I tried it, and it indeed worked.
But why?

The Arduino IDE suspends the serial connection while uploading, and then resumes when done. It looks like they added some delay before reopening the serial connection. So it looks like you code will run twice, even when you keep the Serial Console open.

Thank you so much for your clarification and your time.

This is NOT my answer, this is the answer of @Gerben, thank you.
The Arduino IDE suspends the serial connection while uploading, and then resumes when done. It looks like they added some delay before reopening the serial connection. So it looks like your code will run twice, even when you keep the Serial Console open

@Gerben should answer this. Your task is to accept his answer.

I agree, if he posts an answer I will definitely accept his, that's why I did not accept my answer.

Per the documentation at:https://www.arduino.cc/en/Reference/EEPROMWrite   An EEPROM write takes 3.3 ms to complete. What tells us is you must give it that amount of time or more to complete the operation. Insert your delay after "EEPROM.write(20, 143);" of at least 3.3 ms or delay(3300);. That should resolve your problem. You can also use that to have your students read the manual. Present as a problem so they can try to solve it. Once you get caught by it (we all have) you never forget.

Read the question more carefully. The issue is about the EEPROM.read() that happens before EEPROM.write(). Adding a delay after EEPROM.write() won't change anything.


text:
Extracting .hex from Arduino Due
I have an Arduino Due that was programmed by the Arduino IDE, to cut things short I lost access to the original sketch (.ino) file, there is no way of recovering it no matter what.
I know that in the 8-bit MCUs I can read the .hex file from the flash memory, I already did that with PIC and AVR MCUs with their software programmer utilities.
My question is: Can I use a software programmer utility on Windows PC to extract the hex file to reprogram other Arduino Due with it? If yes, please help me.
I've read about the Bossac utility, it looks promising, but I have no experience in the ARM MCUs field at all.
again: I am NOT interested in C or Assembly code, I just want the .hex file.

you can simply read the hex with avrdude with the -U flash:r:filename option

No you can not, avrdude is for 8-bit Atmel MCUs, this is a 32-bit ARM MCU, the USBASB will not work.

You're right, my bad!

No worries at all, I will try now some methods and report back if anything succedded.

I'm sure you can do it through the JTAG interface. No idea how though.

You can use JTAG and probably should.  But, it can also be done with bossac if you are very careful.  If you're not, you'll end up erasing your flash on your source board.
Using bossac
This would maybe not be preferred over JTAG because it is probably easier to screw up (see warnings below), but it can be done.  I may add some on JTAG programming later, and if I do it may be above this section for that reason.  The main advantage here is just that you don't need a JTAG programmer.  The one caveat is that your existing sketch, or rather the image of the sketch that has been burned onto what I'm calling the "source board" has to be functioning well enough that it can cooperate in being placed back into the ROM bootloader.  I fully expect this is not a problem for you, or for pretty much any normal Arduino sketch that has been burned to a board.
WARNINGS

Under NO circumstances do you want to connect to the PROGRAMMING port of your source board at 1200 baud.
Doing so will erase your board, and then that's the end of it.

In the below you will be connecting to the Native USB port at 1200, NOT the programming port.
Connect only one port at a time to your computer so there is no possibility of selecting the wrong one.

Practice this whole procedure with a board you don't care about first.

Locate your BOSSAC command.
On my Windows machine, it was in:
C:\Users\username\AppData\Local\Arduino15\packages\arduino\tools\bossac\1.6.1-ardunio\bossac.exe

It may be under a different version number.  It's possible that it will be in a completely different location.
cd %USERPROFILE%
dir bossac.exe /s/b/p/a

Should locate it it, eventually, in any case.
On Linux it will be under ~/.arduino15 somewhere:
find ~/.arduino15 -name bossac

On a Mac it will probably be under a /Library/ directory under the user account somewhere.  You get the idea, locate it, make sure you can run it.
NOTE: There's a bossa program that is the GUI version where bossac is a command-line program.  Unfortunately the IDE board support files don't ship the GUI program.  If you're having trouble with the command-line and want to try that instead, go for it.  But test it on a board you don't care about beforehand.  I have not tried it.
Connect to the Native Header
Connect your native USB port on the source board and only to that port.

Enable boot to ROM
Open a terminal emulator of your choice at a rate of 1200 baud to the native USB port, wait a couple seconds and then close the port.  You can use the Serial Monitor from the IDE to do this if you want:

Select the correct port from Tools/Port.

Open the Serial Monitor

Switch the baud rate to 1200 baud.

You're not going to type anything and you're not going to see anything once you're connected at 1200 baud.

Close the Serial Monitor

You probably should:

See if the port has changed COM#, if so select the new one.

Re-open the serial monitor

Change the baud rate again to anything-but-1200-baud

Close the serial monitor again.
This is not strictly necessary but the IDE remember the last chosen baud rate, and for what we're doing this is a slightly dangerous thing.

Close the IDE as well.

What connecting at 1200 baud does is activate the code inside the core part of the programmed sketch that changes the board to boot from the internal ROM bootloader.  It doesn't need traffic.  It just needs to see a request for 1200 baud.  More specifically, it needs to see the DTR "signal" go inactive, which happens when the port is closed, when the effective rate was 1200 baud.
NOTE: if you screw up here and connect to the programming port at 1200 baud instead, you'll wind up causing the ATMega16U2 to erase your source board.  The IDE remembers your last chosen baud rate, which makes this easy to screw up as well.  Hence the weird little dance in the above instructions regarding reopening the serial monitor and changing to something other than 1200 baud.  It's just putting an extra barrier up to accidentally doing this.
Once you've connected to the native USB port at 1200 baud and closed the port, your board will not run your sketch any more.  It's still there, it's just not running it.  The board has been told to sit in the ROM based bootloader, waiting for bootloader commands.
Saving your existing sketch's image
What we're going to do is run the bossac command you found earlier like so:
bossac --read saved-sketch-image.bin --boot --reset

I'm assuming you either changed directory to where bossac.exe is, or alternately you're going to specify the necessary path to it found earlier.  I've found this command locates the correct COM port automatically.
This command:

Downloads all of flash, 512 kbyte, and takes while, 128 seconds in one test.  Weirdly the same version under Linux takes closer to 10 seconds;  I haven't looked into why the difference, but I'm also unconcerned.
So you now should have a 512 kbyte raw binary file containing your sketch image.

It re-enables the boot-from-FLASH so that on the next reset it will go back to running your sketch

It resets your board, so it will begin running your old sketch.  If you don't want it to do that until you power cycle it, you could just as easily leave off the --reset part.

As said, this is a raw binary file.  But you mentioned a HEX.  I'm assuming you didn't mean that literally, so I'm not going to detail how to convert the .bin file to a HEX format.  Though, if you want to do that, you should know that it needs to be offset to 0x80000, because that's where flash starts on the Due.
Disconnect your source board from USB.
Making your clone (target) board
Connect to your target board via the programming port.

Hold the erase button for a few seconds to make sure the target board is erased.  Usually this would be done by the IDE connecting to the port for a while at 1200 baud.  But since we're using bossac at the command line, we need to do that step manually; it's just easier to use the button this time.

Reset the board with the reset button.  Your target board is now sitting in its ROM bootloader awaiting commands.

Put your image on the new board with:

bossac --write saved-sketch-image.bin --boot --reset

Again, it's programming the whole 512 kbytes.  In one test on Windows it took about 100 seconds; no difference between Windows and Linux.  We're using the USART (programming port) which is slower than USB and we're flashing rather than reading which is slower; I haven't bothered to figure out which thing is the bottleneck.

Like before --boot sets the board to boot from flash (your sketch) on next reset.

And again --reset just resets the board.

Your target board should now be be behaving identically to the original source board.

There's an Arduino auto-erase feature in bossac that may simplify parts of this procedure, but I haven't tested it out yet.  I'm leaving as is until I can play with that command-line option.

I have now successfully cloned a Due's flash to another via 10-pin JTAG header using OpenOCD as well, though it may be a while before I update this.  I have not yet done it on Windows nor via SWD header, which seems to be one that more reliably comes pre-soldered.  For now: In any case, yes you can do it.  If you want flash via JTAG, which is less important than reading, just know that you need to issue  OpenOCD flash bank commands before the program command will work, and that if you don't the error you'll get out of the program command doesn't make this clear.

Thank you very much, it worked 100%.
And yes I meant .bin not .hex it is my mistake.
You are a life saver :)

When you say Doing so will erase your board, and then that's the end of it, you mean the .bin right?, not that the board will be somehow screwed for further work with other source codes?

That phrase refers specifically to what will happen if you connect to your programming port at 1200 baud.  The firmware that is on the atmeag16u2 that behaves as a serial transceiver has been coded such that a connection at 1200 baud  will effectively hit the erase button for you.  So, no I don't mean it will erase a file, it will erase the content of flash on the board itself.  Given that the goal here is to preserve firmware on the board, it seemed appropriate to warn against doing this thing that will completely destroy the firmware currently on the board.

Connecting to the programming port at 1200 baud wouldn't wouldn't ruin your hardware; it would ruin any chance of success at recovering the current contents of flash.


text:
PID controlled DC Motor Speed
I'm writing a PID program for a simple DC Motor. This motor has an encoder at the bottom which allows me to read motor speed. The goal of the project is to provide a constant speed if there is light friction applied to the motor. Although speed may vary slightly, I can still graph the PWM signal and show the duty cycle increases in response to friction. I've gotten the motor speed and potentiometer to function perfectly, now I'm just stuck on the actual PID part.
The issue I'm having is that whenever I set my SET pin high, the motor completely shuts off. I don't understand why because I'm sending it values in that while loop which should be sufficient to initiate the compensation
Here is my code:
#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;
//Polarity
const int IN1 = 11;
const int IN2 = 10;

volatile float pot=0;
//PWM Signal and Analog from the Potentiometer
const int POT = 0;
const int ENA = 6;

const int SET = 12;

int rotation;

double Setpoint, Input, Output;
double Kp=1, Ki=1, Kd=1;

PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void docount()  // counts from the speed sensor
{
  counter++;  // increase +1 the counter value
}

//This takes the docout() counter and calculates how many holes its read to give rotations per second
void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  rotation = (counter / 31);  // divide by number of holes in Disc
  Serial.print(rotation,DEC);

  Serial.println(" Rotation per second");
  counter=0;  //  reset counter to zero
  Timer1.attachInterrupt( timerIsr );  //enable the timer
  Serial.print("pot = ");
  Serial.print(pot);

  Serial.print("\n");

}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(SET, INPUT);
  Timer1.initialize(1000000); // set timer for 1sec
  attachInterrupt(0, docount, FALLING);  // increase counter when speed sensor pin goes High
  Timer1.attachInterrupt( timerIsr ); // enable the timer

  myPID.SetMode(AUTOMATIC);
  myPID.SetSampleTime(10);
}

void loop()
{
  // This bit is how you convert the pot values to manually control the fan
  pot=analogRead(POT)/4.01569;
  analogWrite(ENA, pot);

  // This basically acts as a push button. If the SET pin is HIGH it initiates the PID and whatever
  // the current rotation and pot setting are, they're used to send to the myPID function above to
  // maintain current operating values
  while (digitalRead(SET) == HIGH)
  {

      Setpoint = rotation;
      Input = pot;
      myPID.Compute();
      analogWrite(ENA, Output);
      digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
      digitalWrite(11, LOW);

  }
  digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
  digitalWrite(11, LOW);

  delay (50);
}

You haven't implemented any of the suggestions, that I gave in my answer to your previous question. Did you find them not fitting? Or were something unclear? Then please comment on my answer, so that it can be approved.

Your logic seems garbled. I thought you use the pot (which is constant while SET is HIGH, since you don't read it there) to control the setpoint, but currently you use it for input of the PID, which should instead be the current speed value.

And most likely your while loop runs so fast, that the PWM wave gets restarted again and again, effectively chopping it up to zero, which means no speed


text:
Esp8266 Vin pin
I've read that Vin pin is directly connected to usb cable in esp8266 (which is 5V). I wonder if I can power a relay 5V and a servo motor Sg90  with this pin? And is there any danger of doing that ?

esp8266 is a 3.3 V chip without USB. what dev board do you have?

I have esp8266 node mcu with usb adapter

most devkits have a diode connecting USB to Vin. you can burn this diode if you draw too much current. The current handling depends on how cheap they were at the factory, but anything above 1A will fry a cheapo board. Of course, you can solder bridge out the burnt diode, as long as you take care sending when plugging the USB into an actual PC.

The GPIO pins on the ESP8266 (including the ones with built-in NodeMCU) are 3.3v tolerant.
First, if there is ever any feedback from the 5v+ from the relay coming back down the signal wire, it'll likely cook the ESP.
Also, if it's a 5v relay, 3.3v from the ESP most likely wouldn't be enough to trigger the unit anyhow.
You'll either need to power the relay from an external power supply (or the Vin pin depending on the mA the relay requires), and then use a voltage converter (eg. logic level converter) so you can have 5v on the relay side (I'm speaking of the signal pin here), and 3.3v on the ESP side, or purchase a relay that will operate on 3.3v.

(Answering in more detail, as this is the top search hit for "ESP8266 Vin", at least for me)
TL;DR: Vin is NOT directly connected to USB power. There is a protection diode between USB+/VU and Vin, which has a limited current capacity.
If your board provides VU, that one is directly connected to USB power.
As long as you only power 1-2 tiny devices, it should be OK. (controlling will need additional components, or it will fry your ESP)

Since you talk about 'Vin' and '5V', I'm going to assume you have a devboard, not a 'naked' ESP8266. If your "esp8266" has a USB-connector and flash/reset buttons, then its a devboard-version. If it is only a fingernail-sized metal cover with a 1mm edge with solderpads, then its 'naked'.
The Vin pin is a power input for the onboard regulator.
On all common devboards, there is a protection diode between the USB+ wire, and Vin.
Some devboards also provide a VU-pin, which is directly connected to the USB+ wire without anything in-between.
The 3.3V regulator converts any input voltage (5V-19V) connected to Vin into the 3.3V needed by the ESP chip and the 3V3-pins. The regulator has capacity (barely) for the ESP and a (large) handful of leds, not much more.

There is always danger when connecting mechanical/magnetic 'power'-devices (relays, servos and motors) in the same circuit with 'sensitive' microcontrollers/logic gates.
'power' devices are noisy and cause feedback which must be filtered, blocked and absorbed so it will not fry 'small' electronics. (even a toothbrush motor is 'power', compared to microchips).
'Power' devices are also hungry, causing voltage drops when activated. These drops can cause glitches, bugs and even resets in logic-level electronics.
This not stop many people from trying it anyway, and it will often work, for a while, until it someday 'mysteriously' stops working because the chip finally gave out under the repeated abuse.
(side note: as other have mentioned: You also cannot control magnetic/mechanical devices directly from the signal pins. Microcontroller outputs are too weak. Trying anyway can destroy your microcontroller with the feedback.)

A detailed background explanation for powering ESP devboards, including wiring schematics and explanations, can be found here:
https://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

Relays, motors, and other inductive loads release a surge of reverse current when you remove power from them. You have to connect a suitably sized “flyback diode” across the coil, wired backwards from the normal current flow direction to protect the other devices on the circuit from that reverse current or they will likely be damaged.
Relays and motors also draw a large in-rush of current when they are first connected, which can cause the supply voltage to droop.
You can buy relays that are made to be controlled by logic levels. They take a low power 5V or 3.3V logic level input, plus a separate power supply, and use the logic input to switch the relay on and off safely. The relay modules I’m using have optical isolation for the logic lines for extra protection.


text:
Arduino SPI Multiplexer problems
I want to use the ADG731 32 ch multiplexer to read 32 potentiometers, I have wired everything and it works but it doesn't works as fast as I would want.
The problem is that If I turn a potentiometer between the range of 10-90% of the rotation, the analog reading is so slow, for example, if I have my POT at 0, and i turn it to 50%, it goes so slow until it reach the 512 value(like an hysteresis effect), BUT, if I turn the potentiometer back to 0 or up to 1023 it makes the reading as quick as I would expect.
So in resume it reads slowly the values except the edges values.
This is my code(I have set it to read only one potentiometer at pin S16 to test how the ADG731 works:
#include <SPI.h>

void loadDrain(void);
const int slaveSelectPin = 53;
void setup() {
  pinMode(slaveSelectPin, OUTPUT);
  SPI.begin();
  Serial.begin(9600);
}

void loop() {
  loadDrain();
}

void loadDrain(){
  SPI.beginTransaction(SPISettings(30000000, MSBFIRST, SPI_MODE2));
  digitalWrite(slaveSelectPin, LOW);
  SPI.transfer(00001111);
  digitalWrite(slaveSelectPin, HIGH);
  SPI.endTransaction();
  Serial.println(analogRead(A0) >> 3);
}

You should remove the multiplexer from the circuit to see if that is the culprit. (I'm guessing not.) I'd try wiring 1 pot directly to the analog input pin and seeing if the results are still slow to register.

BTW, why do you issue the SPI commands to select the specific pot every time, even though in your test you're reading the same pot every time?

@DuncanC without the MUX it reads properly; Because you must select what channel of the MUX you want to read thru SPI. And now I am only reading one because I only want to read one pot to test if it works correctly and the when I have it working correctly I will add the other 31

What value (ohms) pots are you using?

@Gerben 10K ohms

Are you using Linear taper pots? Or audio/logarithmic taper pots?

@CrossRoads linear

Take a deep look into the library you are using to read the POT. Most HW and / or SW will take many readings & average them to remove the randomness and improve the accuracy of the ADC HW. It could be that your setup is so noisy that the SW is compensating by taking even more readings to average. Hats off the the SW developer who had the foresight to adapt the code to noisier situations. If true, and you think that too much automation, remember you are using the Arduino platform where the libraries are designed to make things simple by abstracting (hiding) the hardware details.

to read the pot I am using the analogRead() standart function, can you give me more information about what you say please, it is interesting to analyze

Remember that the libraries are re-written for each different processor.  What source code you look at depends on the processor.  The point of the libraries is to abstract the differences of each processor such that the Arduino code doesn't have to change or doesn't have to change much when ported to different platforms (processors).

Some things look odd:
Why do this every time? You only need to set these up one time in setup():
SPI.beginTransaction(SPISettings(30000000, MSBFIRST, SPI_MODE2));

Most 16 MHz Arduinos, including the Mega you appear to be using, won't do 3 MHz, choices are 8 MHz, 4,MHz, 2 MHz, 1 MHz  and 3 or 4 more slower speeds.
The chip seems to support higher speeds, 8 MHz should work:

fSCLK 30 MHz max SCLK Cycle Frequency

So run it faster to same on time.
Why take a 10-bit reading and shift it down to 7?
Serial.println(analogRead(A0) >> 3);

You could speed up the reads by doing an 8-bit read instead of 10-bit, and use a faster Serial speed, up to 115200, to send the results out.
Instead of digitalWrite() to control the slaveSelect pin, you could use direct port manipulation to toggle that pin.  You can write a 1 to the Input port to toggle the output bit. From the Atmega2560 datasheet:

Toggling the Pin
Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI
instruction can be used to toggle one single bit in a port.

You can modify beginT and endT
// test SPI slave n=1
    SPI.beginTransaction(1, SPISettings(30000000, MSBFIRST, SPI_MODE2));
    SPI.transfer(00001111);
    SPI.endTransaction(1);


text:
Run website / Javascript game from a Arduino UNO device?
I apologise if this is a dumb question, but I'm trying to find information on whether or not this is possible. I'd like to build a arcade machine to play my custom Javascript 2D game. The game currently runs in the browser (of course), but is it possible to execute the code in the Arduino. I'd like to make an arcade machine that runs from the Arduino and connect the game controls to a joystick. Can anyone tell me is this is possible, or any suggestions about how I can achieve this without rewriting the application.
I found the below link that has some information but this is for a PI
https://www.raspberrypi.org/forums/viewtopic.php?t=194808

You're probably better off using a Raspberry Pi (or actual small PC). It is not going to run on Arduino w/o re-writing it to Arduino/C/C++.

The Arduino cannot run Javascript, no.
It could serve Javascript from an SD card to a web browser running on a PC / Pi / Phone, etc, but there is no way it can run it itself.

Thanks for the reply, So it is possible to run the game from an SD card in the browser that would be on the device. I just need to figure out if I can read the input from a joystick and read that input in the browser

There is no browser on an Arduino. The Ardunio would just be a (slow) web server to some other device. Which is pretty pointless, since whatever device it sends the javascript to would be a far better candidate for serving the javascript.

Think about it - you can't even connect a monitor to an Arduino. How could you run a browser? How would you see it?

this is true, thanks for your help. I think the best solution is to run the application from a laptop. But thanks for the fast answer!


text:
Simple code to define pins used for Shift Register control - Error: a function-definition is not allowed here before '{' token
I'm simply trying to light up some pins on a customized circuit board via Arduino.
 My code below has the seemingly common error "a function-definition is not allowed here before '{' token".  I've scoured my code for open/close curly brackets and semi-colons. I also regularly do a quick ctrl+T to format it.  Now I am at a loss - any info/advice greatly appreciated!  The error occurs at the '{' after the 'void loop()' line towards the bottom:
// serially read in 32 bytes at a time to send to shift registers.
// currently updating every 0.1s in Matlab

// Define which pins will be used for the Shift Register control
int dataPin = 2;
int latchPin = 3;
int clockPin = 4;

#include <SPI.h>

void setup()
{
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);

  SPI.setClockDivider(SPI_CLOCK_DIV16);
  SPI.begin();

  //Configure each IO Pin
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);

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

  int seq
  [32] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  int timeElapsed = 2000;
  int timeOld = 0;
  int interval = 100;

  void loop()
  {
    Serial.flush();
    Serial.println('K');
    for (int i = 0; i < 32; i++)
    {
      while (Serial.available() == 0);
      {
        seq[i] = Serial.read();
      }
    }
    digitalWrite(latchPin , HIGH);
    digitalWrite(latchPin , LOW);
    for (int i = 0; i < 32; i++)
    {
      SPI.transfer(seq[i]);
    }
    digitalWrite(latchPin , HIGH); //necessary to tramsit to board
  }

You forgot to close your setup() function.

There's no closing bracket for your setup() function and your loop() function is inside setup(). Close off setup() with a }and then start loop()!

Ahh thank you.  I actually did that before then got a "initializing" error.  But I believe you just mentioning this helped me figure out where to put the "}"


text:
Can I support all these sensors?
I'm new to arduino's and am currently working on a project which requires a lot of different sensors. I was just wondering if its possible to use all the following sensors on a single Arduino Uno:

2 Separate Load sensors (i.e giving different readings) controlled with an load cell amplifier
a Gyro Sensor
an Accelerometer
and an ESC

If its not possible, could someone please tell me what hardware I would need to run all these sensors together. Thanks :).

Did you check what kind of interface they have? And an ESC is not a sensor.

@gre_gor It is... it "senses" a PWM signal from some external source and sets the speed of the motor proportionally ;)

Thanks for the responses! I just included the ESC case it takes up some ports on the Arduino as well. Here is some information on each sensor: The load amp i'm using is a HX711 which outputs VDD to 5v, DAT to port 3, CLK  to port 3 and GND to GND respectively, but I have two separate amplifiers. I'm using a Gyro and Accelerometer in one (MPU6050) which outputs VCC to 5v, GND to GND, SCL to A5, SDA to A4 and INT to port 2 respectivly. The ESC connects to the 5v, GND and port 9.

@Gian.Pit it would be best to edit that info into your question. Comments are ephemeral.

Yes, it should work. The HX711 need two pins each (one for clock and one for shifting out the data). The MPU6050 seems to have an I2C interface, which needs two lines (SCL and SDA). And lastly an ESC uses a PWM pin.
All in all this needs 7 pins, way less than an Arduino UNO has.
Note that having enough pins doesn't mean, that you can usw all the sensors at the same time. You might habe to disable one for a short time to do something else.

you are always only "reading" one at a time in linear programing. But given the list that was provided I do not see any reason that anything would need to be "disabled"   Like, the ESC may only be updated so often, or the gyro/accelerometer might only be read from every so often, but they are still enabled and functioning.

It really depends on how many pins each sensor uses. The signal pins of all the sensors used would have to be equal to or less than the total number of I/O pins on the arduino, which would be 20. So you can control 20 sensors if they each have one signal pin.
However, to control more sensors (or use a lower pin count on arduino) you can use multiplexing. See Two sensors on one input or MULTIPLEXING WITH ARDUINO AND THE 74HC595.
Theoretically, you can control an infinite number of sensors with the use of multiplexing.

You are not taking into account the type of signals produced by your "Sensors"  If you were talking single pin digital sensor("Switch") then you are kinda correct,  there still is no way (even theoretically) you can say you can support infinite number of sensors since you have to be able to address them some how.   But most sensors (like the ones listed in the question) use some sort of protocol, (I2C, SPI, UART) and that greatly effects the number(and method) that can be used by a single uno.

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


text:
'import' does not name type ERROR
I am working with a group of people on an arduino controlled BB8 robot. We are using an IMU unit (accelerometer+gyroscope). I found a processing example for the IMU unit we are using. The code is shown below. I am getting an error "'import' does not name type". I know programming but I am not very familiar with arduino. Can anyone help me?
import processing.serial.*;

Serial myPort;  // Create object from Serial class

final String serialPort = "/dev/tty.usbmodem621"; // replace this with your serial port. On windows you will need something like "COM1".

float [] q = new float [4];
float [] hq = null;
float [] Euler = new float [3]; // psi, theta, phi

int lf = 10; // 10 is '\n' in ASCII
byte[] inBuffer = new byte[22]; // this is the number of chars on each line from the Arduino (including /r/n)

PFont font;

void setup()
{
  size(800, 600, P3D);
  myPort = new Serial(this, serialPort, 115200);

  font = createFont("Courier", 32);

  /*
  float [] axis = new float[3];
   axis[0] = 0.0;
   axis[1] = 0.0;
   axis[2] = 1.0;
   float angle = PI/2.0;

   hq = quatAxisAngle(axis, angle);

   hq = new float[4];
   hq[0] = 0.0;
   hq[1] = 0.0;
   hq[2] = 0.0;
   hq[3] = 1.0;
   */

  delay(100);
  myPort.clear();
  myPort.write("1");
}

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  if (inString.length() == 8) {
    inData[0] = (byte) unhex(inString.substring(0, 2));
    inData[1] = (byte) unhex(inString.substring(2, 4));
    inData[2] = (byte) unhex(inString.substring(4, 6));
    inData[3] = (byte) unhex(inString.substring(6, 8));
  }

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  return Float.intBitsToFloat(intbits);
}

void readQ() {
  if (myPort.available() >= 18) {
    String inputString = myPort.readStringUntil(lf);
    //print(inputString);
    if (inputString != null && inputString.length() > 0) {
      String [] inputStringArr = split(inputString, ",");
      if (inputStringArr.length >= 5) { // q1,q2,q3,q4,\r\n so we have 5 elements
        q[0] = decodeFloat(inputStringArr[0]);
        q[1] = decodeFloat(inputStringArr[1]);
        q[2] = decodeFloat(inputStringArr[2]);
        q[3] = decodeFloat(inputStringArr[3]);
      }
    }
  }
}

void buildBoxShape() {
  //box(60, 10, 40);
  noStroke();
  beginShape(QUADS);

  //Z+ (to the drawing area)
  fill(0,255,0);
  vertex(-30, -5, 20);
  vertex(30, -5, 20);
  vertex(30, 5, 20);
  vertex(-30, 5, 20);

  //Z-
  fill(0,0,255);
  vertex(-30, -5, -20);
  vertex(30, -5, -20);
  vertex(30, 5, -20);
  vertex(-30, 5, -20);

  //X-
  fill(255,0,0);
  vertex(-30, -5, -20);
  vertex(-30, -5, 20);
  vertex(-30, 5, 20);
  vertex(-30, 5, -20);

  //X+
  fill(255,255,0);
  vertex(30, -5, -20);
  vertex(30, -5, 20);
  vertex(30, 5, 20);
  vertex(30, 5, -20);

  //Y-
  fill(255,0,255);
  vertex(-30, -5, -20);
  vertex(30, -5, -20);
  vertex(30, -5, 20);
  vertex(-30, -5, 20);

  //Y+
  fill(0,255,255);
  vertex(-30, 5, -20);
  vertex(30, 5, -20);
  vertex(30, 5, 20);
  vertex(-30, 5, 20);

  endShape();
}

void drawCube() {
  pushMatrix();
  translate(800/2, 600/2 + 50, 0);
  scale(5, 5, 5);

  // a demonstration of the following is at
  // http://www.varesano.net/blog/fabio/ahrs-sensor-fusion-orientation-filter-3d-graphical-rotating-cube
  rotateZ(-Euler[2]);
  rotateX(-Euler[1]);
  rotateY(-Euler[0]);

  buildBoxShape();

  popMatrix();
}

void draw() {
  background(0,0,0);
  fill(255,255,255);

  readQ();

  if (hq != null) { // use home quaternion
    quaternionToEuler(quatProd(hq, q), Euler);
    text("Disable home position by pressing \"n\"", 20, 600 - 30);
  }
  else {
    quaternionToEuler(q, Euler);
    text("Point FreeIMU's X axis to your monitor then press \"h\"", 20, 600 - 30);
  }

  textFont(font, 20);
  textAlign(LEFT, TOP);
  text("Q:\n" + q[0] + "\n" + q[1] + "\n" + q[2] + "\n" + q[3], 20, 20);
  text("Euler Angles:\nYaw (psi)  : " + degrees(Euler[0]) + "\nPitch (theta): " + degrees(Euler[1]) + "\nRoll (phi)  : " + degrees(Euler[2]), 200, 20);

  drawCube();
}

void keyPressed() {
  if (key == 'h') {
    println("pressed h");

    // set hq the home quaternion as the quatnion conjugate coming from the sensor fusion
    hq = quatConjugate(q);
  }
  else if (key == 'n') {
    println("pressed n");
    hq = null;
  }
}

// See Sebastian O.H. Madwick report
// "An efficient orientation filter for inertial and intertial/magnetic sensor arrays" Chapter 2 Quaternion representation

void quaternionToEuler(float [] q, float [] euler) {
  euler[0] = atan2(2 * q[1] * q[2] - 2 * q[0] * q[3], 2 * q[0]*q[0] + 2 * q[1] * q[1] - 1); // psi
  euler[1] = -asin(2 * q[1] * q[3] + 2 * q[0] * q[2]); // theta
  euler[2] = atan2(2 * q[2] * q[3] - 2 * q[0] * q[1], 2 * q[0] * q[0] + 2 * q[3] * q[3] - 1); // phi
}

float [] quatProd(float [] a, float [] b) {
  float [] q = new float[4];

  q[0] = a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3];
  q[1] = a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2];
  q[2] = a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1];
  q[3] = a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0];

  return q;
}

// returns a quaternion from an axis angle representation
float [] quatAxisAngle(float [] axis, float angle) {
  float [] q = new float[4];

  float halfAngle = angle / 2.0;
  float sinHalfAngle = sin(halfAngle);
  q[0] = cos(halfAngle);
  q[1] = -axis[0] * sinHalfAngle;
  q[2] = -axis[1] * sinHalfAngle;
  q[3] = -axis[2] * sinHalfAngle;

  return q;
}

// return the quaternion conjugate of quat
float [] quatConjugate(float [] quat) {
  float [] conj = new float[4];

  conj[0] = quat[0];
  conj[1] = -quat[1];
  conj[2] = -quat[2];
  conj[3] = -quat[3];

  return conj;
}

You can't put Processing code onto an Arduino.

While you could painfully translate this, what you probably want to do is find an Arduino library and/or example for the sensor chip you are using.

Frankly this seems a rather harsh response to a relatively innocent and simple to explain mistake which could nonetheless be quite perplexing when encountered.  Let's not forget that Arduino has shared heritage with Processing and that they are sometimes spoken of together, despite having different syntax and targets.

Processing code is intended to be run on a computer. You would use the Processing IDE to run this code.
The Arduino IDE is used to write, compile, and upload code to a microcontroller that you might have on an Arduino board. This is the cause of the error.

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


text:
Write to EEPROM before shutdown
I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?
The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.

Well I beleive the EEPROM writes are going to happen with a single full byte at a time. So if you are writing single bytes they will either happen or not happen depending on when power is pulled.  If you are recording a float(4 bytes) and power is removed half way through, then if you try and read data back out it will be corrupt. Without knowing the data you are trying to save, or how the device is being used, I cant really give you more advice then that.

Each byte is independent, it's like a snapshot of the current state of the Arduino.

Then I do not believe you will run into an issue with corrupting a single byte, but the problem you may actually be facing is how to know when to save the data. You dont want to write too often as you can eventually wear out the EEPROM, but you want to make sure it gets saved on power down ya?

@ChadG That is correct. I have a slave ATTiny85 that does the power-down through a mosfet.

So the 85 is what is controlling the power to the main board(uno or something)?  Then it can have a pin that tells the main board "im about to shut you down" and data can be saved at that time.

Good idea, shame on me that I didn't think about that

Might I suggest adding a second line between the tiny and the main board, so the main board can tell the tiny it's ready to be shut down. Also, make sure those pins are set back to inputs, before shutting down, or current might flow, through the input-protections diodes on the main board.

According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.


text:
Output pin low used to complete 12V LED circuit?
I have a project that (in part) will drive 3 LEDs where the LED
anodes are at 12V.  The thought is to drive each LED by connecting
each cathode to a 650 ohm resistor, and connect that to an Arduino DIO pin which, when needed, is set to output LOW.  Arduino VIN = same 12V with
common ground.  Am I going to have an Arduino problem of any sort?

Why would you want to do that?  Do you want to switch the LED on/off by changing the digital HIGH/LOW state of the Arduino pin?  If so, no, that will not work.  Depending on the power consumption of the LEDs you could (i) low power, drive directly from the Arduino like in the Blink example, (ii) high power, drive via the same code but with a transistor in between the IO pin and LED.

That doesn't work. When you set the pin to output LOW, then leds will be on (like you want). But if you set the pin to output HIGH, the voltage is 5V, so there is still 7V (12V - 5V) across the leds, and the leds will light up dimly. If you set the pin to input, the voltage at the pin will become around 12V, which exceeds the allowed voltage. The clamping diodes inside the MCU will clamp the voltage to around 5V, so the leds will still be on, dimly, and the internal clamping diodes will die from overheating, potentially destroying the the entire MCU.

The detailed Gerben explanation is the WHY my approach will not work.  Thanx.

No, what you propose will not work. And it risks damaging your Arduino.
Normally you would include a single transistor which the Arduino uses to control the power through the LEDs. This removes the 12V from the Arduino and turns the output into an actual switch.
The problem is that the Arduino's GPIO isn't just a single transistor.  It is (amomgst other things):

Two complimentary transistors (that's the C in CMOS) for HIGH and LOW switches
ESD Diodes
Input buffer

By just adding the one transistor like this:

simulate this circuit – Schematic created using CircuitLab
the 12V is kept well away from the Arduino. Setting the output HIGH will turn on the transistor, allowing the current to flow to ground. Setting it LOW with turn it off, blocking the flow of current and switching the LEDs off.
Further: the Arduino's GPIO has a maximum sustained current of 25mA. Ideally you don't want to even come anywhere near this. By adding the transistor it acts as a buffer and allows you to deal with much higher currents - and hence more, and brighter, LEDs.
Incidentally, R1 in that schematic is there solely to keep the transistor off when the Arduino is not actively driving the output - e.g., when it's either unpowered or is running the bootloader - or you happen to have the GPIO in INPUT mode (as it defaults to).

Thank you.  I am aware of the transistor approach, altho I had not considered the addition of R1 and using a mosfet.  Each Arduino output will be driving only one LED.  My original post was motivated by a desire to minimize the component count needed to drive each LED...and to have a better understanding of Arduino I/O limitations.


text:
Can I disable the TX pin by setting its mode to INPUT while still receiving data on the RX pin of a UART?
I'm using the ATmega328PB in a personal project with MiniCore. My board streams data in on the RX pin from another microcontroller, but my board also has a DIP switch connected to the TX pin, that's used for configuration. My board has already been manufactured, so a hardware solution means a board redesign and extra cost/time.
This DIP switch is connected between TXD (Arduino pin "1") and GND. Upon startup, I read the value of this pin when in mode INPUT_PULLUP. However, when I go to start the Serial, if this switch is in the closed position, it shorts the TXD pin to GND.
Is it possible to disable the TX pin by putting it into INPUT mode while still receiving data on the RX pin?

modify the library

Well, I ended up answering my own question in a few minutes of forum research.
You can disable the TX pin of the hardware UART with:
UCSR0B &= ~bit (TXEN0);


text:
Max current per pin is 40 mA. But it is always 40 mA?
I need to calculate resistor for a PNP transistor.
To do this I need to know the voltage and current.
I know voltage is 5 volts as it is easy to find in the internet,
but how about current? I mean people say the maximum current is 40 mA, but
will it be 40mA? Does the arduino supply 40mA as long as it is able to?
Or for example if i just connect a single diode it magically "calculates" the current it needs and supplies, let's say, 20mA?

voltage depends on source, current depends on load. too much current and the voltage goes down.

Electronics doesn't use magic.

Which resistor? Base or load?

It means that a pin can give (source) at max. 40 mA. However, if a components uses more, than the Arduino cannot give it and as a result the pin becomes unusable.
So you never should exceed 40 mA. And 20 mA is adviced.
+5V and GND pins can take more, however there is also a maximum on 'groups' of GPIO pins. See more information here, below is an excerpt of the page.
However, I doubt that your transistor needs so much, most (if not all) are directly controllable from a GPIO pin and if you need to calculate a resistor value, just make sure you are safely above the minimum current needed to switch the transistor.

That's a great diagram and captures 1/2 of the Notes under the table in section 30 well - there is another section on Sink currents.  To reach the full 300mA of sink  or source current, a Surface Mount 328P needs to be used; the 328P in DIP only provide One VCC and One Gnd pin, and the chips have a max limit of 200mA per per pin, which I have personally confirmed with Atmel Tech Support.  Datasheet can be downloaded here http://www.microchip.com/wwwproducts/en/atmega328p

Figure on driving the PNP hard so it turns in into full saturation.
To do that, you want to pull as much current from the base as you can.
Treat the PNP like it is one diode drop of voltage away from 5V when on.
So 4.3V generally (maybe 4.5, check your part specs).
Then you want the Arduino to sink 20 mA.
4.3V/20mA = 215 ohm resistor.
Use a 200, 220, both are standard values and should well to protect the Arduino output transistors and drive the PNP into saturation.
Maybe go as low as 150 ohm to drive a little harder.
If the PNP needs less to turn on full, go a little higher resistance value.


text:
Connecting 5V arduino logic with 12V car logic

I need to connect arduino to K-Line in my car's OBDII port.
I used an L7805 to power the atmega but how can I interface 12V car logic with 5V arduino logic?
The problem is, the connection has to be bidirectional- sometimes the arduino will pull the line high/low and sometimes the car will - the purpose of this connection is to get throttle, rpm etc. data.
This would be easy if the connection was one directional - I could use a transistor to steer 12V to going IN the K-Line and voltage divider if I wanted to do the reverse. But how to do both?

here they use a voltage divider for the RX and a transistor for the TX.

These bi-directional logic level converters work with 5V and 12V, and cost 0.33CAD: https://www.aliexpress.com/item/4-channel-IIC-I2C-Logic-Level-Converter-Bi-Directional-Module-5V-to-3-3V-For-Arduino/32310628741.html

I found this that may be helpful to you.  this circuit allows for bidirectional communication between automotive K-line ECUs and an arduino.
 K-Line Interface circuit


text:
Are resistors necessary for 8x8 LED matrix?
I was following the official tutorial of LED matrix integration and couldn't figure out why there is no resistor.
I assumed there are built-in resistors in the LED matrix, so I did an experiment by connecting pin 9 of the LED matrix to v5 of my Arduino Leonardo board and pin 13 of the LED matrix to GND of the same board. You can refer to the schematic diagram below to know I was trying to lit up the LED at the position [0, 0].
Unfortunately, the LED next to [0, 0] burned immediately and I still couldn't figured out it.

Question

Are resistors necessary for 8x8 LED matrix?

If yes, why the official example doesn't have any resistor?
If no, why my experiment failed?
If no, why are there so many unofficial examples use resistors for each wire?

Source
https://docs.arduino.cc/built-in-examples/display/RowColumnScanning
Circuit

Schematic

Since the pins of a microcontroller cannot provide much current, they got away without resistors. However, they might be using the chip out of its maximum limits. But as you connected the LED directly to the power source, it delivered all it can.

as per my comment in your previous question, the LEDs are lit only one at a time ... that means that each led is turned on very briefly ... so briefly, that the LEDs do not heat up enough to burn

Well done Arduino, you did a great job providing a magic-smoke tutorial [sarkasm off]. IDK how this tutorial could make it into their official docs, it should not be there!
You definitely need series resistors at each column or at each row to protect the LEDs/GPIOs (that's 8 resistors). There may be matrices that integrate resistors, but your one and the one they use in their docs does not.
An alternative is to configure the column GPIOs as inputs with enabled pullups and the row GPIOs as ordinary outputs. This way, current will be limited by the pullup resistors. But as those are quite large (several 10kOhm depending on MCU) the LEDs will be very dim.

The issue has already been documented: https://github.com/arduino/Arduino/issues/8950

@Mikeologist if they know about the issue already I wonder even more why the tutorial is still online! I'd expect them to know how to drive a simple LED...


text:
Increasing distance of IR remote / transmitter
I am trying to set up my Arduino as a replacement remote control. The setup works and I can use it to turn on/off my things, for example my fan.
However, the working distance is quite short. Around a meter. The actual remote for my fan works across the distance of my apartment.
What can I do to improve the working distance of my Arduino remote? Does the LED need a back reflector or something? Does it need a different LED?
The LED I am using is this, it came in a bundle I purchased.
https://www.amazon.com/dp/B07PJC7WSQ/#detail-bullets

I assume that the led you purchased just isn't as bright as the led that came with your remote.
As I've seen from your link you could quite easily swap the led from the board.
If the new led has the same voltage, the board should work just fine with any other led. Maybe just search for a brighter led with the same wavelength.
I don't think that a back reflector would have such a big effect to boost the range to the distance you need. Also I think it would be rather complicated to install one on the tiny board.

Judging form the picture of the IR breakout board you shown, it seems that the board is drive the LED directly via Arduino GPIO pin. The current of the GPIO pin could supply is typically around 20mA @5v (and about 10mA @3v3) which is not sufficient. A typical 940nm IR LED has the spec like this:
Max. Continuous forward current: 100mA
Max. Forward Voltage: 1.5 typ., 1.8V max.@50mA

In order to drive the LED, a circuitry like this would be required:

simulate this circuit – Schematic created using CircuitLab
Assuming the LED has a voltage drop of 1.8v, and you are supply the circuit with 3.3v, the 18 ohm resistor should limit the LED current to about 83 mA ((3.3 - 1.8)/18 = 83mA) - safely under its maximum rating of 100 mA. Use a 20 ohms if want to be on the safer side. The transistor's emitter must be connected to the Arduino ground.


text:
Any possible way to stack Motor Driver shield L293D with Xbee Shield v03 on arduino?
So i am trying to stack these two shield on arduino, now the problem here is that i guess there is a conflict between the pins of arduino being used by both shields, so can anyone suggest a solution?

the XBee uses Serial on 0,1 (conflict with USB). the motor shield doesn't use the Serial pins. why do you think there is a conflict between shields?

Read the documentation for both boards. They should list the pins used. Their associated libraries will define variables to which you can assign non-conflicting pins. Review the sample code provided as well. Usually, the sample code included setting the pins to use, even if the code only sets them to their default.
There is another possibility. I don’t think this is the case, but I’ve run into this issue with different shields. If the shields use I2C, they may need to have jumpers shorted to set an address.


text:
ACS712 Module inaccurate reading in some devices
I'm currently trying to isolate what's the problem with a current sensor build I'm working on right now. I'm using a ACS712 that can handle 30A, I've used the code at
http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-arduino-ac-current-tutorial/
And so far for certain devices like pencil sharpeners, computers, chargers, and other household devices the amperage readout seems is "correct" there's some minor error due to the noise I assume.. There's like .10 amperage difference. But when I plug in a stereo amplifier the error sky rockets to 1 Amp to even 2 Amps and I'm not quite sure what's the problem, I've also tried multiple codes online and all of them reach the same conclusion.
Thanks,

how do you know that there is an error?

I use an amp meter to detect if the current matches, and the readout does not match therefore an error


text:
Webpage values wont update
I've been trying to run the following esp32 LED PWM code to change the LED's brightness, and show the current PWM duty on the webpage, but the PWM values on the webpage won't change until I hit the submit button twice.
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
WebServer ser(80);
int s=0;
String k;

String iso()
{
  k="
LED PWM<FORM action=\"/\" method=\"post\"><input type=\"text\" name=\"duty\">
 <input type=\"submit\" value=\"Submit\">Cureent Duty=";
  k=k+s;
  k=k+"
";

  return k;
}

void root()
{
  iso();
  ser.send(200, "text/html", iso());

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());
  }
}

void setup() {
  Serial.begin(9600);
  ledcAttachPin(33, 4);
  ledcSetup(4, 5000, 8);
  WiFi.begin("ssid", "pass");
  Serial.print("\nConnecting To WiFi");
  while (WiFi.status()!=WL_CONNECTED)
  {

    Serial.printf("\n.");
  }
  Serial.print("\nConnected");

  ser.on("/", root);
  ser.begin(80);
}

void loop() {
  ser.handleClient();
}

Here's a GIF addressing the issue

upvote for visually demonstrating the issue

When the client sends you a request, you should answer only once. Your
root() function attempts to answer twice whenever the request contains
the argument “duty”. The client will not handle a duplicate response to
a single request.
Here is your root() function:
void root()
{
  iso();
  ser.send(200, "text/html", iso());  // ← first response

  if (ser.hasArg("duty"))
  {
      iso();
      s=ser.arg("duty").toInt();
      ledcWrite(4, s);
      iso();
      ser.send(200, "text/html", iso());  // ← second response
  }
}

You may notice that the first response was sent before updating the
duty cycle.
The proper way to handle the request is to first handle the request
parameters, if any, then send the response:
void root()
{
  if (ser.hasArg("duty")) {
    s = ser.arg("duty").toInt();
    ledcWrite(4, s);
  }
  ser.send(200, "text/html", iso());  // ← only sent once
}

As a side note, there is absolutely no need to build the response five
times (you have five calls to iso() within root()) when you only
need it once!

I'm such an idiot ! ;P thanks a lot.


text:
Use Arduino Uno as 5V Power Source for Sensors Connected to ESP32 Microcontrollers
I am using an ESP32 WROVER B based microcontroller, which has 3.3V and 5V outputs. Due to poor soldering of the header and attempted removal of the solder (permanently damaged PCB etching electrical contacts around the 5V pin), the 5V pin doesn't output any current, so only the 3.3V works (e.g. lights up a LED). Some of my modules require 5V to work properly (according to their specification) e.g. sensors. Can I provide a 5V power source from another component (e.g. arduino uno 5V output, USB to TTL converter 5V power output or USB power supply) for these or use a GPIO output (I believe these are 3.3 volts only) on the ESP32 device itself, perhaps with level shifting? The ESP32 is powered via USB and no issues there (serial monitor shows it boots up okay).

I would suggest soldering a wire to the 5V pin of the 3.3V regulator, but it sounds like your soldering skills are not up to such a task. Yes you can use power from anywhere you like - just remember to connect the grounds.

A level shifter doesn't magically convert 3.3V to 5V. It takes 3.3V logic signals, and uses a 5V power supply to amplify the signals to 5V. A 3.3V to 5V level shifter requires a 5V external power supply. Second, the GPIO lines on a 3.3V device like an ESP32 will be 3.3V, and very low current. Even if there was a 5V logic pin available, you should not try to use it for 5V power. You need some regulated 5V external power source. A USB power supply, another Arduino, discrete 5V power supply, etc.

Note that using an Arduino Uno as a 5V supply is a poor choice. it needs a 7-12VDC input to it's regulator, and then uses a fairly inefficient linear regulator to regulate that down to 5V. It would also sit their running but doing nothing. Buy a cheap 5V regulated power supply that runs from mains power and be done with it.

you have a development board with esp32 microcontroler. the board has power outputs, not the MCU


text:
Arduino piezo-buzzer melody for car alarm
I would like to play car alarm sound through Arduino buzzer - something like this https://youtu.be/nuPHwijMsIg
Does anybody have a library for such melody?

why would you need a library? ... arduino has tone generation capability

I think what you're really asking for is a library of sounds (in the form of code), rather than a code library in the normal sense.  I'd like such a thing too (specifically a retro-gaming style laser noise), but extensive googling hasn't found anything, though someone has made a sketch of the Tetris theme.
A car alarm is probably fairly easy - a couple of for loops changing the frequency of a tone(); My Arduino and piezo buzzer are at home but playing that YouTube and using a spectrum analyser app on my phone it looks like (using the waterfall display mode):

The first alarm is looping from 1000Hz to 2200Hz over about 250ms, then back down again.  - The next 2 are falling tones, from 1kHz down to about 500 over 250 or 500ms.
Then we've got a rising tone 500 Hz to 1kHz  over 2s
A beep at about 2.2kHz, 250ms on/off
A two-tone siren at 1 and 1.5kHz, 1s of each.

Times and frequencies were indeed a little off, and many of the frequency ramps aren't linear, but here's something to play with.  The more interesting alarms are in there, along with a couple of laser zaps.  The square-wave drive of a piezo (leading to interesting harmonics), and the complete lack of a low frequency response (nothing below about a few hundred Hz on the one I have here) limit things a little, but it compares well to a Lego siren I have
int beep_pin=10;
int gap=1000;

void setup() {
  // put your setup code here, to run once:
  pinMode(beep_pin, OUTPUT);
}

void zap1()
{
    for (float f=3000;f>40;f=f*0.93){
    tone(beep_pin,f);
    delay(10);
  }
}

void zap2()
{
    for (float f=3000;f>10;f=f*0.85){
    tone(beep_pin,2*f);
    delay(5);
    tone(beep_pin,f);
    delay(5);
  }
}
void risefall()
{
  float rise_fall_time=180;
  int steps=50;
  float f_max=2600;
  float f_min=1000;
  float delay_time=rise_fall_time/steps;
  float step_size=(f_max-f_min)/steps;
  for (float f =f_min;f<f_max;f+=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
   for (float f =f_max;f>f_min;f-=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void fall(float rise_fall_time)
{
  int steps=50;
  float f_max=2000;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=0.97;
  for (float f =f_max;f>f_min;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
}
void rise()
{
  float rise_fall_time=2000;
  int steps=100;
  float f_max=1500;
  float f_min=500;
  float delay_time=rise_fall_time/steps;
  float step_size=1.012;
  for (float f =f_min;f<f_max;f*=step_size){
    tone(beep_pin,f);
    delay(delay_time);
  }
  noTone(beep_pin);
  delay(100);

}

void twotone()
{
  float f_max=1500;
  float f_min=1000;
  float delay_time=800;
  tone(beep_pin,f_max);
  delay(delay_time);
  tone(beep_pin,f_min);
  delay(delay_time);

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

  for (int count=1;count<=10;count++)
  {
    risefall();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=10;count++)
  {
    fall(300);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<=5;count++)
  {
    fall(600);
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    rise();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<5;count++)
  {
    twotone();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap1();
  }
  noTone(beep_pin);
  delay(gap);
  for (int count=1;count<10;count++)
  {
    zap2();
  }
  noTone(beep_pin);
  delay(gap);
}

It's also on GitHub, and released into the public domain under the unlicense so anyone can use it however they like

https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody See this example to get the code for each musical note. It should work very well!


text:
How safely write to SD or Eeprom on Arduino power off
I want to constantly store data to sd. But how I make sure data is not corrupted on moment of power off? I think I could add small capacitor on 5V and check when voltage drops, so I would stop data write. Or is there better solution for safe data write?

I think a "small" capacitor here is not going to do the job as you need to keep power stable until the write is completed.  You need to determine:

How much power am I using?
How quickly can I detect a power outage?
How much time do I need to keep power on the Arduino to complete the write operation(s) I want to complete.

Then you will be in a position to calculate how much capacity you need and whether a capacitor or battery is more appropriate.

well data is written in probably microseconds, so I 3300uF or something would be enough for short period of time. Question - is that proper way to do it? Discharging capacitor will reduce it's voltage, so I have no idea what could happen

You're just guessing on both how much time and how much reserve you need.  Take measurements and do calculations.  That's engineering.

Also calculate the odds of having a power outage, right when you are writing to the SD card. If you, for example, only write once every 15 minutes, the odds are very low. Combined with the chance of a power outage, it might not be worth you time to try to prevent.

You're probably going to want to look to various forms of NVRAM (Non-volatile RAM).  SRAM with an automatic save to EEPROM function on power loss, e.g. 47L16.  Or battery backed RAM; if you have a real-time clock in your project you may have some limited storage in it.  E.g., the DS1307 has 56 bytes, although you can probably find a more accurate RTC that has storage in it.  Or FRAM, though it's as bit expensive, e.g. cy15b064q-sxet
In any case you'd probably want to write your data out in blocks with CRC so that you can make a determination on whether or not a partial write was done when reading back later.


text:
DIY Arduino with USB port
I am planing on making Arduino from scratch. I found many examples on internet, but they all need another Arduino for programming. How can I make Arduino with USB interface for programming and serial data transfer? Would I need something called FTDI? Basically I want same Arduino you can buy, just build it from separate parts.

If your atmega328 isn't preloaded with bootloader firmware, you need a programmer (which can be an arduino running a special sketch). And you need some USB to TTL-Serial, which can be an FTDI or CP120x or CH340 or similar.module.

There are two critical things that make an "Arduino". There is the hardware, and there is the bootloader.
The hardware is nothing special. It's just an MCU and the required minimal support hardware. What really makes it an Arduino is the bootloader which allows it to be programmed over the serial connection (via USB usually).
Without that bootloader the only way to program the MCU is over the hardware programming interface (typically ICSP for an AVR MCU), and for that you need some form of hardware programmer.
And of course that means the only way to put the bootloader onto the chip is to use a hardware programmer.
So you have two options:

Program the bootloader into the chip using a hardware programmer (which you can make with an Arduino), or
Buy an ATMega328P chip with the bootloader pre-programmed.

Once you have the bootloader installed then yes, you can program the chip over UART (through USB with a USB to UART adaptor such as an FT232).


text:
Very weird bug / odd behavior of OUTPUT
So, I have this code (Arduino Mega):
void setup()
{
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);

  analogWrite(10, 50);
  analogWrite(11, 50);
}

very basic motor speed control. Now when I do this (nothing else is connected to board, only 10 and 11 PWM control pins):
void setup()
{
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);

  analogWrite(10, 50);
  analogWrite(11, 50);
  digitalWrite(6, 0);
}

motors stop. As if those analogWrites are ignored. Is this some exteption about Arduino board? Or is it just a bug? Again, nothing else is connected. Only 10 and 11 PWM outputs. Pin 6 is free. I tried puting digitalWrite above analogs - nothing.

what does this mean? ... I tried puting digitalWrite above analogs - nothing.

Is it a genuine Arduino or a cheap Chinese knock-off?

Chinese. But does it matter?

How are you measuring the PWM output? With an oscilloscope?


text:
How to offset PWM output so it would also have negative amplitude?
So PWM goes from 0 to 5V. How could I do -2.5 - 2.5V? Basically I am asking how to add offset to PWM signal. Should I use operational amplifier? How would I use it? I never had to deal with them, but I have LM2904P laying around.

You could use an op-amp as a comparator, but you would need to supply it with suitable power rails. Your question may be more appropriate for https://electronics.stackexchange.com/

@ EdgarBonet's and @ st2000's responses are perfectly appropriate. But to clarify for future readers (and hopefully not confuse anyone): the PWM output is not a voltage but a wave form with a duty-cycle ranging from 0% to 100%, and as such, is not able to take on negative values. That waveform can be converted to a voltage (a step that was understood but not included in the question and the replies); the resulting voltage can have whatever range one designs into the conversion circuit.

Consider removing the average of the PWM voltage by subtracting the Direct Current (DC) component of the PWM output.
Often, between different audio amplifiers stages, the DC component of the signal is removed through the use of coupling capacitors. The above link offers these guide lines for picking the value of the capacitor:

Below is a basic rough guideline of capacitors that can be used for
various frequencies.
For coupling a 100Hz signal, a 10μF capacitor can be used.
For a 1000Hz signal, a 1μF capacitor can be used.
For a 10KHz signal, a 100nF capacitor can be used.
For a 100KHz signal, 10nF capacitor can be used.
For a 1MHz signal, a 1nF capacitor can be used.
For a 10MHz signal, a 100pF capacitor can be used.
For a 100MHz signal, a 10pF capacitor can be used.
This is a rough estimate that will be effective the majority of the
time. The only variable that could affect the above values is the
resistance in parallel to the capacitor.

Consider the last paragraph above when designing your circuit.  The lower the input impedance of the circuit you are driving the more likely the possibility of unexpected results.  At which point you might consider adding the OpAmp suggest in the question.


text:
Arduino IDE upload error
I've recently been trying to make program using IRremote(library) in my Arduino IDE(v1.8.9), but whenever I hit the upload button this error message is returned

Sketch uses 7514 bytes (23%) of program storage space. Maximum is
  32256 bytes. Global variables use 415 bytes (20%) of dynamic memory,
  leaving 1633 bytes for local variables. Maximum is 2048 bytes.
avrdude: verification error, first mismatch at byte 0x0002
0x5d != 0x62 avrdude: verification error; content mismatch
avrdude: verification error; content mismatch

I'm using Arduino UNO R3
This is the code I'm trying to run
    #include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode(&results))
    {
     Serial.println(results.value, HEX);
     irrecv.resume(); // Receive the next value
    }
}

Also, every other code(not using the IRremote library) uploads just fine without any errors.

Is it a genuine Arduino or a cheap Chinese knock-off?

There can be power/connection problem or somehow the bootloader has been damaged.
So

Check power
Check Connection

If there no problem found, then by using usbasp, avrisp, usbtinyisp, etc reflash the bootloader. I hope your problem will be solved.


text:
Change From One State Machine To Another
I have a project where I need to state from leds turning on and off to another one that will have all the leds turned on and send data and I was wondering how should I do that, this the code I have:
#include <CapacitiveSensor.h>

CapacitiveSensor cs_11_10 = CapacitiveSensor(11,10);

int state_s1 = 0;
int state_s2 = 0;
int state_s3 = 0;
int state_s4 = 0;
int state_prev_s1 =0;
int pin_s1 = 12;
int val_s1 = 0;

const unsigned int ledPins[]={2,3,4,5,6,7,8,9};
const unsigned int lenledPins=9;

unsigned long t_s1 = 0;
unsigned long t_0_s1 = 0;
unsigned long t_s3 = 0;
unsigned long t_0_s3 = 0;
unsigned long t_0_s4 = 0;
unsigned long t_s4 = 0;
unsigned long t_s2_4 = 0;
unsigned long tiempo = 250;

unsigned long bounce_delay_s1 = 5;

long total = 0;

void setup()
{
  pinMode(pin_s1, INPUT_PULLUP);
  Serial.begin(9600);

  for(int i=0; i<(9); i++)
  {
    pinMode(ledPins[i], OUTPUT);
  }

  cs_11_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
  Serial.begin(9600);

}

void loop()
{

  MBoton();          //MAQUINA DE ESTADO

 MaquinaGeneral();

  if(state_s2 == 1)
  {
    led();
  }

  if(state_s1 != state_prev_s1)
  {
    Serial.print("state =");
    Serial.println(state_s3);
  }

  if(state_s4 == 6)
  {
    for(int i=0; i<lenledPins; i++)
    {
      digitalWrite(ledPins[i],HIGH);
    }
  }

  Serial.print("");

}

void MaquinaGeneral()
{
  switch(state_s2)
  {
    case 0:
    if(state_s1 == 4)
    {
      state_s2 = 1;
    }
    break;

    case 1:

    break;
  }
}

void MBoton()
{
  state_prev_s1 = state_s1;
  switch(state_s1)
  {
    case 0:         //RESET
    state_s1 = 1;
    break;

    case 1:        //START
    val_s1 = digitalRead(pin_s1);
    if(val_s1 == LOW)
     {
      state_s1 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s1 = millis();
    state_s1 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= bounce_delay_s1)
    {
      state_s1 = 5;
    }
    break;

    case 5:         //ARMED
    val_s1 = digitalRead(pin_s1);
    if(val_s1 == HIGH)
     {
      state_s1 = 4;
     }
    break;

    case 4:       //TRIGGERED
    state_s1 = 0;
    break;

  }
}

void led()
{

  switch(state_s3)
  {
    case 0:         //OFF
    for(int i=0; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],LOW);
    }
    for(int i=1; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],HIGH);
    }

    t_0_s3 = millis();
    state_s3 = 1;
    break;

    case 1:         //WAIT
    t_s3 = millis();
    if(t_s3 - t_0_s3 >= tiempo)
    {
      state_s3 = 2;
    }
    break;

    case 2:         // ON
     for(int i=0; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],HIGH);
    }

     for(int i=1; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],LOW);
    }

    t_0_s3 = millis();
    state_s3 = 3;
    break;

    case 3:         //WAIT
    t_s3 = millis();
    if(t_s3 - t_0_s3 >= tiempo)
    {
     state_s3 = 0;
    }
    break;

  }

  }

void Capacitor()
 {

  switch(state_s4)
  {

    case 0:         //RESET
    state_s4 = 1;
    break;

    case 1:        //START
    total = cs_11_10.capacitiveSensor(10);
    if(total >= 1000)
     {
      state_s4 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s4 = millis();
    state_s4 = 3;
    break;

    case 3:         //WAIT
    total = cs_11_10.capacitiveSensor(10);
    if(total < 1000)
     {
      state_s4 = 0;
     }

    t_s4 = millis();

    if(t_s4 - t_0_s4 >= 2000)
    {
      state_s4 = 5;
    }

    break;

    case 5:         //ARMED & WAIT
    t_s2_4 = millis();
    total = cs_11_10.capacitiveSensor(10);
    if(total < 1000)
     {
      state_s4 = 4;
     }

     if(t_s2_4-t_s4 >= 1000)
     {
      state_s4= 6;
     }
    break;

    case 4:       //TRIGGERED
    state_s4 = 0;
    break;

    case 6:     // ARMED 2
    Serial.println("Entro al estado 6");
    total = cs_11_10.capacitiveSensor(10);
    break;

}
}

A quick scan of your code would suggest you have too much going on.  That  or not enough comments to explain your decision to use multiple state machines.  I would start over with only 1 state machine and stick with only 1 state machine.

I don't quite understand, what your problem is with doing so. You have written all these state machines. So  you can just add states for exactly what you want (a state that would leave the LEDs on and would send data). Though I think st2000 is right in that you should check thoroughly if using only 1 state machine would be sufficient. That would be way easier to code.

Also use an enumeration type for the states, instead of 'magic numbers' 1, 2, 3 etc.

I highly recommend you design state machines with a state-diagram showing events, transitions, and actions. They are a whole lot easier to read & understand than any state-machine code I've ever seen or written. When you have a diagram you believe does what you want, then start coding it. Remember to check your state-machine code against the diagram, to be confident your code does what the diagram says it should. The state-diagram should be your working reference. When you debug, debug/fix it on the diagram first, then use that to fix the code. You'll get a working state machine much sooner.

If you think you need two finite state machines, where only one of them
is running at any given time, then it is trivial to combine them
together: draw them side by side, and add the required transitions
between them. The set of states of the combined FSM will be the union of
the states of the initial FSMs. For example, if you have:

FSM 1 states: STATE_A, STATE_B, STATE_C
FSM 2 stages: STATE_D, STATE_E
global states: FSM_1_RUNNING, FSM_2_RUNNING

Then the combined FSM will have the states STATE_A, STATE_B,
STATE_C, STATE_D and STATE_E, and all the transitions of both
initial FSMs.

Similar to what others have commented, this is not the best implementation of a Finite State Machine (FSM). You should establish clear states and define what happens during all transitions of your system.
Follow Edgar's advice on using enumerators for your states.
Nick Gammon's guide will surely be of great help: https://www.gammon.com.au/statemachine