text:
Unable to burn bootloader with avrisp
I want to burn the arduino optiboot_atmega328.hex bootloader but it doesn't work. I remember that I was able to burn the BL using the arduino IDE which was quite easy, this time I'm having some problems.
I'm always using an avrispv2 programmer to flash my atmegas and it was also this programmer I used once to burn the BL. When I try, the IDE gives the following output:
avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/xxx/Downloads/arduino-1.8.7-linux64/arduino-1.8.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/xxx/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Fehler beim Brennen des Bootloaders.

After this didn't work I tried to manually upload the optiboot_atmega328.hex with avrdude on the commandline (following this guide). The output of avrdude is as follows:
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m -P /dev/ttyACM2

avrdude: Version 6.3
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/tabaluga/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : avrispv2
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel AVR ISP V2
         Programmer Model: STK500
         Hardware Version: 10
         Firmware Version Master : 2.10
avrdude: stk500v2_command(): command failed
avrdude: stk500v2_getparm(): failed to get parameter 0x9a
         Topcard         : Unknown
         Vtarget         : 3.3 V
         SCK period      : 17.4 us
         Varef           : 3.3 V
         Oscillator      : Off

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: erasing chip
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0xfd != 0x05
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: efuse changed! Was 5, and is now fd
Would you like this fuse to be changed back? [y/n] y
avrdude: safemode: Wrote efuse to 5, read as fd. 9 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 8 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 7 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 6 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 5 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 4 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 3 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 2 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 1 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 0 attempts left
avrdude: and COULD NOT be changed
avrdude: safemode: Fuses not recovered, sorry

avrdude done.  Thank you.

As I'm unable to set the fuses it's no wonder that the actual upload doesn't work as well:
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U flash:w:optiboot_atmega328.hex -U lock:w:0x0F:m -P /dev/ttyACM2

avrdude: Version 6.3
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/tabaluga/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : avrispv2
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel AVR ISP V2
         Programmer Model: STK500
         Hardware Version: 10
         Firmware Version Master : 2.10
avrdude: stk500v2_command(): command failed
avrdude: stk500v2_getparm(): failed to get parameter 0x9a
         Topcard         : Unknown
         Vtarget         : 3.3 V
         SCK period      : 17.4 us
         Varef           : 3.3 V
         Oscillator      : Off

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: erasing chip
avrdude: reading input file "optiboot_atmega328.hex"
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328.hex:
avrdude: load data flash data from input file optiboot_atmega328.hex:
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0xcf != 0x0f
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:D9, L:62)

avrdude done.  Thank you.

I personally doubt that the µC or my programmer are bricked because I'm able to upload program code via ISP as I always used to, also I've tried two different ATmega328p.
Do you see what I'm doing wrong?
Why does one actually have to change fuses before flashing the bootloader (just curious)?

I can see you are on Linux so I won't give you instructions for using AVR Studio - but do know that if you have access to a Windows machine that is another option you could try.
I can't tell you exactly why it is not working through the Arduino IDE - it could be that the settings are not set correctly or any number of reasons. What I can say is that it is not seeing the AVRISPmkII. Try turning on verbose mode in the Arduino SE settings.
However when using avrdude, you are requesting the efuse be set to 0x05. The value of 0x05 (or b0000 0101) means that you are requesting a brownout detection of 2.7V. But because only the last 3 bits of the fuse are relevant, the chip fills the rest of the bits with 1 not 0. So b0000 0101 (aka 0x05) becomes b1111 1101 (aka 0xFD), hence you get a mismatch.
Also, according to my \Arduino-x.x.x\hardware\arduino\avr\boards.txt file, the fuses for the Arduino/Genduino Optiboot are:

low_fuses=0xFF
high_fuses=0xDE
extended_fuses=0xFD

Change your avrdude command to the following:
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDE:m -U lfuse:w:0xFF:m -P /dev/ttyACM2

The last block of output in your question shows that you are trying to load the optiboot hex file. That part works so it seems, as it writes and verifies successfully. The interesting part is the lock bit fails verification. It is reading 0xCF which means it is in bootloader protection mode #3: LPM and SPM prohibited in boot loader section.
From the datasheet:

SPM = Store Program Memory instruction
  LPM = Load  Program Memory instruction

And

SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.

But it appears that these lock bits can be removed by doing a chip erase:

The Boot Lock bits can be set in software and in Serial or Parallel Programming mode, but they can be cleared by a Chip Erase command only.

And

The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are not reset until the program memory has been completely erased. The Fuse bits are not changed. A Chip Erase must be performed before the Flash and/or EEPROM are reprogrammed.

So it looks like you need to do a full chip erase with avrdude.

For reference I use the following fuse calculators:

http://www.engbedded.com/fusecalc/
http://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p


text:
How to show the º character in a LCD?
I have a 16x2 LCD and I want to show a temperature: 23 ºC.
But the º symbol is not properly shown. It shows a strange character instead of the º symbol .

Some displays have different characters above 128. It is best to make your own character.
That is what @dannyf ment with "CGRAM". The custom characters are stored in CGRAM. There is no need to read the datasheet though, because there is a function in the Arduino LiquidCrystal library for it.
Start here: Arduino CreateChar reference
There are even websites that help you to create the character: omerk and maxpromer.

Easy.

Pull up the datasheet and pick the character that most resembles your symbol. Char 0b11011111 looks the best to me but 0b10110000 isn't bad.
While you are in the datasheet, check out CGRAM.

do lcd.write(223);
Transform the Decimal into an ASCII symbol.

source: Stack Exchange

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

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

sort: votes


text:
Should I buy a retired Arduino?
I am a beginner who would like to buy an Arduino Yún (58 dollars).
It is retired so will I have any problem?
Else I can buy an Arduino Uno and an Arduino Yún Shield. But in this case I don't understand the difference between an Arduino Uno + Arduino Yún Shield and an Arduino Uno + ESP8266 serial WIFI wireless module.
Arduino Yún Shield: I can't find the price. I only found an Iduino.

ESP8266 serial WIFI wireless module: 7 dollars.

The yun has a coprocessor running a compact embedded linux distro, while the esp8266 is a simpler MCU running bare metal software or at most an RTOS.  Cost wise the latter clearly wins, though you seem to have been quoted quite a markup for it.  But your basic question is "primarily opinion based"

Yún has ethernet and USB. Which may or may not be interesting. You should get what you need, and only more if you can afford it. You could do an Arduino Uno  & ESP8266 & rasperry pi. For thuis combo there is an elaborate amount of tutorials, and will learn you about both microcontrollers and single board computers.

When a board is retired, it may:
- get no support (never had support from Arduino zelf though)
- not be readily available.
Which may or may nog be a problem.
The biggest problemen with retired boards is that they often didn't sell very well.
So they may:
- target niche applications.
- not have a lot of people post tutorials on it.
- not have/get elaborate answers on Arduino.se
I believe you should only get something that fits your needs.
Usually you van get away with an Uno, and since there are millions if (beginner) tutorials, i'd pick that as my first Arduino.
If you want to do anything more "pc-like" like USB, camera or a "server", my first pick would be a raspberry pi.
Also, since there are hundreds of tutorials.
You can choose to do it with a yún, and it may work, but you should check if there are tutorials/documentation for whatever you'd like to do with it.

It is retired so will I have any problem?
It depends on what you want to do with your arduino. If you need a project that requires future support then dont buy a retired board. If you just want to do basic beginners stuff (like blinking LEDs, controlling motors, sending serial information wired or with an add on shield to send wireless information)-then any arduino can do these basic projects and probably at a cheaper price than 58 dollars.

The question of the Arduino Yun being retired can be answered here:
http://www.arduino.org/forums/yun/retriered-boards-894?p=3495&hilit=Retired#p3495
At least regarding Arduino.org the answer is no. The Yun is not retired.

The Yun has also been recently moved from the retired section of the arduino.cc products page to the active products chart. I think this is a result of the dispute between .cc and .org being settled.

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


text:
Is my MQ-2 gas sensor analog or digital?
I have this MQ-2 gas sensor for an Arduino Uno:

I found these two articles about how to use it:

https://create.arduino.cc/projecthub/Aritro/smoke-detection-using-mq-2-gas-sensor-79c54a
http://www.instructables.com/id/Ardunio-Smoke-And-Gas-SensorMQ-2/?ALLSTEPS

But I need to know if the sensor is analog or digital.
Also I would like to know what is the blue switch for.
This questions help me a bit:
It says that he use an analog sensor. But as this sensor is not mine I don't want to brake it or burn it.

Your sensor is analog. I have the same one. By the way, there is no chip on board, so it cannot form a digital signal ;)


text:
What's the difference between CloudTemperature, CloudTemperatureSensor and Float data types?
I have a SHT30 sensor for Wemos and I am learning to use Arduino IOT Cloud.
I use float data type for my temperature variable but I see two more data types:
CloudTemperature
CloudTemperatureSensor
What are the differences? Shouldn't use float?

From the technical reference for the Arduino Cloud on arduino.cc:

For your convenience, IoT Cloud provides specialized types which are just wrappers around basic types but declare the variable semantics more explicitly. This enables smarter integrations with third-party services (such as Alexa) and better visualization of widgets in dashboards.
You can use them just like a normal variable of the wrapped type, since they support assignment and comparison operators.

These types are actually wrapper classes, which add some functionality to better integrate in cloud services. You can use these just as the normal data types.

You can even look at how they are defined. Let's look at CloudTemperature for example. All the files can be found in the ArduinoIoTCloud repo on github.
The types are defined in the PropertyContainer.h file:
...
#include "types/CloudFloat.h"
...
typedef CloudFloat CloudTemperature;
...

So CloudTemperature is actually just CloudFloat, which is included from the corresponding header file. When we look at the CloudFloat.h file we find:
class CloudFloat : public Property {
  protected:
    float _value,
          _cloud_value;
...

So internally CloudFloat is just a float value with added functionality. And you can use it like any other float, since below that part that I've shown here all the operators (like /, *, +, ...) are overwritten (so the class knows what to do with these operators).
CloudTemperatureSensor is found at CloudTemperatureSensor.h and inherits from CloudFloat so works basically the same way (it only overwrites the assignment operator; the rest is the same as CloudFloat).

Shouldn't use float?

I haven't tried that myself. But from the documentation it sounds like there is no reason to not use the specialized types, since they provide the same functionality and more.

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


text:
Wemos: relay shield doesn't work on top of the stack
I connected a SHT30 shield to a Wemos D1 mini (one on top of the other) to measure temperatures.
Wemos D1 mini (2.3.0):
SHT30 shield:
It works great but when I added a relay on the top of the stack it doesn't work anymore.
Relay shield:
Maybe there are a conflict with their pins. So these are their schematics:

This is the solution that I made but I don't know why this works instead of inserting the relay shield on top of the SHT30 shield:

Yes, there is a pin conflict.  The relay uses D1, however D1 is (as you can see from looking at the schematics) part of the I2C connection for the SHT30.
You will have to find some way of modifying the relay shield to use a pin that's not part of I2C.


text:
arduino will not save data after receiving from serial communication
I'm new to Arduino and what I'm trying to do is change the variable by sending it from php to the Arduino.
I've added the delay as stated by other questions but it has not worked so far. The pin 13 LED so
Arduino Code
float val;
void setup() {

  Serial.begin(9600);

  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
  val=29.1;

  Serial.println("Start!");
}

void loop() {

  if(Serial.available()){
    String temp = Serial.readStringUntil('\n'); //read string
    val = temp.toFloat(); //convert string to float
  }

  if(val==62.10){
    digitalWrite(13,HIGH);
  }else{
    digitalWrite(13,LOW);
  }

  Serial.println(val);
  delay(1000);

}

PHP Code
<?php
$port = fopen("COM3", "w");
sleep(2);
fwrite($port, "62.1");
fclose($port);
?>

Any tips would be much appreciated. Thank you for reading.

Comparing floats like that is never a good idea. There's no such thing as 62.1 as a floating point - the closest is 62.09999847412109375. Floats are only ever an approximation.

I see. Luckily for me, the comparison is only used for debugging. @Majenko

You typically use abs(val - 62.1) < 0.05 where 0.05 is the 'accuracy you accept, so values between 62.05 and 62.15 are resulting in true

You are writing "62.1" but you are trying to read up until a \n, which you never send.
You need to ensure that you send the end-of-line character that you subsequently check for,
fwrite($port, "62.1\n");

Also it's worth noting that floating point values are only ever an approximation. They're great for doing calculations, but very poor at doing comparisons. Your test value of 62.1 cannot be represented precisely as a floating point value, the closest being about 62.099. If you do need to do a comparison then you should check it's within a small range, not a precise value.

Your "problem" seems to stem from you opening the serial port with one program, sending a value, then closing the serial port and opening it again in something else and expecting to see that value being echoed back to you.
That can't happen on a stock Arduino UNO. Every time you open the serial port the DTR line toggles the RESET pin to enter the bootloader - which is why you need the 2 second delay after opening the serial port.
In doing so the sketch then runs fresh every time you open the serial port.
There are a number of ways of disabling that reset, from cutting a trace on the Arduino, to adding a large-ish (10µF +) capacitor between RESET and GND - both of which will interfere with your ability to program the board. The capacitor is the easier to reverse.
Ideally you'd use a different serial channel to communicate so it never interferes with the reset or programming. You could use SoftwareSerial and an external USB to UART adaptor instead of the Serial connection, or use a board with a native USB connection that doesn't reset when you open the serial port, such as a Leonardo.

I have added the \n to the fwrite and applied the changes. It seems that Arduino resets and is unable to read the previously sent value.

Every time you open the serial port the Arduino resets, yes. That's what it does. There's plenty of writeups about that functionality and how to avoid it. Mostly they involve hardware changes.


text:
Multiple arduino slaves with one master computer that sends instructions for the actuators to work
I am in the middle of an automation project and suddenly after completing one stage of my assembly, I now need to scale it. So my computer which until now was sending data to only one arduino UNO can send to multiple arduino uno's, also I am seeking an advice, I am using up all the digital pins on my arduino Uno and this makes me think if I should upgrade to arduino mega or leave it the way it is.
The communication protocol I am using is UART which is done through USB from my computer to the board, so can I just use a USB hub to handle this issue?

If you’re sure that you won’t expand your project and need more pins, why upgrade? If you have lots of free analog pins you can use them as digital pins too.

Yes, if course you can use a USB hub to connect multiple Arduinos to your PC at once. If you need to upgrade to a mega depends on if you need more pins

Thank you so much I definitely not need more pins on one communication as the more the messy it gets thats why I tried sticking to Uno to the least, I would rather get multiple unos so troubleshooting doesn't become a challenge.


text:
When does interrupt get fired
When does the ISR mapped to SPI_STC_vect (SPI transmission complete) get fired? Does it fire after a byte has been received (eight clock cycles) of when the slave select changes back to high to deselect the slave?
Or: does "transmission" mean the transmission of a byte or the whole bunch of bytes that belong to the command sequence?

It fires after a single byte has been sent or received (the two are one and the same). This is because there is only room for one byte in the buffer, so you need to get it out of that buffer (or put a new one in) after each 8-bit transfer.


text:
Esp32: upload eeprom file
I'd like to flash the eeprom sector with content so that the eeprom already holds data when it boots the first time.
How do I upload such an eeprom file like I would do with avrdude on an atmega? Is there a tool that can be installed in the arduino IDE like the data uploader?

esptool can download and upload any region of the esp flash

@Juraj I can't find any dedicated command line option. Like, for my atmega I would use something like -U eeprom:w.... Do I have to find the address offest myself and if so, where? Actually, where do I find the actual partition table the arduino IDE uses?

I said "flash". the esptool command is read_flash and write_flash. I don't write an answer, because I never tested that.

The ESP8266 has no EEPROM.
Instead the flash memory is partitioned into different areas for different purposes. One of those areas is set aside for "EEPROM Emulation" data.
To upload to that area you first need to know where that area is in the flash memory, and that is dependent on what partitioning scheme you are using at the moment.
Once you have worked that out (look in the partition scheme files in the core for more information) you can then use esptool to upload data to the right area of flash.

@Juraj I did, yes, but technically I am also correct saying it has no flash, since it relies on an external flash chip :)


text:
make EEPROM.h use custom eeprom partition
I created the below partition table for an esp32 and replaced the 'default_8MB.csv' with it.
# Name,   Type, SubType, Offset,  Size, Flags
nvs,      data, nvs,     0x9000,  0x5000,
otadata,  data, ota,     0xe000,  0x2000,
app0,     app,  ota_0,   0x10000, 0x330000,
app1,     app,  ota_1,   0x340000,0x330000,
eeprom,   data, 0x99,    0x670000,0x1000,
spiffs,   data, spiffs,  0x671000,0x18f000,

After uploading a sketch, I confirmed that the partition table was correctly uploaded to the flash at address 0x8000, using esptool.py --port /dev/ttyACM1 read_flash 0x8000 0x300 partition_table.bin && gen_esp32part.py partition_table.bin && cat partition_table.bin.
Now my question is: what do I have to do so that the EEPROM.h library maps the eeprom emulation to the address that I have specified in the partition table? I naively assumed that EEPROM.h would automatically use the partition named "eeprom", which doesn't seem to be the case.
I uploaded the following test sketch to analyse the situation:
#include <Arduino.h>
#include <EEPROM.h>

String s="this is a unique string";

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

  for (uint32_t i=0;i<s.length();i++){
    EEPROM.write(i,s[i]);
  }
  EEPROM.commit();
  Serial.println("EEPROM stored");
}

void loop() {
  delay(10000);
}

After the sketch has stored my unique string I read the flash memory using esptool and expected to find the string at an offset of 0x670000, but that wasn't the case. Instead it must be stored somewhere else because I can retrieve the string in a different sketch.
One thing that is confusing me: I'm pretty sure that I once ordered ESP-WROOM32s with 4MB flash, but the esptool's auto-flash-detection states that my board has 8MB. Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32? What is supposed to happen if I created a partition table that exceeds the flash memory size? When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).
My main question: which additional steps do I have to take to get my ESP running with a custom_partion_table.csv (beside creating the table) and when using "EEPROM.h"?

EEPROM.h looks up the partition location by name. More specifically, it uses the SDK call nvs_open to open the partition named eeprom. So it should be stored at the right location.

EEPROM on the ESP32 doesn't work like you would expect.  It uses the SDK's "Non-Volatile Ram" storage system to store the data within the nvs partition.  This works through a system of "Key / Value" pairs, and the data is stored as a "BLOB" (Binary Large OBject) for the key eeprom in the namespace eeprom.
Quite what the internal layout of the data within the partition itself is I have no clue (the SDK is closed source), but it won't just have your string located at the start of the partition - it will be at the start of the BLOB, wherever that happens to be in the partition.
The eeprom partition is no longer used. It's just wasted space.

Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32?

I can't comment on that I'm afraid. I would have thought it would look at the chip's JEDEC data, but it may just look at the partition table information instead.

What is supposed to happen if I created a partition table that exceeds the flash memory size?

Probably not a lot, since much of the partition table refers to data storage, or a (presently) unused OTA partition.
When you compile your code you're only compiling it for the partition in which it will reside (app0 for example). When you upload the code you are only uploading to that partition.  Anything outside that range is irrelevant to the compilation / uploading.

When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

As I mentioned, it won't care. The partition will not be accessible, since it doesn't actually exist, but it's just an entry in a table. The compiler doesn't know or care what it is.

"it will be at the start of the BLOB, wherever that happens to be in the partition" - until now I had this working the way I expected (the EEPROM structure was just like in my sketch), but unfortunately I had to update the arduino IDE and now the partition scheme I used to work with does no longer exist... How do you upload the eeprom content?

@SimSon I guess the core changed from manually working with the flash chip to using the SDK's built in system. Makes it simpler for the core to implement, but harder for the user to do low-level stuff.  Best to leave EEPROM as internal to the sketch only, and if you want to have data that you can upload from outside a sketch then use SPIFFS.

I'm a bit confused, how do I use "SPIFFS from outside"? What does esptool.py [...] write_flash [...] do (does it depend on the partition type I'm uploading to)? As I understand, I can upload any data to arbitrary memory locations, so what does that have to do with SPIFFS, EEPROM or whatever partition I'd like to write to? On the other hand, what implications does it have to use "SPIFFS from outside"? I seem to lack some important understanding, but I don't know where...

SPIFFS is a filesystem stored in a flash partition. There are tools to create and manipulate an SPIFFS filesystem image on the computer, which you can then upload to the ESP32 at the correct memory location for your SPIFFS partition.

Sorry, I still don't understand: why can't I simply upload the persistent data (which I'd like to access via EEPROM.h from within the sketch) using the esptool like I did until now?

and do I actually need a partition named "eeprom" when I use EEPROM.h in my sketch? If no, where would EEPROM.h emulate the eeprom instead? In SPIFFS maybe?

You can't because the data is formatted in a different way with the current version of the core. And yes you absolutely need a partition named eeprom when you use EEPROM.h in your sketch.

So, on my computer I need to create a SPIFFS partition (which is formated like the eeprom partition that EEPROM.h expects) and then I have to upload this SPIFFS partition to the address of my eeprom partition on the esp? Did I get it?

No. Not quite. SPIFFS has nothing to do with EEPROM.h.  It's a filesystem. You use it like an SD card (but without the SD card).  On your computer you will create (in a new folder) a file with data in it (what format that takes is entirely up to you). You can make multiple files if you like. Then you use mkspiffs to turn that folder into a SPIFFS image, which you then upload to the memory address of the spiffs partition. Then you use SPIFFS.h to access it like you would an SD card.

There's loads of ESP32 tutorials here - many are about SPIFFS.

Let us continue this discussion in chat.


text:
How can I get a holding torque on dc motor if I am using an H-bridge?
I am trying to build a robotic arm and also using a lot of metal in it, now the real challenge for me have arrised at first I was using tower pro mg995 but that servo is worse than scrap. So I ditched them and got myself Johnson geared motors. Now as long as I apply the voltage the motor running holds the weight and move it to the desired position but when current is shut down it drops it. Please help me understand the concept of holding torque or even how much duty cycle will be required to hold the motor in place. I am using external potentiometers for position feedback and have achieved accuracy with it. Also I have cut open the tower pro servo to use its gear mechanism and found it worked nice so I wonder if I could use them too.
I aim to control 8 motors but for the time being struggling with just one. Please help.
And one more question should I consider using L298N IC for the motor control and not build my own H-Bridges.
Thank you, you guys are awesome.

While you can break the motor by essentially connecting both ends of the coil through the driver, that breaking might not be enough. It might need active driving of the motor to keep the position. So how are you currently moving to a set position? A common way of achieving such things would be implementing PID control in your software. Please show us your current code.

Correct me (anyone) if this is over simplistic, but I always assumed robots were driven by either stepper motors or motors with feedback (servos). For steppers it is unnecessary to know the torque as long as you exceed it.  For servos I would think you need to constantly monitor if the motor is in the desired position and use the H-Bridge to return to the desired position if necessary. I have not seen a situation where you can remove power with out a mechanical break system to hold the position.

@st2000 I understand your point and that is the reason why I said I am using potentiometer to get the position feedback.

@chrisl I had tried the breaking mechanism by short circuiting the wires of the motors but the force was of more intensity.
Should I consider a gearbox for further reduction, I have an option to 3d print the mechanism.

Dynamic breaking is likely not going to stop a motor as it only generates a stopping force when objects are in motion.  This is the reason a lone locomotive is more dangerous (only or mostly relies on dynamic breaking) then an entire train (now the engineer has air breaks on all the cars attached to the train).  So, if you are going to cut the power, you likely need a mechanical break.  Posting in this forum usually indicates a low budget project.  So I would consider a small amount of friction applied to the motor shaft so that you can take advantage of the gear box multiplication effect.

Do you really need to cut power? Then you definitely need mechanical braking. Otherwise just keep driving the motor actively. Please show your code


text:
Multi turn potentiometer are a pain should I use a incremental encoder instead?
I built a robotic arm, the problem is I want to rotate the base more than once in order to complete a job, so I figured out I could use multi turn potentiometer.
The problem I am facing is the potentiometer is burning without any reason.
I have a ton of burnt ones with me.
Sometimes it is caused by soldering and sometimes the shaft testing rotates the potentiometer beyond its limits.
While I could get the values precisely.
I am trying to avoid the pain of buying more.
My question is if I can use incremental encoder, the electricity in my country is not that stable and I don't want to lose the values accumulated by the arduino.
So does the encoder remembers the values or rotation or it starts afresh?

Please show your circuitry. Any potentiometer can be operated in a way that it does not burn, you might have an error here. However, the number of revolutions is limited. -- No, an incremental encoder does not remember its value, aside the current quadrant. That's why it's called "incremental". You might want to save the current value in EEPROM, time after time or at power loss. The latter needs some prerequisites. -- There are "absolute rotational sensors", at least I was involved in the development of one more than 20 years ago. However, they are expensive.

I kind of thought about it so I also ordered a sd card module to store the values and retrieving on resets. At first I thought about saving the values in EEPROm of the arduino but I figured out it has 100,000 write/read cycles

@Juraj the reason why I need to remember the position is because I do no want my system resetting every time the power takes a turn. And continue where it left.
Thats just a technique to make a dependable system.
I know about limiting switches and in a device which has 6 degree of freedom its kind of a pain to use them.

Yes, you can use a rotary encoder. However, there are two kinds of rotoary encoder: absolute, and relative. Relative encoders are the small common ones you find being used for things like volume controls. They only give you "It moved clockwise x steps" kind of information, which is not ideal for your usage. What you need is an absolute rotary encoder. This is a far more complex device and is often used on the shaft of motors to give the current angle the motor is at. These usually use a Gray code to represent an absolute angle at a specific resolution (choose the resolution to meet your requirements) and will tell you (within that level of resolution) the exact angle your robot arm is at. You can rotate it as many times as you like and it will always give you the current angle (note: it can't tell you how many revolutions it's made, that is down to you to count, should you actually need to).

I kind of thought about it so I also ordered a sd card module to store the values and retrieving on resets.
At first I thought about saving the values in EEPROm of the arduino but I figured out it has 100,000 write/read cycles.


text:
RadioHead Library custom configuration for RFM96 LoRa
I have a pair of Adafruit RFM96W LoRa Transceiver Breakouts and want to use them with the RadioHead library.
My pair of radios works if I use the example sketches from the adafruit tutorial, but I want to change their default configuration.
From the Datasheet of RFM96:

For maximum flexibility the user may
  decide on the spread spectrum modulation bandwidth (BW),
  spreading factor (SF) and error correction rate (CR).

I want to configure the BF, SF and CR. I also want to be sure that the radios are working with the LoRa Modulation and that CRC is enabled.
And how to set Header-Settings?
I did find the method rf.setModemConfig() which gives the capability to change the configuration to library-pre-defined ones, which is not what I want. I want to try different combinations of settings.
I did find the method rf.setModemRegisters() but I did not understand how to use it.
Any solution is welcome.

Parameter in RH_RF95.h
const RH_RF95::ModemConfig myProfile =  {
  RH_RF95_BW_62_5KHZ | RH_RF95_CODING_RATE_4_5,
  RH_RF95_SPREADING_FACTOR_1024CPS};

rf95.setModemRegisters(&myProfile);


text:
Difference between Wire.setClock() method and TWBR method for changing I2C Frequency
I want to change the I2C frequency of my Arduino Mega 2560. I did find two methods. One method is to change the TWBR variable after Wire.begin(). The other one is to use Wire.setClock() after Wire.begin().
Whats the difference between the 2 methods? which one is better? Can I set any I2C frequency I want?

Whats the difference between the 2 methods?

The difference is that one is more portable than the other. The "direct register set" will not work very well on an Arduino Due.
There is no speed or foot-print advantage with the "direct register set" as this is often only done once in the setup of the sketch.

Which one is better?

If better is portable, maintainable, readable, etc then the answer is simple - use the API and not "direct register set".

Can I set any I2C frequency I want?

No - obviously there are some restrictions. First, the CPU frequency is scaled so it cannot generate all possible frequencies. Second, the I2C device(s) and bus will set restrictions on the maximum frequency. Longer wires and several devices will add capacity and require lower frequency. Also the device with the lowest frequency puts an upper limit. Always check the data sheets for the I2C devices.
Cheers!

They are both one and the same. One is easier to remember though (I'll let you work out which).
Wire.setClock(frequency) just (ultimately) does:
TWBR = ((F_CPU / frequency) - 16) / 2;

You can set any frequency that ends up with that formula generating an integer between 0 and 255.


text:
How much time does the Arduino need to call a Function or to read a Variable?
How much time does an Arduino Uno or Mega need to only call a function. And how does the time change if this function is inside a Class, for example inside a Library?
The same thing for a variable. How much time does a micro-controller need to read a declared variable?
How to determine this values? Is there a mathematic formula? Can we predetermine this type of delays and other similar micro-controller related delays?

Is this question really about how to optimize performance for a micro-controller? What are your performance goals? Why not start with high level system optimizations first. They give XN instead of N%.

It is hard to give a general answer, as it depends on the specifics of
your code and on how the compiler compiles it:

How much time does an Arduino Uno or Mega need to only call a function.

This can involve a number of things:

the caller puts the arguments on some predefined CPU registers, unless
they are already there from a previous operation (the compiler tries
to optimize the code so that this happens whenever possible)
the caller issues the call instruction to do the actual function
call
the callee pushes some CPU registers into the stack in order to use
them without clobbering the caller's data
the callee does its job
the callee pops the previously pushed registers
the callee issues the ret (meaning return) instruction
the caller finds the return value in some CPU registers

On the Uno, the call and ret instructions cost 4 CPU cycles
each (0.25 µs). On the Mega, it's 5 cycles (0.3125 µs)
each. push and pop are 2 cycles each, and you need one such
pair for every 8-bit register you need to save.

And how does the time change if this function is inside a Class, for
  example inside a Library?

The only difference is that a class method receives an extra hidden
parameter called this. Except if it's a virtual method, which is more
expensive because it involves some pointer dereferencing.

How much time does a micro-controller need to read a declared
  variable?

“Reading” generally means transferring the contents of the variable to
some CPU registers. Local variable are usually allocated to CPU
registers in the first place, so there is no need to read them. Global
(and local static) variables are stored in RAM, and reading them takes
2 cycles per byte (e.g. 4 cycles for a 16-bit int).

How to determine this values?

Disassemble the code generated by the compiler. Then look up the
instructions in the instruction set manual: it documents the number
of clock cycles needed by each instruction.

Would add that the compiler may inline functions to allow further optimizations. Also the compiler may eliminate a variable if const, reuse value from register, etc. In these cases the time needed is zero or even negative :)

How much time does an Arduino Uno or Mega need to only call a function.

Why do you want to know? This sounds like an X-Y problem.
It will vary, depending on a lot of things.

The number of arguments, because the more arguments the more work involved. Plus if an argument involves copying it might invoke a copy constructor.
Whether or not the compiler in-lines the function. If it is in-lined (copied into the other function) then there is less work, for example the compiler doesn't need to generate call and ret instructions.
What the function does. The more things a function does, the more registers the compiler may have to push and then pop afterwards to save the state of registers which had useful information in them, outside the called function.
The size of the arguments. Longer arguments take longer to copy onto the stack, or put into registers. For example, long arguments will take longer than char arguments.

How much time does a micro-controller need to read a declared variable?

Again, it varies. It depends on the variable size, and whether or not it is already in a register. If the variable happens to be in a register at the time, you could argue it takes zero time to read it.

How to determine this values?

The sensible thing to do is to time some test code. Here's an example from another thread:
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {
  }  // end of loop

In the middle of the code there I time doing digitalWrite 100 times. By dividing the resulting output by 100, I can work out how long each digitalWrite takes.

You don't normally need to know how long, exactly, it takes to read variables, and call functions. Either your code works at an acceptable speed, or it doesn't.
Trying to answer this question on test code may give meaningless results. For example, in my test code the compiler may have in-lined the digitalWrite call. But if I use digitalWrite in many places it will no longer in-line it, which means the timing figures are now incorrect.

The Questions is how much time the millis() and micros() functions need to finish their work, so the measurement is accurate.

If that was what you wanted to know, it would have been better to ask that exact question. That saves us waffling on about copy constructors and so on.
I tested with the code below, which calls micros() and saves the results to a variable foo. I made it volatile so that the compiler wouldn't be tempted to optimize away the saving altogether (because it isn't used anywhere else).
void setup ()
  {
  pinMode (13, OUTPUT);
  PORTB = 0;
  }  // end of setup

volatile unsigned long foo;

void loop ()
  {
  PINB = bit (PB5);   // toggle D13
  foo = micros ();
  PINB = bit (PB5);   // toggle D13
  }  // end of loop

I measured 3.380 µs on my oscilloscope for the time when D13 is high. That would be 54 clock cycles. A couple (only) would be the time taken to toggle D13. Thus you can probably reckon micros() in general as taking 3.38 µs.
Changing it to call millis() instead, it only takes 1.760 µs (28 clock cycles). This is probably because all millis() does is return a variable which has already been calculated (in the timer ISR).
Test done on an Arduino Uno running at 16 MHz.

The Questions is how much time the millis() and micros() functions need to finish their work, so the measurement is accurate.

You don't need to save the return value of micros() to RAM. Doing so takes 8 extra cycles. The compiler can't optimize the call away because it is not aware that micros() has no side effects.

Well, the OP was also asking about time taken to read variables. If I needed to time some thing, I would need to get the start time, save it, and then get the end time, and subtract one from the other.

No need to save to RAM though: if you use local variables, they are likely to be allocated to CPU registers by the compiler. I tried compiling your first example and that is exactly what happened: neither start nor finish were committed to RAM. The overhead of timing the loop was 2 cycles (a couple of movw) + the cost of a call to micros().


text:
Audio.h Library Issues
I'm trying to incorporate audio into my Arduino project for the first time, and have been have a lot of issues. I originally couldn't get the Audio library to work, but after installing it through the Arduino application, I figured the Audio.h library would work fine. However, it spit out this error:

WARNING: library Audio claims to run on (sam) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s).
  In file included from /Documents/Arduino/libraries/Audio/src/Audio.h:16:0,
                   from /Documents/Arduino/boxgame/boxgame.ino:1:

Then it lists plenty of syntax issues, none of which have to do with my code. I think it's giving errors from the library, but I'm not really sure what's happening. Here's an example of one of the slew of errors:

/Users/tschadius/Documents/Arduino/libraries/Audio/src/DAC.h:37:2: error: 'IRQn_Type' does not name a type
    IRQn_Type isrId;

Any ideas as to how I can fix this? The error message goes on for quite a while, but none of them appear to be from my code that I've written.
Thanks!

Need a bit more information to be able to answer this.  Which particular board are you using?

Using a SparkFun redboard, which is essentially identical to the uno!

The Uno cannot use that library. The Uno has no DAC.

Occasionally people do not realize how many platforms the Arduino paradigm has been ported to.  In almost all cases the ported to platform far exceeds the features found on an Arduino Uno.  So there exists a considerable amount of software that can not run on an Arduino Uno or on an Arduino Uno with out additional hardware.  But, usually, such software is surrounded by "text", "web-pages" and other "readme"  type files explaining the situation.
For the Arduino Audio library, the web-page says this:

Audio
Compatible with Arduino Due only
The Audio library enables an Arduino Due board to play back .wav files
  from a storage device like an SD card.
The Due uses the DAC0 and DAC1 pins to play sounds.

Thank you, I really appreciate your comment. I'll be sure to be more thorough about reading all associated documents next time.


text:
LEDs not working with tone() function
I have a strange issue. I have 3 LEDs, each is supposed to beep with a correlated tone... Imagine the beginning of a racing game (beeping with traffic lights). Here's my code:
#include "pitches.h"

//Beginning Melody
int melody[] = {
  NOTE_C3, NOTE_C3, NOTE_C4
};

//Beginning Note Durations
int noteDurations[] = {
  2, 2, 1
};

int redLight = 3;
int yellowLight = 5;
int greenLight = 6;

void setup() {
  Serial.begin(9600); //initialize serial communication

  pinMode(redLight, OUTPUT);
  pinMode(yellowLight, OUTPUT);
  pinMode(greenLight, OUTPUT);
}

void loop() {
  playBegin();
  delay(5000);
}

void playBegin(){
  int lightColor = 1;

  for (int thisNote = 0; thisNote < 3; thisNote++) {

    if(lightColor == 1){
      analogWrite(redLight, HIGH);
    }else if (lightColor == 2){
      analogWrite(yellowLight, HIGH);
    }else{
      analogWrite(greenLight, HIGH);
    }
    lightColor++;

    int noteDuration = 1000 / noteDurations[thisNote];
    tone(11, melody[thisNote], noteDuration);
    delay(1000);
    noTone(11);

    analogWrite(redLight, LOW);
    analogWrite(yellowLight, LOW);
    analogWrite(greenLight, LOW);
  }
}

Originally, the 3 LEDs would light up correctly. The red light is plugged into Pin 3, the yellow light into Pin 5, and the green light into Pin 6. HOWEVER, when I added in the tones, the red light (in Pin 3) doesn't light up. The 3 tones still sound off correctly, and the yellow and green LEDs work perfectly fine. This is ONLY not working for the red LED, it just doesn't light up while the 1st tone happens.
When I take out the line of code where tone() is, it works fine and the red light will turn on at the correct time again. This is ONLY happening when the tone() function is included.
To be clear, this is the exact line of code that is affecting the red LED:
tone(11, melody[thisNote], noteDuration);

Furthermore, I swapped the pins of the yellow and red LEDs to see if it was an issue with the red LED, and it was not. It's whatever LED is plugged into Pin 3, and again, ONLY when the tone() function is in the code as well. I'm not sure how they're conflicting. This does not appear to be an issue with my hardware.
I'm working with Arduino Uno. If you need anymore info, let me know.
Thanks!

Why are you using analogWrite() coupled with the digial level of HIGH...?

You have a timer conflict.
tone() uses a timer, and analogWrite() on certain pins uses the same timer.
Quite why you're using analogWrite() though, with HIGH (which equates to 1) as the duty cycle I don't quite understand. I would have though digitalWrite() would be a better choice. A duty cycle of 1 would be pretty much invisible anyway...

Following on from the information provided by Majenko and Delta_G and a minor modification/simplification, here is the resulting code:
#include "pitches.h"

//Beginning Melody
int melody[] = {
  NOTE_C3, NOTE_C3, NOTE_C4
};

//Beginning Note Durations
int noteDurations[] = {
  2, 2, 1
};

int redLight = 3;
int yellowLight = 5;
int greenLight = 6;

void setup() {
  Serial.begin(9600); //initialize serial communication

  pinMode(redLight, OUTPUT);
  pinMode(yellowLight, OUTPUT);
  pinMode(greenLight, OUTPUT);
}

void loop() {
  playBegin();
  delay(5000);
}

void playBegin(){
  for (int thisNote = 0; thisNote < 3; thisNote++) {

    if(thisNote == 0){
      digitalWrite(redLight, HIGH);
    }else if (thisNote == 1){
      digitalWrite(yellowLight, HIGH);
    }else{
      digitalWrite(greenLight, HIGH);
    }

    int noteDuration = 1000 / noteDurations[thisNote];
    tone(11, melody[thisNote], noteDuration);
    delay(1000);
    noTone(11);

    digitalWrite(redLight, LOW);
    digitalWrite(yellowLight, LOW);
    digitalWrite(greenLight, LOW);
    delay(200);
  }
}

If you read the documentation for the tone function ( https://www.arduino.cc/en/Reference/Tone ), you might notice this line:
Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).


text:
Multiple LED on arduino
I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.
Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?
Thanks for your help

please explain why you think that you can only light up one LED with the Arduino.

Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.
Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.
This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.

If you connect them in parallel instead of series you'll be able to turn them on and off with 3.6 volts (5 volts through an appropriate dropping resistor), assuming the Arduino can supply the current. Here's a general explanation of the difference.

yes I had actually tried in parallel and it had not worked but today I figured out that one wire had a problem. It all works now thanks


text:
Programming standalone 328P in circuit
I am designing a PCB using a 328P. As I understand it, I can either flash the chip via the ICSP header (without bootloader) or via Serial (if it has a bootloader already). But how does programming actually work?

According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?
Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?
Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?

According to my program running on the chip, it acts as master for SPI peripherals. If using ICSP, how does the chip know that it is supposed to act as SPI slave and receive a program?

A special signal is sent using the RESET pin. From the datasheet (p361):

Power-up sequence: Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems, the programmer can not guarantee that SCK is held low during power-up. In this case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to “0”.
Wait for at least 20ms and enable serial programming by sending the Programming Enable serial instruction to pin MOSI.
The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte (0x53), will echo back when issuing the third byte of the Programming Enable instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a positive pulse and issue a new Programming Enable command.

Is there anything I must take into account with regards to what is connected to the SPI pins? i.e. does it harm in any way if I have other SPI slaves on the board connected to these same pins?

Yes. It is possible that a chip may respond to the ICSP signals. You should have pullup resistors on all your CS (or SS if you prefer to call it that) pins on all your slave chips so that while the ATMega328P is in programming mode (and all the GPIO pins are in INPUT mode by default) the CS pins of your slaves aren't floating.

Same for serial programming: how does the chip know that it's supposed to receive a program on the serial interface, when my application uses this port for a different purpose?

Simple: it listens for 2 seconds after power-on or reset for a special sequence of bytes arriving on the serial port. If they arrive within that 2-second window (8 seconds for ATMega32U4 based boards, to allow time for USB enumeration) the bootloader keeps running and looking for programming instructions. If it doesn't see that start sequence within the timeout period it exits the bootloader and runs your sketch.
The STK500 protocol (which the Arduino bootloader is based around) is detailed here. The trigger sequence is the "CMD_SIGN_ON" command detailed on page 4.

You pull the reset pin LOW.

Both the Flash and EEPROM memory arrays can be programmed using the serial SPI bus while RESET is pulled to GND. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the Programming Enable instruction needs to be executed first before program/erase operations can be executed.

Most SPI devices have a Chip Select pin. Unless this pin reads LOW, the device isn't listening. That way you can have multiple devices sharing a single SPI bus.
You pull the reset pin LOW for a moment. That makes the chip reset itself. When the chip resets, it first runs the bootloader program. The Arduino bootloader waits 3 seconds for any programming instructions coming in via the serial connection. If these 3 seconds have past, it will exit the bootloader and run your main sketch.

Simply follow the hardware design guide from Atmel AVR042


text:
Why would anyone use Arduino in 2017?
Sorry for clickbait question but it really bugs me why Arduino is still a thing in the age of ARM based boards like Pine64, Raspberry Pi, Bannana Pi, Whatever Pi etc.
I'm more or less aware of Arduino capabilities as I used to program PLC controllers but I don't really see any rational reason to use Arduino platform over ARM devboards (unless we need mission-critical level reliability however I believe commercial realtime OSes for ARM boards also exist). Even PLC and in general industrial controllers seem to shift towards platforms driven by actual RT OSes underneath running on powerfull hardware.
Getting 30$ quad core 1.2 ghz ARM board with 512M RAM, ethernet, GPIO, I2C, SPI, USB, SD card and actual Linux OS which can do virtually everything whatsoever over 25$ Arduino Uno board with abacus level performance, similar or inferior i/o, capable of only pretty basic stuff sounds to me like no brainer. Arduino sounds to me like extremely cost ineffective solution for almost anything. And I can't seem to find any rational explanation to why people still use such thing now? Maybe as Linux engineer I'm a bit biased towards Unix based solutions because I feel "safe" in this ecosystem but still I think my points are kind of objective no matter if availability of unix itself on platform is considered serious advantage or not.

When's the last time you did hard realtime in Linux? Or even on ARM?

Not necessarily Linux. There are OSes like QNX for example or other commercial RT systems. However RT Linux is also kind of taking off, though I'm aware it's far from RT OS. Not that you really need RT OS at this level of tasks... As long as you're not building medical equipment or industrial controllers using Arduino boards...

You might not need 512M RAM and 1.2 GHz quad ARM core to blink a LED :). 2K RAM and 16 MHz single AVR core might be sufficient. And the learning curve not as high. In any case, what type of GPIO performance (highest pin toggle frequency) can you get using Linux (from user space)? Bare metal has its charm (and fun).

Go to trends.google.com and show the graph for "arduino" worldwide from 2004. It is going up. However, the Arduino organization can not sit still, even if sometimes a bad choice is made. The WeMos is not an official Arduino board, but it should be.

@MikaelPatel I didn't check max PWM freq on ARM boards but I guess after setting FIFO scheduling policy to process so that preemption doesn't occur automatically you can have quite strict control over i/o timings even without strictly RT OS. Also at least how I justify power reserve is that you don't really need to run just one project on such board. With greater reserve you can run multiple projects in parallel on single piece of hardware.

See When Raspberry Pi is preferred over Arduino and Why connect arduino with Rasberry pi?.

@EdgarBonet yeah I've seen plenty of topics like those but I don't really agree with them as ARM board using RT OS (like FreeRTOS for example) is pretty RT and boards other than Rpi (eg. banana Pi, Rpi isn't actually that much i/o oriented ARM board) have plenty of i/o options, quite comparable with Ardu. That's why I created this question to gain more details and boarder cases where it really does make sense to use Ardu over ARM board.

Possible duplicate of When Raspberry Pi is preferred over Arduino

One way to approach answering your question is to look at some specific implementations. Take, for instance. 1-Wire and study how the respective implementations on rpi and arduino are done (and how easy they are to use, understand, etc). Another example is MQTT or some other high level TCP/IP protocol.

This is the ATtiny.

It costs < $1 and is completely capable of most tasks that a hobbyist requires of a chip. Truthfully, it’s more than capable of many tasks a pro requires as well. It’s perfect for adding just a little bit of smarts to a project. Not every project needs an ARM chip, dual cores, or a Linux distro running. In fact, in low power situations, that’s likely the last thing I want. How long does your smart phone battery last? A day? I’ve heard of people powering ATtiny based projects on 3 AAs for over a year!
The Arduino is an excellent little dev board for these micros. For the cost of a few cups of coffee I can have one for my work bench. Heck, I’ve used them at work as dev boards for prototyping. It’s cheap enough to put one on the desk of every dev on a project. We can verify our code works on the target architecture very early in the dev process. That was unheard of just a decade ago.

One year on 3 AAs? I have an ATtiny running since June 2012 on 2 AAs. As much as I love my Raspberry, I'm sure it can't do that.

It's just uC. ARM SoCs are also super cheap but that's not the point. It's not board with meaningful i/o, just single component. You need either custom PCB for that or some of the shelf one as it doesn't even have any form of power delivery (though I can't seem to find off the shelf i/o boards for ATTiny). It's not ready to use platform. I got flushed by Arduino Uno price. Didn't consider it's mostly price of programmer, debugger and whole starter kit rather than uC itself. However like I said I can't seem to find universal i/o boards for ATTiny with something like GPIO

@Lapsio: See the Trinket.

The 328P & 32u4 (most commonly used chips for Arduino) are similar enough to the Tiny to use them as dev boards. Atmel has really done a fantastic job of keeping their libraries portable between their devices.

@RubberDuck My concern about common Arduino dev boards was that they're expensive. Too expensive considering capabilities compared to ARM boards. But with i/o boards like mentioned Trinket it's fair price. 7$ is significantly less than 30$ and this is something I can understand.

You’ve got to be trolling. An arm eval board runs $250 and that’s on the less expensive side.

@Lapsio: If you think the Trinket is a fair price, how about $1.45USD for a Pro Mini (same performance specs as the Uno) at aliexpress.

How about this? http://www.orangepi.org/orangepizero/index.html and the cheapest variant is $6.99 :)

Here is another one $8.99 and comes with Ubuntu preloaded; http://www.friendlyarm.com/index.php?route=product/product&path=69&product_id=132

@RubberDuck it was pretty bad example of really beefy ARM board. 3gb DDR4 RAM is more than most phones have to offer. I didn't even know such overkill ARM boards are widely available. Average price of mainstream ARM boards is somewhere around 30-50$ for ~1Ghz few cores, ~1GM ram and some mainstream i/o. Those 8$ ARM boards are rather ultra compact ones without ethernet and quite poor i/o options in general so I don't think comparing them to more complete Arduino boards is fair either.

An arduino board is really a breakout for a micro processor. Microprocessors you can get separately. A rPi is really a full system without that modularity.
There are also other size factors for that breakout board, many of which are much smaller than a rasberry pi and will have a much better battery life. And very often the abacus-level perf and half a dozen GPIO pins is all you really need.
Also some people enjoy having direct control over the chip in a way that a semi-stripped linux OS on a poorly documented platform just doesn't give. Hard realtime when you don't have full control over the system means you need to trust the RT-OS writers to actually hold to their documented deadlines.

On the other hand from engineering standpoint it doesn't really seem to be wise to trust your own code more than industrial solutions at least as long as you didn't break everything into ASM code and compared against timings of individual instructions for certain uC. It's general rule of thumb to use as much of the shelf stuff as possible while designing RT systems to avoid necessity to prove time limits.


text:
Analog Read gives Erratic behaviour in Struct
I'm getting some very strange behaviour from a Haptic feedback system I'm trying to make.
The test code works fine as a Multiple-In One-Out in the main loop, but once I moved the code to the Struct, I ended up with very erratic behaviour on the motor that is completely independent of pressure on the FSR and bears no correlation.
Bizarrely, the serial data that I have been using to debug the code is also largely unusable now.
Does anyone have any idea what's going on?
(p.s. Don't worry about the current draw of the motor, I'm using tiny mobile phone vibration motors specifically for their low voltage and current draw)
Note: All '[' chars in the code and log have been replaced with '<' and ']' with '>' so that I can actually post this question without the site screaming at me about more than 8 links.
main.cpp:
#include <Arduino.h>
#include "sensorWeighting.h"

const int DIAG_PIN = 2;
short int numMotors;

sensorWeighting* MOTORS;

void setup() {
  Serial.begin(9600);
  MOTORS = new sensorWeighting<1>;
  //motor 1
  MOTORS<0> = sensorWeighting(9,2,new int<2>{0,1},new int<2>{100,60});
  numMotors = 1;//sizeof(MOTORS) / sizeof(sensorWeighting);
}

void loop() {
  //Serial.println("Start Loop.");
  //Serial.print("numMotors = ");
  //Serial.println(numMotors);
  for (short int index = 0; index < numMotors; index++) {
    //Serial.print("Updating Motor: ");
    //Serial.println(index);
    MOTORS<index>.update();
  }
  //Serial.println("End Loop.");
}

sensorWeighting.h:
#include <Arduino.h>
class sensorWeighting {
  private:
    short int output;
    short int inputNum;
    int* input;
    int* weight;

  public:
    sensorWeighting(){}
    sensorWeighting(short int pinOut, short int numInputs, int* inputs, int* weights){
    pinMode(pinOut, OUTPUT);
    output = pinOut;
    inputNum = numInputs;
    input = new int<inputNum>;
    weight = new int<inputNum>;
    for (short int index = 0; index < inputNum; index++) {
      pinMode(inputs<index>, INPUT);
      this->input<index> = inputs<index>;
      this->weight<index> = weights<index>;
    }
  }
    virtual ~sensorWeighting(){
    delete &output;
    delete &inputNum;
    delete<> input;
    delete<> weight;
  }

  void update(){
    Serial.print(inputNum);
    Serial.print(" inputs. ");
    int out = 0;
    for (short int index = 0; index < inputNum; index++) {
      int rawVal = analogRead(input<index>);
      Serial.print("raw input :" + index);
      Serial.println("value: "+rawVal);
      int val = (weight<index>*rawVal)/90;
      if (val>out){
        out = val;
        }
      Serial.print("Evaluating input: Input<");
      Serial.print(input<index>);
      Serial.println("] = " + analogRead(input<index>));
    };
  Serial.println("Raw Output: " + out);
  Serial.print("Trimmed Output: ");
  Serial.println(out/4);
  Serial.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
  analogWrite(output, out/4);
    };
};

typedef class sensorWeighting senorWeighting;

Serial Log:

2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :
~w[�?��x��o{Ӿ��˗��{��"����0�������^�������o?WwZ�{����[e���������������?�����/������ѧ����������������}��w����i����s���c�Mo}�����׷ʾ������Ф�m�Y�zo������
  =��������������)��ۺW{r�[w����g׬����-����ߦ]��{�{�w��y�߻��(�?�^���[%}U��7��
  ���|����������}W�ֶo���]��-�ݔ]�������Yo0
  ��쎖w��z9���}��]o���[���K���?9^K����b�����%�s����;S+S���[}Y�1���^
Trimmed Output: 27
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :luating input: Input<
Evaluating input: Input<1> =
put:
Trimmed Output: 1
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
aw input
  :Ӿ��˗��{��"����0�������^�������o?WwZ�{����[e���������������?�����/������ѧ����������������}��w����i����s���c�Mo}�����׷ʾ������Ф�m�Y�zo������
  =��������������)��ۺW{r�[w����g׬����-����ߦ]��{�{�w��y�߻��(�?�^���[%}U��7��
  ���|����������}W�ֶo���]��-�ݔ]�������Yo0
  ��쎖w��z9���}��]o���[���K���?9^K����b�����%�s����;S+S���[}Y�1���^
  ޯ�3���������}�/jv����|��O讝����Ͷ�����������������Ϸ�+�l��s�}m����������������o�~�~�
  8
Evaluating input: Input<1> =
Trimmed Output: 66
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

char array concatenation doesn't work with +.

@gre_gor cheers for that, I'm getting much more usable serial data now.
I can see that the inputs are working, so it's an issue in the workings between I and O.


text:
How do I change the I2C address on the LCD backpack?
The 20 x 4 LCD comes with a I2C backpack.  I know it has A0, A1, A2 to set the address, as shown at the bottom here:  https://tronixlabs.com.au/news/tutorial-serial-i2c-backpack-for-hd44780compatible-lcd-modules-with-arduino/
It points to here:  http://www.nxp.com/products/interface-and-connectivity/interface-and-system-management/i2c-bus-portfolio/i2c-general-purpose-i-o/remote-8-bit-i-o-expander-for-icbus-with-interrupt:PCF8574_74A
My unit shows up as 0x3F.
And even with all this information I can't tell how to change it.
I need to have a second display on the same I2C bus.
Question:  How do I change the address of the second one?

As mentioned in the page you linked, jumper together one of the address jumpers. For example, above A0 are two pads. Solder a wire across them (vertically - between the two pads above A0). I am guessing the address is pulled high by a resistor, so that will probably make the new address 0x3E, but you could run the I2C scanner to check that.

I tried it and it works.  Simply jumpering A0 together gave me the address of 0x3E, just like you said..  Thanks again for your help,

I would add that the method I used that worked was to first use my soldering iron to build up a bead of solder on both contact points, then take a small solid wire and scrape it and tin it thoroughly, bend it to fit, then solder both points at the same time.  Then snip off the excess.  These points are small but it sure can be done.  Thank you again, @Gammon, for the encouragement.

I fleshed out this process here:  https://arduino.stackexchange.com/questions/12181/how-do-i-use-two-i2c-lcds-with-4-pins/32188#32188 and couldn't have done it without your help, @Gammon.  Thank you again.


text:
Conditional compilation depending on sizeof(double)
Is there a macro (#define ...) somewhere in the bowels of Arduino IDE or core header files which tells me at compile time(!), if the double data type for a given platform/board is a true double precision floating point number (64 bit width) or "only" an alias for a single precision float (32 bit width)?
With Arduino, both can be the case. 8-bit AVR boards have double equal to float, ARM-based boards (like Arduino Zero) support "true" double precision.
I am working on a library which implements some bit-banging of floating point numbers (both single and double precision). Due to the low-level nature of the problem, there must be separate functions for float and double. I would like to do somthing like that:
uint32_t function_for_float(float f) {
    // function body here...
}

#if defined(HAS_64_BIT_DOUBLE)
uint64_t function_for_double(double d) {
    // function body here...
}
#endif

That way, a compile time error would be generated if somebody tried to use the "double" version on platforms which do not support the "true" double data type. I want the compiler error to be generated, because function_for_double() will do silently "the wrong thing" when fed a single precision float, leading potentially to difficult-to-debug problems.
Right now, I am defining a macro constant for every relevant board I own, like this:
#if defined(ARDUINO_SAMD_ZERO) \
 || defined(SAMD_FEATHER_M0_EXPRESS) \
 || defined(ADAFRUIT_FEATHER_M4_EXPRESS)
    #define HAS_64_BIT_DOUBLE
#endif

But this is ugly and not future-proof (new boards can/will become available...).
Any suggestions?

This is not really an Arduino question. Arduino uses g++ to compile, so your question really is "can g++ do this?" Judging by this - not really. You can assert if double isn't 8 bytes (I tested that) but not make a choice, unless there is another tricky way of doing it.

@NickGammon: Thanks for the link. I actually have a static_assert(sizeof(double) == 8) in the code of my "double function". However, then the complete library .cpp file will not compile on platforms where double ist only four bytes. This is what brought me to think about conditional complilation in the first place. I would like to generate a compiler error only if sombody tries to use the double version when he/she shouldn't. Somewhere in Arduino there surely must be definied that double is equal to float? I hope(d) to use this as a hook somehow...

The double data type is almost universally 8-bytes long, so you could
simply
#if !__AVR__
# define HAS_64_BIT_DOUBLE
#endif

Gcc provides a more specific macro though: __SIZEOF_DOUBLE__, which
has the same value as sizeof(double). But I do not know whether it is
provided by other compilers.

Perfect! I will make use macros __SIZEOF_DOUBLE__ and __SIZEOF_DOUBLE__, even if they are gcc/g++ specific. The Arduino IDE uses g++ as its backend, anyway, so this is "good enough" for me.

Just verified that __SIZEOF_DOUBLE__ == 4 on an Arduino Pro Mini (AVR 328p) and __SIZEOF_DOUBLE__ == 8 on an Adafruit Feather M0 (ARM Cortex-M0+ / SAMD21). Thanks a lot! I have selected your answer as the correct one.


text:
How to get Velocity and Displacement from IMU sensor?
I have an imu mounted bot.I want to get the speed of the bot using imu i dont want to use the encoders. Imu gives acceleration how should i integrate that to get velocity and how much error would be there??

The error in this method would be massive.
Velocity is the integration of acceleration over time. However, you don't have acceleration over time - you only have acceleration at discrete points in time - the times that you actually sample the acceleration.
You would want the total acceleration between two points in time, which you just don't have.
Take the following timeline of acceleration points:
+3 +2 +5 +2 -3 -4 +3 -5 +3 +2 +6 -4 -2 +3 -4 -5 +6 -3 -1 -2 +7 -2
 ^           ^           ^           ^           ^           ^

The carets are the points where you are actually sampling the acceleration.
Assuming you start from 0m/s, and those are all changes in m/s, your calculated speed from your samples would be 3-3+3-2+6+7 = 14m/s.  However, the real velocity would be 7m/s.
In reality, there aren't discrete points of acceleration - just a single smooth waveform.
The faster you can sample the closer to reality you get, but there's always a chance that you would miss some critical brief change in velocity.
On top of that, you have noise. Quantisation noise, vibration, electrical noise, etc - all of which add a certain amount of uncertainty of their own.


text:
Attempts with Sainsmart Motor Shield Not Working
I received the sainsmart motor controller a few days ago, and am now having trouble testing it. The Arduino I am using is an Arduino Mega 2560. I thought it was an I2C communication issue but that wasn't working. So here I am now asking for help.
Here is my wiring.

Here is my code:
#include <AFMotor.h>

AF_DCMotor motor(2);

void setup() {
 Serial.begin(9600);           // set up Serial library at 9600 bps
 Serial.println("Motor test!");

 // turn on motor
 motor.setSpeed(200);

 motor.run(RELEASE);
}

void loop() {
 uint8_t i;

 Serial.print("tick");

 motor.run(FORWARD);
 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

 for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tock");

motor.run(BACKWARD);

 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tech");
motor.run(RELEASE);
delay(1000);
 }

I also tried this one:
#include<AFMotor.h>
 AF_DCMotor motor2(2);
void setup() {
 // put your setup code here, to run once:
 motor2.setSpeed(255);
}

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

None of the two worked. If someone could help me that would be great. Thank You!!!

the picture of your board is not a very good representation of the wiring. ... please draw a schematic.  ... there is a button for that when you edit your question

How am I supposed to represent the motor shield? I'll tell you the wiring. The sainsmart board connects all the pins on the side of the standard arduino uno except for pin 7 digital. The IC2 is connected to SDA(Digital 20) and SCL (Digital 21). The motor is connected to the M2 Terminal.
Thanks!!!!

I figured out the problem. One of the terminals was damaged during transportation. Now it's all good. Thanks for the help.


text:
All of the sudden the Nano will not accept programming
I have been working merrily along with CH340 to make Com10 work.  It has been working flawlessly but now I am getting various messages like it can't open the port then the programmer is not responding.  It tries several times before giving up.
This was working fine yesterday.
I tried uploading to a raw board not connecting to anything and am getting the same result.
Suggestions?

Throw away the CH340 and use something that is more likely to last you more than a few days.

I believe CH340 is installed with the IDE.  I did a reinstall and it still shows it.  I have used it for several months just like this.  But I do see your point - since the same problem happens with multiple boards the problem must be in the PC.

OK, problem solved.  I wish I knew enough to be able to say why it worked, but here is what did the trick:
I uninstalled the IDE.
THEN REBOOTED.
Then installed the IDE (version 1.6.10) again, this time not selecting the USB driver.
THEN REBOOTED.
In Device manager it still shows the CH340 driver on COM14
All my sketches and the two libraries (DHT and LCD) in the documents/Arduino directory were unaffected.
And now it will upload to my boards just fine.
This is one of those times where I can't explain why, but I can tell you for sure that it worked for me.  I had tried uninstalling/reinstalling, but without the rebooting in between.  Perhaps that was the crucial step that needed to be taken.

This problem occurs quite often with all the boards. Here is how to troubleshoot it.
1 - Unplug the Arduino.
2 - Upload the program WITHOUT any boards connected to your computer.
3 - Replug your Arduino.
4 - Upload the program WITH your Arduino connected to your PC.
If this doesn't work, read this post by Nick Gammon.

@ Dat Hair Do.----in additon to above answer- you may connect the arduino on another computer running arduino IDE if that possible. If the arduino is detected and works on another different PC than it still ok. That may save time - if you have multiple PCs or can borrow one-if you just want to know your arduino still works.

@ Dat Hair Do ---the idea in the above comment has now been added by Nick Gammon to his post. So its a good idea. I would give try the stuff with it if possible

@yabbadabba, why the hell do you call me Dat Hair Do? Please stop or I'll be forced to flag you.

@yabbadabba - Please read the Be Nice policy

I found a method that works and added it as an answer.  I am glad that it is acceptable to post answers to our own questions as we learn more.  My desire is that this might be useful to others.


text:
How to calculate required amperage of multiple motors?
I a very simple question about calculating the amperage I need to run 5 stepper motors from my Arduino Uno.
If I have 5 28BYJ-48 stepper motors(which are 5V and are said to require about 240mA each) all plugged into 5 separate ULN2003 driving boards, and I wire 4 signal wires from the boards to the Arduino, and connect the two power wires for the board to 5V and GND on the Arduino. What voltage and amperage I need to supply to my Arduino for everything to run properly?
I'm worried because I read that the Arduino cannot handle over one amp but 0.24*5>1, although I don't know if the amperage is additive with each additional motor.
Thanks for any answers!

your question is not about the arduino ... it is off topic here

I don't know if the amperage is additive with each additional motor

Yes, amperage is additive.

the Arduino cannot handle over one amp but 0.24*5>1

That is correct. But the stepper motors should never be powered through the Arduino. You should connect a fitting power supply directly to the stepper drivers. That way the needed current flows past the Arduino, not through it.

What voltage and amperage I need to supply to my Arduino for everything to run properly?

The Arduino runs at 5V, though you can provide 7-12V to Vin/barrel jack. When your motors are rated for 5V, you should provide them with 5V. So it would be fitting to buy one 5V power source to power the Arduino (through the 5V pin or USB) and the stepper drivers.
For the current: A good measure is the stall current of a motor, so the current, that flows, when the motor is driven, but cannot move (due to being physically stuck). Add a bit headroom to this. The mentioned motors are often badly documented, so that you might not be able to find a stall current value. Add more headroom in that case. So I would suggest adding up all the amps and then multiply this value with 1.5 or even 2. Let's take 250mA per motor (for ease of calculation) with 5 motors gives 1.25A. Take at least a 2A power supply. When you want to make sure go directly to 3A. The price difference in that range isn't that much anyway.

Super helpful thanks lot

You said it would be fitting to have a single 5V/2-3A power source for both the Arduino and the motors but can't the Arduino not take over 1A

@KidWithComputer Current is different than voltage. While you need to provide a specific voltage, the current of a power supply is only a maximum, that it can supply. The Arduino will only draw the current, that it needs to work, from the power supply. You could easily use a power supply capable of hundreds of amps, it would still work. The 1A current limit is actually meant for the situations, where you power components through the Arduino, so the current is flowing through it and its components and PCB traces can only handle max current. But this current would be drawn by other components.


text:
Arduino UNO With On / Off Module Switch + Battery Advice
So I have the following connected and the programming works fine when connect by USB
The Parts

1 Arduino UNO
1 Laser Module (KEYS)
1 Rocker Switch Module (Standard 3 PIN)
2 Variation Motors (KEYS)
1 Speaker Module (BIG SPEAKER MODULE)
2 Push Button Modules (Standard 3 PIN)
1 SD Card Reader Module (Generic)
1 3V 1800 amh Battery

The Problem 1
I want to make an On/Off Switch but it doesn't work.
Battery Powers The Arduino Like This: (WORKS)
https://postimg.cc/JHmTwFKc
Battery Powers The Arduino Like This: (NOT WORKING)
https://postimg.cc/V0RKzFVy
PROBLEM 1: Why doesn't this work when it does for the Nano I have here:
https://postimg.cc/SnXHfwPJ
Secondly Here are some pictures of the setup I have
Battery - Rocker
https://postimg.cc/KK6qfjMW
Rocker - Arduino
https://postimg.cc/hXH6y2FM
https://postimg.cc/4HJrvnCg
Wide View Of Project
https://postimg.cc/3WY5Qfkc
The Problem 2
I need advice on what size battery to use the project for 1-2 hours I think I need (5v,7v,9v) but would like some help with which would be best suited or any suggestions you have
What I think it is but need help

The Wiring is wrong (but I have tested it all and its working fine)
The Rocker Module is passing 3V to the UNO (Not enough Power)
The Battery is not powerful enough (I need a bigger battery)
NOOB Problems as its my first project

What I need help with

What battery to use?
Making the On/Off switch work

Thanks for the HELP!!!
BONUS
Here is the code used:
    #include <pcmConfig.h>
    #include <pcmRF.h>
    #include <TMRpcm.h>

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

    //SD card pin
    #define SD_ChipSelectPin 10
    //soundplayer object
    TMRpcm tmrpcm;

    int led = 13;
    //pin numbers
    int buttonpin = 3;
    int lazerpin = 4;
    int buttonpin2 = 5;
    int motorPin = 6;
    int motorPin2 = 7;

    //other values
    int t = 0;
    int val;
    int val2;
    int ammoUsed = 0;
    int prestate = 0;
    int prestate2 = 1;
    int canReload = 0;

    void setup()
    {
      //pin modes
      pinMode(led, OUTPUT);
      pinMode(lazerpin, OUTPUT);
      pinMode(buttonpin, INPUT);
      pinMode(buttonpin2, INPUT);
      pinMode(motorPin, OUTPUT);
      pinMode(motorPin2, OUTPUT);

      Serial.begin(9600);
      if (!SD.begin(SD_ChipSelectPin))
      {
        return;
      }
      else {
        //setup sound
        tmrpcm.speakerPin = 9;
        tmrpcm.quality(1);
        tmrpcm.setVolume(5);
        //play setup sound (user knows the gun is ready)
        playSound(0);
        tmrpcm.disable();
        tmrpcm.stopPlayback();
      }
    }

    //method to call sounds depending on the input
    void playSound(int t) {
      tmrpcm.disable();
      tmrpcm.stopPlayback();

      if (t == 0) {
        tmrpcm.setVolume(5);
        tmrpcm.play("0.wav");
        delay(2980); //time of clip
      }
      else if (t == 1) {
        tmrpcm.setVolume(6);
        tmrpcm.play("1.wav");
        delay(660); //time of clip
      }
      else if (t == 2) {
        tmrpcm.setVolume(5);
        tmrpcm.play("2.wav");
        delay(950); //time of clip
      }
      else if (t == 3) {
        tmrpcm.setVolume(6);
        tmrpcm.play("3.wav");
        delay(620); //time of clip
      }
      else if (t == 4) {
        tmrpcm.setVolume(5);
        tmrpcm.play("4.wav");
        delay(660); //time of clip
      }

      tmrpcm.disable();
      tmrpcm.stopPlayback();

      return;
    }
    void loop()
    {
      val = digitalRead(buttonpin); // check the state of the button
      val2 = digitalRead(buttonpin2); // check the state of the button

      //reload gun
      if (val2 == HIGH && prestate2 == 0 && canReload == 1)
      {
        //reset ammo and play sound with vibrate
        ammoUsed = 0;
        canReload = 0;
        digitalWrite(motorPin, HIGH); //vibrate
        digitalWrite(motorPin2, HIGH); //vibrate
        playSound(3);
        digitalWrite(motorPin, LOW);  //stop vibrating
        digitalWrite(motorPin2, LOW);  //stop vibrating
        prestate2 = 1;

      }
      else if (val2 == LOW)
      {
        //reload let go
        prestate2 = 0;
      }

      //Shooting the gun 1-4 normal. 5 is louder and longer.
      if (val == LOW) // if button is pressed, turn LED on
      {
        digitalWrite(lazerpin, LOW);
        digitalWrite(led, LOW);
        prestate = 0;
      }
      else if (val == HIGH && prestate == 0)
      {
        if (ammoUsed != 5)
        {
          ammoUsed ++;

          if (ammoUsed > 0) {
            canReload = 1;
          }
          else {
            canReload = 0;
          }

          //turn on lazer and virbate
          digitalWrite(lazerpin, HIGH);
          digitalWrite(led, HIGH);
          digitalWrite(motorPin, HIGH); //vibrate
          digitalWrite(motorPin2, HIGH); //vibrate

          //play sound
          if (ammoUsed == 5) {
            playSound(2);
          }
          else {
            playSound(1);
          }
          //after sound lazer and vibrate turn off
          digitalWrite(motorPin, LOW);  //stop vibrating
          digitalWrite(motorPin2, LOW);  //stop vibrating
          digitalWrite(lazerpin, LOW);
          digitalWrite(led, LOW);

          prestate = 1;
        }
        else {
          //no ammo just vibrate and play sound with no lazer
          digitalWrite(motorPin, HIGH); //vibrate
          digitalWrite(motorPin2, HIGH); //vibrate
          playSound(4);
          canReload = 1;
          digitalWrite(motorPin, LOW);  //stop vibrating
          digitalWrite(motorPin2, LOW);  //stop vibrating
          prestate = 1;

        }
      }

    }

Please link to the switch product, that you used. An image is not enough here. We beed to know, how the board uses the switch. Is it just a breakout board for the 3 switch pins or are there other electronics on it? Also please put the images directly in the question, not on an external site. And some of the images are not in focus or rather dark. Please provide good in-focus pictures, so that we can actually see something in them

Good starting project, You need to understand how a switch works, your first does not work you short the battery, draining it very fast. You need only two connections to the switch. Run ground to ground, battery to center pin and arduino to NO pin. Let us know if that works. You can view a few basic electronics tutorials, that will help. Remember we all started the same place you are. Most important have fun!

https://www.geekbuying.com/item/Arduino-2-Mode-Rocker-Button-Switch-Module-Compatible-With-RPi-STM32-343528.html this is the rocker

can confirm its definitly the 2 mode rocker that is wrong.......... as i have just tried it with a push switch to test it. and works fine haha. I tried what you said and the rocker switch does work either (SIG/VCC/GND) connect battery to VCC and SIG to arduino still nothing

So here is the deal (I Kinda Solved It) so I took apart a 9V battery pack with a flip switch in it..... soldered some wired to it and now it works perfectly...... haha
but I would still like the know the reason why the rocker switch module doesn't work.
the only thing I can think of is the Voltage or Amp passed from the Switch Module isn't enough to power the board (as I tried 3 different rocker switches and all acted the same)
Thanks for the help