text:
Joysitck with servo, LED array and buzzer
Does anybody know of a sketch that can turn a single servo 180 degrees clockwise/counterclockwise with the x axis of a joystick, light a bar graph LED with the Y axis, and sound a buzzer when the joystick button is depressed.

With such a specific set of requirements, why not write such a sketch yourself? It's the Arduino way.

We are a bit too new, we have learned each of the parts of the code but we are struggling with the servo control and putting them all together. Check out what we learned about doing lots of commands at once https://arduino.stackexchange.com/questions/48810/emergency-vehicle-make-two-leds-flash-with-buttons-and-a-passive-buzzer-change

Assuming you are new on Arduino: try to create a sketch separately for each component (you can download them mostly). Than if you feel each component works, combine them to get the functionality that you want.

That previous question has an accepted answer with a link to an article on how to multitask with an Arduino. It talks about a state machine. That would be the path to take to be able to handle multiple event triggers and responses.

Oi, @MichelKeijzers - Stop reading my answers before I finish typing them :)

@CodeGorilla Your answer was not posted before I made this remark (but I guess your remark is sarcastic) ... Good answer btw (I upvote it) :-)

Wow -1, harsh from somebody. I am like 11 years old - I am trying.

Michel - Yes it was sarcastic - you know me too well :).  @Jacob - I don't think the down vote was because of your age.  Your question looks like posting here is the first thing you tried, it looks like you didn't do any research, because you haven't mentioned any.  Also because your requirements are so specific most people who post on here would know that there is no chance of there being a sketch that does all that you need.  Your age on here is how long you have been a member and having read your other posts you are a mature 2 YO :)

You have a distinct set of requirements that you could turn into a sketch yourself.  I'm guessing you have never written a program before, in which case the problem really is you don't know how to do what you want to.
So, break the problem down into small chunks.  The less complex a problem the more likely you are to find a generic solution on the web that you can 'borrow'.

How do you turn a servo?
How do you read the position of a joystick?
How do you light a LED bar graph?
How do you sound a buzzer?

I'm pretty certain that you can find pages that tells you how to do each of those in separate sketches.  Once you have each of those working you need to merge the setup functions, making sure they don't over write each other and then tackle the loop functions (which will be more difficult).  BUT I know there are posts on here about how to merge two sketches into one.
I'm 99% certain you will not find a sketch that does what you want.  I'm 99% certain you will be able to coble together a solution that will do what you want if you break it down.
If you get stuck, post the code you have and explain your problem and people will help.
Good luck.

Thanks. We learned how to tackle the loop function bit last week which was cool. Here is the first code we wrote -
the one at the bottom is our best one. https://arduino.stackexchange.com/questions/48810/emergency-vehicle-make-two-leds-flash-with-buttons-and-a-passive-buzzer-change

Added an extra answer to your above post.  I think the answer could also be applied to this question too.


text:
Drive a 12V pump do I need a l293 driver
Me and my girlfriend are working on a small automatic plant watering system. Our first goal is to make an electrical 12V pump suck water out of a bottle.
As we were reading tutorials online we noticed that many people hook up a driver such as the l293 to their arduino in order to control the pump (essentially a brushed DC motor).
http://www.ti.com/lit/ds/symlink/l293.pdf
Our pump is 12V 4.2 W.
My question is do we really need a driver like that for just activating / deactivating the pump ?
In my understanding the driver offers an H-bridge setup allowing to control up to two motors in both directions.
Are there any other reasons to prefer this driver instead of a simple MOSFET / Transistor setup with such a simple use case like ours ?
Thank you for your help.
Best regards

Unless you wish to reverse the direction of the pump without reconnecting the wires in the opposite way, there is no need for a L293. A MOSFET that operates as a switch should be sufficient in your case. You can also try to PWM it and reduce/control the water flow.

I was considering PWM as well. I will go ahead and do some reading on it :)

source: Stack Exchange

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

sort: votes


text:
Arduino Interrupts Classes and Namespace
I'm working inside the Arduino IDE environment and have made a class that builds on the Adafruit RDG LCD with interrupts While looking at how to combine the Attach Interrupt() into my class I came across this post about using namespaces

Why make a class then? What about a namespace?
A class with one instance is like a group with one person in it.
-nickgammon

Understanding that Mr.Gammon is kind of a big deal around these parts, I'd like to understand how to insert/alter my current class into a namespace format. Currently, the most in-depth tutorial I've found is here, but I don't see how I would mix in the Attach Interrupt() function
Right now, my code looks like
/**** Pre-Setup *****/
#define Menu_PIN 3
voltile bool flag;

//Init Class
class LcdMenu : public Adafruit_RGBLCDShield
{
  public:
  MenuFoo()
}
LcdMenu LcdM;

//run Setup
void setup()   /****** SETUP: RUNS ONCE ******/
{
  pinMode(Menu_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(Menu_PIN), ProcMenu, FALLING);
}

void loop()
{
  if(flag){
    LcdM.MenuFoo();
    flag=false;
  }
}

//Handles Inturrupts for Class
void ProcMenu()
{
  flag=true;
}

//define MenuFoo
void LcdMenu::MenuFoo(){[code]}

As I understand it, Implementing a namespace would eliminate the need for the ProcMenu() function making my code easier to read/maintain.

You can move ProcMenu() into the LcdMenu class. It will have to be static and then you can write member function to hide the attachInterrupt() e.g. LcdM.begin(MENU_PIN);

why do you want to implement the screen menu in a class derived from a hardware wrapping class?

I'm trying to follow a principle of inheratence as I understand it the class LCD Menu is a Adafruit_RGBLCDShield As to why overall, I wanted a way to group the LCD functions together.

In this particular instance, and since you are inheriting from a class
of a known library, making your own class makes sense. You just have to
be aware that, although you can in principle have multiple instances of
a class, you can only have one single handler for a particular
interrupt. Thus the handler cannot be a regular method of the class (a
method that knows it has been called for this instance), but it can be
a static method. Such a method is much like a regular function which
uses (abuses?) the class as a sort of namespace.
I would try something along these lines:
class LcdMenu : public Adafruit_RGBLCDShield
{
public:
  LcdMenu();
  void begin([params]) {
    Adafruit_RGBLCDShield::begin([params]);
    attachInterrupt(digitalPinToInterrupt(Menu_PIN), handleInterrupt, FALLING);
  }
  void MenuFoo();
  void update() {
    if (flag) {
      MenuFoo();
      flag=false;
    }
  }
private:
  static volatile bool flag;
  static void handleInterrupt() { flag = true; }
}

volatile bool LcdMenu::flag;

Then you just have to call LcdM.update() in loop().

Don't forget to give your member functions return types... (apart from the constructor of course).

to clarify: begin() is the constructor and the member functions should read something to the effect of void MenuFoo();

Ok so I got the attachInterrupt() function into the class, but when I try to add static volatile bool flag; I get an error saying cckcVoVT.ltrans0.o:(.text.startup+0x838): undefined reference to 'LcdMenu::flag'

@Majenko: Oops! Fixed, thanks! @ATE-ENGE: LcdMenu::flag has to be defined, in addition to being declared. I added that to the code snippet in the answer.

I don't it will change your design.
The main reason to use namespaces is to have an extra 'layer' of hierarchy.
Like a book that can be divided in chapters (classes).
But if you want to combine multiple books (projects) than you use name classes (e.g. to prevent name clashes of equally named class names).

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


text:
Nano v3 dual power source use & detection
I would like to run a Nano 3.0 from both the VIN (mains power supply 7V) and USB power (backup). I understand it selects the highest voltage and switches to VIN at 6.6V. However I am unsure of the following:

How is it possible to detect which power source is being used?
How is it possible to detect if the source has been switched?
How is it possible to detect if the power source NOT in use has been disconnected.

Could you not take a line of each of the inputs and (after suitable level shifting) test them using two of the digital pins?

To check, if VIN is connected, you can connect VIN through a voltage divider to a digital pin (as suggested in the comment of Code Gorilla). For checking the USB connection you would have to connect VUSB to another digital pin. Since VUSB is not exposed on a pin, this could be difficult to do, but it is possible.
But note, that this would also show a disconnect, when the voltage drops (e.g. empty battery). When you want to detect real mechanical disconnects, you need a power jack with an extra switch integrated.
Let's take a look at the schematics: Arduino Nano 3.0 Schematics

The selection of voltage supply is done by the diode D1. If the voltage resultung from the VIN regulator is higher than VUSB - diode_voltage_drop, the diode is closing and the power comes from VIN. If the voltage resulting from VIN is lesser, the current can flow from VUSB. How much power is really drawn from USB depends on the voltage difference.
So - to detect which source is actually used - you can measure the voltage on the diode with an analog measurement with the ADC or through connecting for example a comparator and using a digital pin.
Note that the voltage on the diode can be positive or negative, depending on which source is used.


text:
Will avrdude overwrite the bootloader on my Nano?
I bought an arduino nano (knockoff from Elegoo) and according to the Amazon description it comes with a bootloader.
From what I've read, this means that programming can occur over the usb connection rather than having to rely on a dedicated serial programmer.
I installed the necessary drivers, plugged in the Nano, and ran this command (not to program, just to see if the board would be recognized):
avrdude -p m328p -b 57600 -P /dev/wcbhserial1460 -c arduino
It recognized the board and said it was ready to be programmed. If I then actually go ahead and ask it to flash a hex file onto the board, will the -c arduino argument tell avrdude to use the bootloader or does it just overwrite everything? Can I reprogram multiple times using this command?
I'm using Atmel Studio 7 and am configuring it to call the appropriate avrdude command.
EDIT: According to this answer, the -D flag will program the chip without clearing the flash, allowing the bootloader to preserved. Unfortunately, since the ATmega devices don't support partial flash memory clearing, this will only work once. So essentially I need to reupload the bootloader each time, which kinda defeats the purpose of it right?
It looks like though he is talking about using an AVRISP, so does all that not apply if you're just programming using the bootloader and the usb connection in the first place?

if you write over ICSP header, the bootloader will be erased. if you use bootloader to write hex over UART the bootloader will stay


text:
How do I create boundaries for the possible values of an integer?
I want to create an integer whose total value cannot go beyond a range of numbers when added to and subtracted from. For example, if the "total_value" started at 0 (of a total possible range between -5 and 5), and then, using a button that added 1 to the total value, I got to 5, if I was to press it again it would not go to six but either reset to 5 or block another input of +1.
How would I go about achieving something to this effect?
Liam

This is about Arduino, not a programming school.

You are probably looking for the constrain() macro (an existing implantation of clamp logic, credit goes to @Edgar Bonet)
value = constrain(value + input, -5, 5);

If you get tired of writing constrain() you can even wrap it in a new type (which might be over-engeneering), producing something like following(code not tested)
template<typename T>
struct BoundValue {
    T value;
    const T vmin, vmax;
    //similar for other operators +,/,-=,...
    decltype(*this)& operator+=(T operand) { value = constrain(value + operand, vmin, vmax); return *this; }
    operator T() const { return value; }
    BoundValue(const T& vmin, const T& vmax) : vmin(vmin), vmax(vmax) {}
    BoundValue& operator=(const T& other) { value = constrain(other, vmin, vmax); return *this; }
};

and use like variable of its argument type
BoundValue<int> val(-5, 5);
val += 6;//val = 5

No need to write clamp(): you can use constrain().

Total overkill.

@EdgarBonet good catch, kind of unusual name choice by Arduino though(at least for my computer graphics background) - no wonder I had trouble to finding it.

@LookAlterno kind of agree, there are people who love shiny code though (myself included), its interesting for fun projects. For serious ones not so much due to the other issue being its super-easy to introduce errors when not being careful with c++ constructors/operator overloading. The clamp/constraint is definitely the way to go though.

@wondra. You have to give an answer at the poster's level. If he can't deal with a normal boundary check, an answer with Template, references, operator overload and whatever is not going to work for him. NickGammon gave an answer more appropiate to the poster's habilities.

@LookAlterno reformatted the answer a bit to make the important part stand out.

For adding:
total_value = total_value + 1;
if (total_value > 5)
  total_value = 5;

And for subtracting:
total_value = total_value - 1;
if (total_value < -5)
  total_value = -5;

You may find a C or C++ tutorial very helpful.

Another method for adding:
if (total_value < 5)
  total_value++;

And for subtracting:
if (total_value > -5)
  total_value--;

Thank you for your response, I did try the first method before I posted but I must have mucked something up because it didn't work.

if (++total_value > 5) total_value = 5  and if (--total_value < -5 ) total_value = -5. The use of prefix operators can achieve the same effect and make the code more concise.

@AJD. Nick's way is safer. Using ++/-- inside expressions is going to give headaches sooner or later.

You can not create a number with arbitrary upper and lower limits.  It is common in the C language to create an integer comprised of 16 bits.  Such an integer has a minimum of:
-(2^15) = -32768

...and maximum of:
(2^15) - 1 = +32767

Instead, after pressing the positive button, consider testing if "total_value" is 5 and skipping adding 1 to "total_value" if TRUE.  Conversely, after pressing the negative button, consider testing if "total_value" is -5 and skipping subtracting 1 from "total_value" if TRUE.


text:
How do I connect my Ublox neo 6M GPS Module with arduino mega 2560?
I tried connecting RX of GPS to Pin 18 and TX of GPS to Pin 19 but I get an error that No GPS is detected,check wiring.VCC of GPS to 5V.
I have set baudrate to 115200.I am trying DeviceExample code of TinyGPS++ library.

Have you checked that is the correct baud rate?  Most GPS work at 19200.
If you want more information you need to flesh out the question.  Add a circuit diagram and a link to the GPS datasheet.

The default baud rate for ublox NEO-6M GPS devices is 9600, not 115200.
And try NeoGPS.  It's smaller, faster, more accurate, more reliable and it comes pre-configured to use Serial1 on a Mega.  Be sure to read the Installation instructions.  If it doesn't work, follow the Troubleshooting pages and try NMEAdiagnostic.ino.
NeoGPS has an example sketch (ubloxRate.ino) that can configure the NEO-6M to other baud rates, once you get the basic programs working at 9600.


text:
When i press a button to subtract 1 from 5 it skips to 3
When i press a button to subtract 1 from 5 it skips to 3, it's the same when I add 1 to -5 it skips displaying - 4 and goes straight to -3.
This is the code that i am using:
//Testing the use of addition and subtraction with the menu options.

#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
int calc_total;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){
    adc_key_in = analogRead(0);

    if (adc_key_in > 1000) return btnNONE;

    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 150)  return btnUP;
    if (adc_key_in < 300)  return btnDOWN;
    if (adc_key_in < 450)  return btnLEFT;
    if (adc_key_in < 700)  return btnSELECT;

    return btnNONE;

}

void setup(){
   lcd.begin(16, 2);
   lcd.setCursor(0,0);
   lcd.print (calc_total);

}

void loop(){

   lcd_key = read_LCD_buttons();
   calc_total = constrain(calc_total, -4, 4);

   switch (lcd_key){

       case btnRIGHT:{
            lcd.clear();
            calc_total = calc_total - 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
       case btnLEFT:{
            lcd.clear();
            calc_total = calc_total + 1;
            lcd.print (calc_total);
            delay(700);
            lcd.setCursor(0,0);
            break;
       }
     }
}

You are not debouncing your keypad. Anything can happen.

Bouncing shouldn't be a problem because of delays. I wonder if you know what the constrain function does?

i thought it stops the value from going above or below a certain point, is that wrong?

Yes, but you should be doing it after (or in) increment. Something like  calc_total = constrain(-4,4, calc_total + 1);. Otherwise you are displaying invalid value -5 that'll get contstraned to -4 in next loop.

Your main problem is that you aren't looking for a change in buttons. You're only doing your adding or subtracting while a button is pressed.
That means, all the time you're holding btnLEFT in your total is incrementing until it hits your limit.
You need to remember the button state from the previous iteration of loop() and compare it to the current state - and only if they differ do you need to do anything.
Also you should perform your constrain immediately after your addition or subtraction. As it is, you add or subtract, display the new value (I assume you do - I don't see the code for that), and only afterwards do you then chop the value back down to +/-4 (assuming it's outside the range). So your 5 becomes 4, and your next subtraction takes you to 3.

I had that problem before but adding in the delay seemed to make it stop, if I press and release the button it adds 1 and the other subtracts 1 fine until gets to 5 -1 or -5 +1, it can do 4 +1 or -4 -1, and all the values in between.

Also see my edit.

Thank you, adding the constrain immediately after the calculation has worked.

The whole point of constrain function is to keep the values between -4 and 4 (including). In your code you can go to the -5 and show it, but right after that it's adjusted to -4 (and you are not displaying this value).
If you increment this value, you can get only result and this is  -4 + 1 = -3.


text:
Using timer2's ISR instead of timer1's in Arduino wiring.c breaks Serial object
I want to change timer0 frequency because I need to use 4 PWM pins at a frequency lower than 500Hz and the SPI on an ATmega328. So I changed timer2 to Fast PWM with 64 divisor, enabled the overflow interrupt for timer2 and disabled the overflow interrupt for timer0:
  TCCR2A = _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS22);
  TIMSK2 |= (1 << TOIE2); // enable overflow interrupt for timer2
  TIMSK0 &= ~(1 << TOIE0); // disable overflow interrupt for timer0

and changed the ISR vector in wiring.c from ISR(TIMER0_OVF_vect) to ISR(TIMER2_OVF_vect).
But delay doesn't work. What can be the problem?

I would guess Serial and delay rely on timer 2 and you have just changed it.

HardwareSerial does not use timers. delay uses Timer 0.

Please post a Minimal, Complete, and Verifiable example.

I don't know if millis() and micros() work - why not? Write a "blink" sketch and find out.

Now everything works except for delay()

delay() uses micros() and micros() reads the hardware registers, like this:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t = TCNT0;
#elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t < 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.

This fixed it. Strange that micros() works fine without the fix?

Appeared to work. I'm sure over a longer interval you would have seen anomalies.


text:
Assign string to an array value
I need to assign a string to an array value:
char mystr[3] = "Hello";
But when I run this code on arduino simulator: tinkercad.com, I get this error:
1:17: error: initializer-string for array of chars is too long [-fpermissive]
Why I'm getting this error?

I'm voting to close this question as off-topic because it's a programming question, not an Arduino one.

You have asked the compiler to allocate 3 char of memory, and then you ask it to fill that memory with 6 bytes of data (5 characters, plus null-char for termination.)


text:
Do Arduino Megas Burn Out?
Im building a bedside alarm clock/home assistant. I have a few buttons that input, an LCD display and some RGB LEDs. The LCD and RGBs are only on when commanded to be on. I was wondering if I could leave the mega plugged in and constantly running or if that would burn it out. Im a bit new to this so sorry if this is dumb. If it would burn out, how long is its lifetime?

This has been covered here several times before.

As long as you operate the electronics within specification they will run for years and years. The first thing to probably fail will be the electrolytic capacitors that will dry out after maybe 10 years.
When reading datasheets and specifications the metric you are interested in is the MTBF - the Mean Time Between Failures.


text:
Trouble with Arduino -> PSOC4 communications over I2C! (Multi master/ slave config)
Hello Stack Exchangers!
I am currently working on a project which requires me to use PSOC4 - 049's to scan a series of inputs, and feed this data back to an arduino over I2C.
The arduino, or in this case a teensy 3.5, is the main unit which hosts a UI and retains key system variables. I wish to have the teensy send a few unsigned bytes to the arduino, and when user input is detected have the PSOC act as the master and send relevant information back to the arduino.
Unfortunately I've been trying for about a week now to no avail.
Currently I have 2 Teensy 3.5s sitting on my I2C bus and 1 PSOC4.
I send the first teensy a 'H' or 'L' character from a terminal over USB and it turns an LED high or low respectively,
This teensy then relays this character over the I2C Bus to the other teensy at address 0x10, which also toggles an LED.
The idea is that the first teensy then also forwards a value to the PSOC at address 0x11 but this simply isn't working for me!
I can't seem to get a single byte over to the PSOC let alone set up the full MMMS system I need!
Does anyone see what I'm doing wrong or have a good simple example of a PSOC project using Multi Master Multi Slave?
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
ARDUINO MASTER CODE     (Might be doing something wrong)
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
(Note that this function is part of a much larger project and is just being called from main at this time, much of the project is removed here but should not effect this code in any way)
#include <Wire.h>
void setup()
{
     Wire.begin();
     Serial.begin(9600);
}

void loop()
{checkCommand();}

byte I2CTargetAddr[8] = {0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17}; //       Declares the addresses of the PSOCs

void checkCommand() // Reads Serial Commands H or L, sets an LED, then     relays the instruction (hopefully) to the PSOC to do the same thing.
{
  static int CCFR = 1;

  if (CCFR == 1)
  {
    pinMode(36, OUTPUT);  // Debug LED
    digitalWrite(36,HIGH);
    CCFR = 0;
  }

  char c;
  static char previousC = 'L';

  static byte low = 0;
  static byte high = 255;

  Wire.setClock(100000); // Set to 100kHz

  while(Serial.available())
  {
    c = Serial.read();

    if(c == 'H')
    {
      Wire.beginTransmission(I2CTargetAddr[0]);
      Wire.write('H');
      Wire.endTransmission();
      digitalWrite(36, HIGH);
    }

    else if(c == 'L')
    {
      Wire.beginTransmission(I2CTargetAddr[0]);
      Wire.write('L');
      Wire.endTransmission();
      digitalWrite(36, LOW);
    }
  }

if(c == 'H')
{
  Wire.beginTransmission(I2CTargetAddr[1]);
  Wire.write(high);
  Wire.endTransmission();
  //digitalWrite(high, HIGH);
}

else if(c == 'L')
{
  Wire.beginTransmission(I2CTargetAddr[1]);
  Wire.write(low);
  Wire.endTransmission();
  //digitalWrite(low, LOW);
}

  previousC = c;
}

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=
ARDUINO TEST SLAVE CODE  (Seems to be totally fine)
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=--=-=
#include <Wire.h>
#define LED_1 23  // PWM Capable LED Pin

void setup()
{
  Wire.begin(0x10);
  Wire.onReceive(receiveEvent); // Calls the receiveEvent function when     something happens to the I2C bus
  pinMode(LED_1,OUTPUT);
  digitalWrite(LED_1, HIGH);
}

void loop()
{
}

void receiveEvent(int howMany)
{
  while(Wire.available())
  {
    char c = Wire.read();

    if (c == 'H'){digitalWrite(LED_1, HIGH);}
    if (c == 'L'){digitalWrite(LED_1, LOW) ;}
  }
}

=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=
PSOC 4 Code
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=-=-=-==-=--==-=-=-=-=-=-=
The topdesign includes a bootloadable component, a pin for LED Extern and LED Local, and an i2c block set as multi slave/ multi master at 100kb/s
-------------------------------MAIN.C---------------------------------
#include <project.h>
#include <main.h>

extern uint8 I2CSlaveIn[BUFFER_SIZE];
extern uint8 I2CSlaveOut[BUFFER_SIZE];
extern uint8 I2CMasterIn[BUFFER_SIZE];
extern uint8 I2CMasterOut[BUFFER_SIZE];

/* Fast BootLoad ISR */
CY_ISR_PROTO(bootloadISR_Handler);

CY_ISR(bootloadISR_Handler)
{
    Bootloadable_1_Load();   // Forces a restart of the bootloader,     triggered by the onboard button.
}

int main(void)
{
    BootLoadSys_Start(); // Initialise easy bootloader tool
    bootloadISR_ClearPending();
    bootloadISR_StartEx(bootloadISR_Handler);

    initI2C(); // Initialised i2c

    CyGlobalIntEnable; /* Enable global interrupts. */

    uint8 transferredIn[BUFFER_SIZE];
    uint8 byteCount;
    uint8 lastVal = 0;

    LED_Local_Write(0);
    int i;

    for(;;)
    {
        if (0u != (MYI2C_I2CSlaveStatus() & MYI2C_I2C_SSTAT_WR_CMPLT)) //     Wait for master to complete Write
        {
            byteCount = MYI2C_I2CSlaveGetWriteBufSize();
            MYI2C_I2CSlaveClearWriteStatus();             // Take a wild guess

            for (i =0; i<byteCount; i++)
            {transferredIn[i] = I2CSlaveIn[i];} // Copy data from the buffer

            MYI2C_I2CSlaveClearWriteBuf();
        }

        if (transferredIn[0] != lastVal)
        {
            if (transferredIn[0] == 255u){LED_Local_Write(1);}
            if (transferredIn[0] == 0u  ){LED_Local_Write(0);}
        }

        lastVal = transferredIn[0];

    }
}

----------------------------------I2C.C------------------------------------
#include "project.h"
#include "i2c.h"
#include "main.h"

uint8 I2CSlaveIn[BUFFER_SIZE];
uint8 I2CSlaveOut[BUFFER_SIZE];
uint8 I2CMasterIn[BUFFER_SIZE];
uint8 I2CMasterOut[BUFFER_SIZE];

void initI2C()
{
    MYI2C_I2CSlaveSetAddress(MY_SLAVE_ADDR);

    MYI2C_I2CSlaveInitReadBuf( (uint8 *)I2CSlaveOut  , BUFFER_SIZE);
    MYI2C_I2CSlaveInitWriteBuf((uint8 *)I2CSlaveIn  , BUFFER_SIZE);

    MYI2C_Start();  // Calle after buffer setup
}

----------------------------------I2C.h----------------------------------
#define BUFFER_SIZE 1u // Sets Buffers size
#define MY_SLAVE_ADDR 0x11u

void initI2C();

You need to get your slaves communicating properly first. I would strongly suggest dropping multi-master and have the PSoC use a GPIO line to signal the Teensy master to read it, instead of swapping masters. Much simpler implementation.

This won't work due to the needs of the system architecture.
Arduino -> PSOC commands will be only issued very occasionally, whereas the the PSOC(s , there are 8 of them)
Will be sending information whenever the user interacts with the hardware.
It's important that I minimise the amount of time spent communicating

Design-wise you should consider keeping the drivers separate from the rest of the application. Your current design is so-called "spaghetti", where all files are died together with global variables. This will quickly become unmanageable as the program size grows.

@lundin Yeah, it's just a test programme so I'm not too worried about that at the moment, just want to get it working.
Also, I love having a dangerous amount of globals, puts a little bit of excitement in my life ;)

So it turns out I'm an idiot.
At some point in the last day or so I must have accidentally changed the pins that the I2C component is assigned to.
This code (or at least code very similar to this, after a couple of minor changes) works perfectly for the slave side.
Feel free to make use of it if you need it!


text:
running a dc motor with a small L298N module and an arduino and the L298N library
I have a small L298N module which I would like to use to run a couple of dc motors. The module I have is smaller than most of the ones you see on eBay, it looks like this...

I am trying to use the following library :
https://github.com/AndreaLombardo/L298N
I have managed to get the motor going forwards and backwards, but the problem is, this module doesn't have a pin for enable ( EN for PWM from the Arduino) and the library seems to require this; therefore I can't control the speed of the motors.
Does anyone have any experience with these modules? Is there a different technique I should be using? Is there another library that works with these kind of modules?
All help appreciated.

PWM is used to control the duty cycle and not the voltage directly so your PWM will work directly on the input pins of motor driver and you will be able to control the speed.
just use analogWrite on the input pin which was held HIGH and HOLD the other pin to LOW. If you desire to change the direction while simultaneously controlling the speed. just analogWrite both the pins. Just keep in mind that the duty cycle of both the pins should not be tweaked simultaneously. while the speed is being controlled in one direction the other pin should be at analogWrite(other,0).

Thanks very much for the answer. Do you know of any libraries that will handle the pin writing such that I can just send an int for speed / direction? ( similar to the other library I referenced ). Or do you have some example code of how to set the speed manually?

you can use this snippet in your code if you want
void Loop()
{
   //this is basically to demostrate how you can control the speed
   // and direction simultaneously
   for(i=0;i<256;i+=51)
   {
      analogWrite(motorForwardPin,i);
      analogWrite(motorBackwardPin,0);
      delay(2000);
   }
   for(i=0;i<256;i+=51)
   {
      analogWrite(motorForwardPin,0);
      analogWrite(motorBackwardPin,i);
      delay(2000);
   }
}

and it's better if you don't use a library for this purpose.


text:
Not able to control digital pins using commands sent via HC-05 module
I am trying to control the LED on pin13 using the below code but it's not working.
With this code I am able to print to the Serial Monitor but the code has no effect on the any of the digital pins. I am unable to control the LED and so I have gotten stuck and can't advance further. I can't understand why it is happening even if I have excluded the new line from the Bluetooth app that I am using to send the strings and same on the Serial Monitor.
#include<SoftwareSerial.h>          // import the serial library

SoftwareSerial bluetooth(6, 7);     // RX, TX

void setup(){
  Serial.begin(9600);               //set baud rate
  bluetooth.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}

void loop(){
  while (bluetooth.available()){
    char ch = bluetooth.read();
    message += ch;
  }

  if(!bluetooth.available()){
    if(message != ""){
      if(message.equalsIgnoreCase("on")){
        digitalWrite(13, HIGH);
      }else{
        digitalWrite(13, LOW);
      }
      Serial.println(message);
      message = "";
    }
  }
}

What is the output of the serial terminal? That is exactly what is reaching the code, so this would help alot. I will update my answer, when you provide more information. Also: How have you connected the HC-05? Did you use a voltage divider for it's RX line? (The HC-05 works with 3.3V and most Arduino boards with 5V) And the if-statement if(!bluetooth.available()) isn't necessary here, because when you are leaving the while loop there is nothing available, unless it is received on this few clock cycle of the execution between.

the serial monitor outputs "on" as 'o' and 'n' in separate lines. bluetooth terminal on my phone doesn't print anything. But the code works fine if I am using the normal (Rx,Tx) pins, the terminal on my phone also prints the strings it sends,that works fine even without the voltage divider. I just don't want to engage the pins(1,2). I don't know if there is a problem with the SoftwareSerial library

the chars come slower over SoftwareSerial and your code doesn't wait for them. if next char is not available immediately  you continue in loop

please elaborate I tried while(blurtooth.available()==0);  to wait for the data but that is not working;

I was basically getting the problem due to some garbage values flowing in and I managed that by using if(message.substring(0,2).equals("on")). and now it works fine

Your logic is a complete mess.  You have:

If a character is available, read it and add it to message.
If another character is available, compare what you have already stored with on.

If it's equal ('o' is not equal to 'on') turn on, otherwise turn off.
Print what you have stored.

Forget what you stored
Go to 1 (a character is still available since you never read it in stage 2).

Instead you need something more like:

If a character is available, read it into a variable.
If the character you read is a line ending character:

Compare your message with 'on' and take appropriate action

If the character you read is not a line ending character:

Add the character to message.

Go to 1.

Note how you only check once if there is a character available, and all your testing is done within that one if block.

so i basically tried that but it's  not working

Comments are not places to dump code.

really srry about that


text:
Send an multidimensional array of values from one arduino to another through serial port
I have connected two arduinos using pins: RX and TX and managed to send a string as an array of values:
//sender

char mystr[6] = "hello";

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

void loop() {
  Serial.write(mystr);
  delay(1000);
}

And receive it:
//receiver

char mystr[6];

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

void loop() {
  Serial.readBytes(mystr,5);

  if(mystr[0] == 'h' && mystr[1] == 'e' && mystr[2] == 'l'){

    for(int i = 0;i < sizeof(mystr);i++){

      Serial.print(mystr[i]);

      if(i == sizeof(mystr) - 1){
        Serial.print("\r\n");
      }
    }
  }
  delay(1000);
}

That worked fine! But I need to send and receive something like this:
int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

How can I do that?

CSV seems to match your needs.

Use two for loops to send the multidimensional array, and two for loops to receive the multidimensional array.
Sending:
int a[3][4] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      Serial.print(a[x][y]);
   }
}

Receiving
for (int x = 0; x < 3; x++)
{
   for (int y = 0; y < 4; y++)
   {
      a[x][y] = Serial.read(); // Not sure about the exact prototype
   }
}

If the sizes are fixed (like in your case 3 and 4), than you don't have to send the dimensions, just sent the values in order: 0, 1, 2, 3, 4, ... like above.
And when receiving them you know the first four values belong to row 0, next four values to row 1 etc.
If you need dynamic sizes, first send the number of rows and columns and than the values.
In that case instead of 3 and 4 define two constants and use them:
#define NR_ROWS 3
#define NR_COLUMNS 4

int a[NR_ROWS][NR_COLUMNS] = {
   {0, 1, 2, 3} ,
   {4, 5, 6, 7} ,
   {8, 9, 10, 11}
};

for (int x = 0; x < NR_ROWS; x++)
{
   for (int y = 0; y < NR_COLUMNS; y++)
   {
      Serial.print(a[x][y]);
   }
}

This doesn't work. Serial.print sends the integer as a string and Serial.read() then reads the ASCII value of a single digit. This makes it impossible to receive numbers with multiple digits like 10 and 11.

The code also never checks if Serial.read() returns -1. Which happens because it gets desynced from the previous problem. Or it could happen during the array transmission, because nothing guarantees that the array gets transmitted in a single chunk.

And the array consists of int elements, so it should send and receive two bytes per element.


text:
Arduino TimerOne breaks the program when calling "digitalRead"
I'm trying to make this project.
But i have a problem running this code. It appears to be val = digitalRead(inPin); breaks entire program. just because i call this from the callback function which attached as an interrupt function Timer1.attachInterrupt(callback);
Here is the more simplified problem simulation program,
#include "TimerOne.h"

int inPin = 7;   // sensing digital pin 7

int val;

void setup() {
  pinMode(inPin, INPUT);      // sets the digital pin 7 as input to sense receiver input signal

  Serial.begin(9600);
  Timer1.initialize(8);  // initialize timer1, and set the frequency; this drives both the LC tank as well as the pulse timing clock
  // note: modify this as needed to achieve resonance and good match with the desired tags
  // the argument value is in microseconds per RF cycle, so 8us will yield RF of 125kHz, 7us --> 143kHz, etc.

  Timer1.pwm(9, 512);

  Timer1.attachInterrupt(callback);
}

void callback()
{
  val = digitalRead(inPin);//once you comment this line, it works fine
}

void loop() {
  Serial.print("Program running \n");

}

Any help is much appreciated.

I give you +1 point for taking care of reducing your code to the minimum that show the problem.

The time between 2 interrupt triggers is only 8us. Also digitalRead() is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.
void loop(){
  noInterrupts();
  Serial.print("Program running \n");
  interrupts();
  delay(1000);
}

Now the interrupts are disabled during the execution of the Serial.print(), so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.
The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to this side), which works much faster.
Also you should consider making the variable val volatile, since it will can change everytime through your interrupt service routine.

Thanks mate, It all makes sense. And i'll try this out and let you know how it went. Still i wonder how the tutorial worked for them at some point, Perhaps it was an older Arduino core?

I'm not sure about how the tutorial worked for them. On a quick look I see, that they are not sending serial in every loop cycle, but only when special conditions arrive. Not sure about how this changes the problem. To be sure you would have to measure the length of the interrupt routine with an oszilloscope


text:
I2C communication between Attiny85 as master and arduino UNO as slave
I want to make my Attiny85 and my Arduino UNO communicate together with I2C protocol. Since Attiny do not support Wire library, I use TinyWire by lucullusTheOnly and Wire on the Uno.
The Attiny is sending data as the master to the Uno, the slave.
Here is my code:
Master
#include <TinyWire.h>

byte slave_address = 10;

void setup() {
    // config TinyWire library for I2C master functionality
    TinyWire.begin();
}

void loop() {
    TinyWire.beginTransmission(slave_address);
    TinyWire.send('c');
    // endTransmission sends the bytes in the buffer to the slave and returns 0 if there was no error
    TinyWire.endTransmission();
    delay(500);
}

Slave
#include <Wire.h>

void setup() {
  Wire.begin(10);                // join i2c bus with address #10
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

I connect the pin like this :
Arduino --> Attiny
SCL ---- PIN 7
SDA ---- PIN 5

I try to pull-up the clock and data line with 2.2k resistors but nothing happened, I receive nothing on the Uno from the Attiny.
Any idea ? Thanks !

Also asked at: http://forum.arduino.cc/index.php?topic=524760 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

As per Stackexchange rules, I don't think he is obligated to post links to other forums where he has asked for an answer. It's his choice. Nevertheless, thanks for posting the link to the forums, it helps other readers.

The pure master functionality of the TinyWire library is currently buggy. As a work around you can initiate the library on the ATTiny also as a slave with an address. When the endTransmission() function is called, the library switches temporarily to master mode for sending the bytes. I've tested this with your code in my own setup and it works. (Be sure, that the frequency in the ATTiny is set right. I tested the library only for 8MHz. For my own ATTiny's I had to do an extra step and set the correct fuses with avrdude)
I think the pure master part is blocking itself after the first transmission. I will add an issue in the github project. Maybe I can fix this in some time.
Chrisl aka lucullusTheOnly
EDIT: I had to think about this and looked into the library. The problem was found easily. In twi.cpp there is a NOISE_TESTING define block in the master send/receive function, which is constantly triggering error #6 (unexpected stop condition). In slave mode this doesn't happen, because directly before sending as a master it calls the master init function, which clears all USI flags, including the stop condition flag, that is polled in the send/receive function.
I have deactivated the NOISE_TESTING in the github project. If you don't want to download the current version, you can just open twi.h and comment the definition of NOISE_TESTING.

I finally move to the Serial library but I will test your new code soon!

I have the same issue even though I have the latest Github version with the NOISE_TESTING define block disabled.
I believe it has something to do with the line 359 in TWI.cpp where the stop condition isn't issued if a NACK happens:
      if( temp_result.result & (1<<TWI_NACK_BIT) )
  {
    if ( USI_TWI_state.addressMode )
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
    else
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
    return (FALSE);
  }

I think it should be :
      if( temp_result.result & (1<<TWI_NACK_BIT) )
  {
    if ( USI_TWI_state.addressMode )
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_ADDRESS;
    else
      USI_TWI_state.errorState = USI_TWI_NO_ACK_ON_DATA;
    USI_TWI_Master_Stop();
    return (FALSE);
  }

I tried it on ISIS in pure master only and it worked. I don't know if this is a viable solution or if it will cause any conflict with how the rest of the lib works.

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


text:
How do i run multiple functions simultaneously on a LCD screen?
I have little to no experience in programming and i'm very slowly and gradually getting the hang of it. My next project is that i'm making a clock, and wanted to use multiple functions for the hour:minute:seconds instead of just using one for everything. But after reading some i came to the conclusion that the arduino can only run one function at a time. So my question is how can i make the illusion of multiple functions running simultaneously on a LCD screen.
My code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     144
#define btnDOWN   329
#define btnLEFT   504
#define btnSELECT 741
#define btnNONE   5

int read_LCD_buttons()
{
 adc_key_in = analogRead(0);

 if (adc_key_in > 1000) return btnNONE;
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;
 return btnNONE;

}
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

void Second(){
  int First_Digit = 0;
  int Second_Digit = 0;

  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      }

    lcd.setCursor(0, 0);
    lcd.print(First_Digit);
    lcd.setCursor(1, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      Second_Digit = Second_Digit - 10;
      }

  }
}
void Minute(){
  int First_Digit = 0;
  int Second_Digit = 0;
  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      }

    lcd.setCursor(3, 0);
    lcd.print(First_Digit);
    lcd.setCursor(4, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;
      lcd.print(First_Digit);

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      Second_Digit = Second_Digit - 10;
      }

  }
}

You ought to be able to write to specific positions on the LCD by specifing setCursor() as you have. Is this not working? If not, please describe what it displays, and what you want to see it display?

imagine that you are cooking a pot of stew and a pot of soup.  you have to stir the stew every 10 minutes and you have to stir the soup every 15 minutes.  you have a clock that displays time and beeps every minute. what process do you use for that scenario if you have other things to do? (your LCD program will do something very similar)

@josecanuc It's only showing the Second() function on the first line and nothing else, i want to see the Minute() function beneath that on the second line.

@jsotola i think you're referring to the millis() command which shows the amount of milliseconds that have passed after you start a program. But how could i integrate that in my code so that it seems like they're both shown on the lcd simultaneously.

Examine closely the non-popular-enough Arduino example called BlinkWithoutDelay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay  Your problem is that the use of delay() as you guessed. You need to think about your program flow as though loop() runs millions of times per second, but you only want to execute a particular function less frequently. Expand to running multiple functions at different frequencies.

@josecanuc But a function can't have a high or low state, it's not attached to a pin so how would i translate that example to printed values? Sorry that i'm terrible at this but thanks anyway for your patience.

See my answer -- but the digitalWrite() call in the BlinkWithoutDelay example is a function call, not a pin.

@josecanuc It's still not functioning properly and i have absolutely no idea what i can do, all i can see now is that there are number, rapidly changing. i've integrated your code into mine but i can't for the life of me find the solution, i've tried tinkering with the Blink Without Delay and all it did was make me feel more stupid :D.

Do you understand how BlinkWithoutDelay works, and how it's different from the standard Blink? Do you understand why? Update your question to show your new code that's still not working.

Yes instead of using delay, which pauses the program. it uses millis and if the millis exceeds the interval it changes the value of the pin from either high to low or low to high. it does this every second because the currentMillis gets larger everytime but so does the previousMillis so that it needs another 1000 milliseconds before it can run the if statement again. The ledpin and ledstate i don't fully understand because i'm terrible at hardware. Neither do i understand the digitalwrite but i thought it was unnecessary for my sketch. I'll upload all of my code this time.

My answer updated to reflect the new code sample.

Use the state machine model shown in BlinkWithoutDelay
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

With this example, Second() is called only when the difference between "now" and the last time it was called is greater than secInterval. Likewise for Minute().
[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.]
EDIT BASED ON UPDATED CODE SAMPLE
Issue 1:
In both your Minute() and Second() functions you have a sequence like:
lcd.setCursor(0, 0);
lcd.print(First_Digit);
lcd.setCursor(1, 0);
lcd.print(Second_Digit);
lcd.clear();

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.
Issue 2:
At the start of the Minute() function, you have the following:
int First_Digit = 0;
  int Second_Digit = 0;
This means the variables First_Digit and Second_Digit are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as static so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:
static int First_Digit;
static int Second_Digit;

and similarly in the Second() function.
You're correct that digitalWrite() is not needed in your function as it is described. digitalWrite() is for changing a physical pin on the Arduino to a LOW or HIGH value (that is, a 0V or 5V voltage.) In the Blink without Delay example, ledPin and ledState are just variables to hold the pin identifier for the blinking LED, and the current state (LOW or HIGH) of that pin. Again, not necessary for your code, as you have described it.
SECOND UPDATE
Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the for loop in the Minute() and Second() functions, but it's unnecessary.
You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:
void Second() {
  static int second;

  second++;
  if (second>59) {
    second = 0;
  }
  lcd.setCursor(0, 0);
  lcd.print(second/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(second % 10); // Prints the remainder after dividing by 10
}

void Minute() {
  static int minute;

  minute++;
  if (minute>59) {
    minute = 0;
    // Probably want to increment an Hour counter here?
  }
  lcd.setCursor(3, 0);
  lcd.print(minute/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(minute % 10); // Prints the remainder after dividing by 10
}

After updating my code i only get what it seems like the function Second, furthermore it's unreadable untill i reset it so that it stops for a moment, and then it shows the correct seconds. So it works but it's unreadable until you stop it. Any solutions to this?

Added another part of this answer to deal with the other functions, which are not strictly related to how to run multiple functions simultaneously...

It works properly for each individual part but the hour only shows after an hour and the minute only shows after a minute, how can i display this instantly?

Write the hour and minute in setup() so they run at least at startup


text:
The code fails to generate the values I want, when both trigger pins 2, 3 are high or low. Why?
/*aim of the program is to generate 2 different varying frequency from the
same output which is controlled by 2 triggers*/
void setup()
{
    pinMode(2,INPUT); //setting the trigger pins 2,3
    pinMode(3,INPUT);
    pinMode(6,OUTPUT); //output pin
}

void loop()
{
    if(digitalRead(2)==HIGH && digitalRead(3)==LOW) { //trigger conditions
        infra();
    }
    else if(digitalRead(2)==LOW && digitalRead(3)==HIGH) {
        red();
    }
    else if((digitalRead(2)==HIGH && digitalRead(3)==HIGH) || (digitalRead(2)==LOW && digitalRead(3)==LOW)) {
        Serial.println('help');
    }
}

void infra() //function varies sinosoidaly (working)
{
    float f;

    for(f=16000; f<=20525; f+=4.525) {
        tone(6,f);
    }

    for(f=20525; f>=16000; f=f-4.525) {
        tone(6,f);
    }
}

void red() //function varies sinosoidaly (working)
{
    float p;

    for(p=25000; p<=32071; p+=7.071) {
        tone(6,p);
    }

    for(p=32071; p>=25000; p=p-7.071) {
        tone(6,p);
    }
}

The third if is unnecesary.

'Fails' means your code never print "help"?. You code never initialize Serial to start with ...

'help' is not a string.

the code fails to generate the values i want ... how does it fail?

@gre_gor I think you have found the problem. Would you care to turn your comment into an answer?

@per1234 OP's code doesn't print anything to serial because he is missing serial initialization. Printing 'help' just prints some number.

To send anything to serial you need to initialize it first with:
void setup()
{
    Serial.begin(115200);
    //other code
}

And you are using wrong quotes for the string.
They should be double quotes " not single ones '.
Also you could simplify your code, if you removed the third if, since it's just checking the already known state at that point.
You should also read the button state only once, save them into a variable and then just compare those variables.
bool button1_state = digitalRead(2);
bool button2_state = digitalRead(3);
if (button1_state && !button2_state) {
    infra();
}
else if (!button1_state && button2_state) {
    red();
}
else {
    Serial.println("help");
}


text:
How can Arduino's 8 bit Microcontrollers handle C++
I have just started getting into Arduino and c++ programming!
For all the talk on the internet about c++ being incompatible with 8-bit and even 16-bit microcontrollers, how is it that Arduino Microcontrollers can safely handle c++ code, in terms of the ram usage? Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) that (I believe) are very ram-usage-intensive?
Cheers!

There are some limitations about what you can do with C++ on an 8-bit Arduino, which come from avr-libc. Note that the linked page states that new and delete are not implemented, but the Arduino core provides an implementation based on malloc() and free().

Huh, it's almost as if  all the talk on the internet wasn't always right.

The width of a processor's instruction word ultimately says nothing about how much memory it has.  There are for example "overgrown" 8051 cores in bluetooth chips with several times more memory than many of the low end 32-bit ARM cortex parts.  That said, classic Arduinos do happen to have quite little RAM, and this makes some expensive patterns severely unwise.

It's a misconception that using constructors or C++ in general requires lots of RAM. Plus, to be clear, the AVR processors like the Micro and Uno have separate RAM and PROGMEM (program memory). So, code for functions does not, in itself, use RAM.
As an example, this small program for the Micro:
int main ()
  {
  }

That uses only 206 bytes of PROGMEM and 0 bytes of RAM (according to the IDE).
Sketch uses 206 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 2,560 bytes for local variables. Maximum is 2,560 bytes.

Adding in a class, with a constructor, and using that class, increases the memory a bit:
class foo
  {
  public:
  int bar;  // some class variable

  foo ()  // constructor
    {
    bar = 1;
    }
  };  // end of foo

foo nick;  // a global variable
int main ()
  {
  PORTD = nick.bar;
  }

That uses 2 bytes of RAM, and 278 bytes of PROGMEM. Hardly a lot.
Sketch uses 278 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 2 bytes (0%) of dynamic memory, leaving 2,558 bytes for local variables. Maximum is 2,560 bytes.

Of course, the more things you do, the more RAM and PROGMEM it takes, however the compiler generates quite efficient code, and the linker strips out things that are not needed by your code.

Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) ...

A lot of libraries use classes and constructors (for example the Serial library, the Print class, and a lot of others). There is nothing inherently RAM-intensive about a constructor. It's just a function that does something, with an implied this pointer to the current instance of the class.

do lambdas work? (from a comment)

Yes you can use lambdas:
// array of function pointers
void (*doActionsArray []) () =
 {
 [] { Serial.println (0); } ,
 [] { Serial.println (1); } ,
 [] { Serial.println (2); } ,
 [] { Serial.println (3); } ,
 [] { Serial.println (4); } ,
 };

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  doActionsArray [3] ();
  }  // end of setup

void loop () { }

as long as you don't (extensively) use: the standard library, exceptions, templates ... (from a comment)

Templates can certainly simplify doing things like writing to, or reading from EEPROM and similar. For example:
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

The standard library? There are implementations for the Arduino. We have to bear in mind that RAM is limited, however if you are going to do something anyway that involves linked lists, etc. then the Standard Template Library will probably do what you want as efficiently as you could if you coded it "by hand".

The bottom line is you need to be aware of what you are coding on. I have seen examples like this:
float foo [1000];  // hold my readings

That blows the available RAM on a Uno straight away. Nothing to do with C++ per se.

The other thing to be aware of is some tricks you can usefully employ. One common one is to replace:
Serial.println ("Program starting.");

With:
Serial.println (F("Program starting."));

The first example causes the compiler to copy the string "Program starting." from PROGMEM into RAM, using some of your valuable RAM. The second example doesn't.

Basically you can use C++ as long as you don't (extensively) use: the standard library, exceptions, templates or rtti (do lambdas work? never tried). Whether you'd want to call the remaining language really 'c++' is another question.

@Voo: On the Arduino, templates are not necessarily a bad thing.

@Edgar Very clever trick, but certainly not the way you'd use templates in general code. A better way to phrase it might be that you have to be very careful with how you use templates since they can very easily lead to large quantities of code being generated behind your back.

@Voo Is that just a limitation of the AVR compiler? GCC and Clang do a pretty good job of optimizing template usage for desktop work. Or is it more an issue with standard-library/etc. templates, which are very general so may have lots of stuff you don't need?

@JAB Ignoring STL templates, it's still easy to introduce code bloat through templates. Here's a dummy example that shows a pretty common issue — defining a template function which includes a large amount of code which doesn't need to be genericized. Those two programs are functionally identical, but through GCC with -O2 on my desktop, bloated.cc generates a 31KB executable while trimmed.cc generates a 14KB executable.

@MattK Ah, I see what you mean. (Though in that case the call to preamble seems like it could be kept in the template function with minimal code bloat rather than being a separate call, unless the compiler decided to inline those calls).

See amended reply for comments on some of those points.

@JAB It's generally recommended for efficient code to try and forward to non-generic functions (e.g. standard libraries cast T's to void* and deal with those). Absolutely doable but makes for awkward programming and is easily forgotten. Nick's template example is pretty similar: Instead of forwarding the byte* and size to a generic function we now have almost identical code multiple times in memory. If you had to write it by hand you'd notice the duplication.

@Voo - I guess the same goes for using other features such polymorphism and inheritance and other OOP features?

@Curious The general gist is that C++ is complex enough that it can be rather hard to know what exactly the compiler is doing in the background. Then you also have to rely on your compiler to do certain optimizations for certain things to be feasible (do you know whether your compiler does COMDAT folding?). It can be done, usually by limiting yourself to certain features, but it's a bit fragile (i.e. a tiny change can lead to very different non-functional behavior).

The talk about C++ being incompatible with small MCUs implies that developers would use features it provides. In a good C++ project you're expected to use vectors and iterators instead of C arrays, throw exceptions instead of returning error codes, use lambda-functions, templates etc.
As long as you don't use those features, C++ memory consumption is manageable. The reason for this is simple: such limited C++ is just a syntactic sugar around C structures and function pointers.
The problems usually start when you write a class which is complex enough that its constructor can fail. Then you have a tough choice to make: start using exceptions and drastically increase memory consumption, or write classes which pretend they never fail to construct (which often results in a program which pretends to work).

AFAIK, the Arduino environment does not support exceptions.

@EdgarBonet It wouldn't be a very useful feature to support anyway, considering most boards have about 2K RAM.

@DmitryGrigoryev Or a third choice - use the constructor to set up the class in a known but non-working state, and have a second "initialisation" function which does all the operations which can fail.  This is a fairly standard design pattern.  If you then use a factory which is a "friend", the second "initialisation" function isn't exposed to the rest of the world, and the factory can legitimately report "I'm sorry, I can't do that, Hal".  This has minimal extra cost compared to just calling a constructor; certainly nothing like as heavy as adding exception handling.

@Graham Possible, but it would mean all error conditions must be explicitly handled in code. You won't be able to simply write f(g(x)), you'll have to wrap every action which could fail in the error-handling code.

@DmitryGrigoryev You say that like it's a bad thing. :)  The second "initialisation" function could just report true/false, or it could be more detailed about the cause of failure.  It's up to you as the coder.  In general though, if you don't understand every error condition, then I'd say you haven't thought enough about your design or code.  If you've done your design properly, there simply is no such thing as an unexpected error.  Sure, there could be errors you think shouldn't happen, but a robust implementation will still cover them.

@Graham Well yes, having to write extra code is a bad thing. Your argument reads a bit like "you shouldn't use default in a switch statement, because if you've done your design properly, there's not such thing as an unexpected value". Exceptions are not unexpected errors, they are errors for which you have no cure but to abort the current action, and possibly try again.

@DmitryGrigoryev Having to write unnecessary code is a bad thing, sure; but having to write more code to do the job properly is not.  Handling errors appropriately really isn't unnecessary. Perhaps it takes more code if you're reliant on downstream functions to throw an exception if "new" fails and you try to dereference a null pointer, for example.  But that's where PC coding and embedded coding differ.  On a modern PC with essentially infinite resources you can generally get away with bad habits like that because it rarely if ever happens; but in the embedded world you can't.

@DmitryGrigoryev "errors for which you have no cure but to abort the current action, and possibly try again" are/should not be very common in embedded environments. Any possible "error condition" (external hardware not ready, transmitted failure, etc) should probably be explicitly handled and thus not really be exceptional.

C++ is fine with Arduinos or other AVR based Systems.
I've been use it for quite a while in a home automation project.
The avr runtime does not support exceptions nor dynamic memory allocation, as has been stated. you can provide an implementation  though.
There is much of C++ left to make use of. here are some examples
Templates
They are very useful because, e.g. they allow to move work from runtime to compiletime. I use template for a replacement of the Arduino HAL functions DigitalWrite and others, without the runtime and code bloat.
compare this
int main(void)
{
        DDRB |= (1<<7);
        while(  (  ( PINB & (1<<6) ) !=(1<<6) ) )
                ;
        while(1)
        {
                _delay_ms(100);
                PORTB |= (1<<7);
                _delay_ms(100);
                PORTB &= ~(1<<7);
        }
}

to this
int main(void)
{
        IOPin<13> ledpin;
        IOPin<12> testpin;
        ledpin.SetDir(out);

        while(0 == testpin.State())
                ;
        while(1)
        {
                _delay_ms(100);
                ledpin.SetHigh();
                _delay_ms(100);
                ledpin.SetLow();
        }
}

The template based version is much more readable, and generates exactly the same assembler code. In the abovementioned linked article i explain the template and why this works.
more on templates
The following code uses the "curiously recurring template pattern" CRTP.
It is used to create a job class, which i use for a primitive scheduling
This template builds a chain of registrable items.
template<class registered>
struct Registered {
    static registered *registry;
    registered *chain;
    Registered() : chain(registry) {registry=static_cast<registered*>(this);}
};

The job class applies the CRTP pattern. The constructor takes the actual callback where the work is done, and how often the job is done.
class Job : public Registered<Job>
{
    voidFuncPtr m_p;
    uint16_t m_periodic;
    uint32_t m_lastrun;
    uint16_t m_initialdelay;
    public:
    Job(voidFuncPtr p,uint16_t periode=0,uint16_t initialdelay=0):m_p(p),m_periodic(periode),m_lastrun(0),m_initialdelay(initialdelay)
    {

    }
    void run(uint32_t t_ms)
    {
        // tbd handle wraparound !!
        if(t_ms >= m_lastrun + m_periodic + m_initialdelay)
        {
            m_p();
            m_lastrun=t_ms;
            m_initialdelay=0;
        }
    }
};

to use the job class i just create the instances for the jobs and pass lambdas or regular function pointers
Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);
Job jupdate(updatemc,1);
Job jprint(printstate,500);

initialize the beginning of the chain of jobs
template<> Job *Registered< Job >::registry = 0;

and inside main, run an infinite loop which calls the jobs.
while (1)
    {
        for ( auto p = Job::registry; p; p=p->chain )
        p->run(millis());
    }

Lambdas
Nice to avoid a callback function
instead of
void handleserial(void)
{
    mqttrouteradapter.handleSerialMQTT();
}
Job jserial(handleserial,10);

i can write something like
Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);

the new meaning of auto
Allows to deduce the type automagically. This function iterates over "something" passed the second parameter. It compiles, if the passed type provides the operations/attributes used in the function.
And yes, this works only since c++17
void runRx(const char* data, auto msg_registry) {
    for (auto p = msg_registry; p; p = p->chain) {
        p->rx(data);
    }
}

using a recent compiler
If you want to use a recent compiler (The Arduino IDE uses gcc4.9) you can build your own gcc avr toolchain rather easily. Then you have gcc 7.2 with c++17 support !
An other very good reason to use gcc 7.2 is, that they have improved the error messages by a great deal.
My conclusion is, there is no excuse using c, except you havn't yet learned c++. And use a new compiler !

nor dynamic memory allocation - malloc/free and new/delete are both available in the standard IDE.

To write effective code with limited resources (RAM, program space, processing), you need to know enough about the processor to avoid features which it can't do.  In this case you're limited on all three counts, so you want to get away from anything complex and slow.
A good start is to avoid any features later than C++98, or at least C++03.  These features generally come at a cost.
Beyond that, particular issues are:-

Polymorphism.  All classes using virtual members have a virtual method table, meaning every function call from that class needs to look up against a table.  On a small processor, this does slow down your function calls.  By all means use this where it's required, but if you have performance issues then you want your polymorphic classes to live at a higher level where the function calls happen less often.  Don't do this for low-level functions which get called thousands of times in a loop.
Exceptions.  Already covered by other answers.
Inline.  This is a good thing.  Where you can use this, it can claw back some processing cycles: not just from the function call itself; but also from further optimisation in the calling functions.

And of course general issues for embedded firmware on low-end micros:-

Dynamic memory allocation (new and delete, or most STL containers).  This is always an anti-pattern in embedded development.  It requires a chunk of RAM to be set aside for heap, and you always need to consider the possibility of allocation failing.  If you really need some kind of dynamic storage, consider whether a FIFO buffer or something better bounded would be appropriate.
Longer integers.
Integer multiply and divide.
Anything floating-point.
Anything using a lot of stack, whether this is lots of local variables, lots of function parameters, or over-enthusiastic function partitioning.

Integer multiplication is OK on Arduinos, as the ATmegas have a hardware multiplier. But note that some Arduino-compatible boards (Trinket, Digispark, ...) are based on ATtinies, which do not have such multiplier.

Arduino libraries relying on C++11 are not that uncommon. Also, a lot of STL containers can be used without dynamic memory allocation. Nothing stops you from creating an std::vector on stack.

@EdgarBonet Isn't that only an 8-bit x 8-bit multiplier though?  Technically an 8-bit value is not an integer. ;)

Yes, it's a 8×8→16 bit multiplier. It is used by the compiler to implement all multiplications far more efficiently than a bitwise shift-and-add. Multiplying two ints requires only three 8×8→16 multiplications (two bytes of flash and two CPU cycles each) and a few additions. 2. Technically, both int8_t and an uint8_t are 8-bit integer types. But this is completely unrelated to my first comment.

@EdgarBonet Error on my part - it's an integer, just not an "int". :)

@DmitryGrigoryev Sure, if you need features from C++11 or later, you can use them - you just need to be aware of the implications on a low-spec processor.  Re STL containers, the std::vector container may live on the stack, but its data (which of course is the important bit) will be on the heap because it has to be resizable.  Unless the STL implementation is a bit non-standard, or I guess if you've done something funky with the allocator, but that's probably beyond the skills of the OP at the moment.  std::array could be entirely on the stack though (and yes, this is a C++11 addition).

std::array can be a stack-only allocation. std::vector is dynamically sized, so even if some flavor of std::vector can be stack-only on construction, causing a resize by adding elements will need dynamic memory.


text:
arduino --verify / --upload not working (command line)
I installed Arduino IDE version 2.1 on Ubuntu via apt-get. Then I typed the following command in terminal to see if the Arduino IDE compiles my sketch.
 arduino --verify xx.ino

However, this command launches the GUI IDE. Is the CLI not supported anymore, or is the cause in apt-get the package?

There's no such thing as Arduino IDE version 2.1, the most recent version is a mere 1.8.5.

It's quite possible that this "version 2.1" doesn't support command line processes. I've never heard of an Arduino IDE version 2.1. My understanding is the version you get from apt-get install arduino is something like 2:1.0.5+dfsg2 so maybe you interpreted that as 2.1. That version is based on Arduino IDE 1.0.5, though apparently it has some non-standard modifications. Command line operation was first added in Arduino IDE 1.5.2, though some additional functionalities were added in newer versions.
You should always install the official Arduino IDE downloaded from:
https://www.arduino.cc/en/Main/Software

Thank you very much  for the clear answer! I indeed interpreted 2:1.0.5+dfsg2 as 2.1.


text:
avrdude: stk500_recv(): programmer is not responding after all tries
After months of good use, both my boards Mega 2560 and Uno became unavailable for uploading sketch or burning bootloader.
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\[...]bin/avrdude -CC:[...]avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM5 -Uflash:w:C:\Users\GREGOR~1\AppData\Local\Temp\arduino_build_242793/BareMinimum.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:[...]\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

Facts :

v1.6.20 of the boards
v1.8.5 of the IDE
Windows 8.1 64bits
Programmer: "AVR ISP"
Drivers are fine (the boards are well recognized)
Serial monitor works
I'm trying to upload the "Bare minimum" exemple sketch
Nothing in pin 0 and 1, nothing at all is plugged actually
Get Board info:
Uno : VID 2A03
Mega2560 : VID 2A03
From instructions here, every instruction is "echoed back"

What i tried :

https://forum.arduino.cc/index.php?topic=385160.0
avrdude: stk500_recv(): programmer is not responding
https://zestedesavoir.com/forums/sujet/5676/probleme-televersement-arduino
All other programmers
A few old versions of boards
Resetting the boards a few times, during upload, before, after...

Nothing works. If you have any idea.....
Thank you all !

What i tried : ... i do not see rebooted computer on the list

haha @jsotola but I did :)

It eventually worked by using upload / ctrl+U (what I didn't try... smh) instead of  upload using programmer / ctrl+shift+U.
So i know now where it comes from, though I don't know what's wrong with AVR ISP.

"upload using programmer" requires one more step to work. You need to change one of your Arduinos into an ISP (there is a sketch for that) then you put some wires between the ArduinoISP and clean (no bootloader) ATmega/ATtiny, and you can write program (or bootloader) directly to the chip. Your ArduinoIDE was trying to find the ArduinoISP, but it couldn't because there wasn't any. and told you "programmer is not responding" Read more here: https://www.arduino.cc/en/Tutorial/ArduinoISP

Thank you, this resolved the issue for me as well.


text:
Arduino Burn the code programmatically
Is it possible to burn arduino code programmatically?
I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.
Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.

You mean like https://create.arduino.cc/editor ?

it should be possible. ... store the new sketch on an external eeprom ... modify the bootloader so that it checks for the existence of the new program and loads it

First, the Arduino Uno has 32 KB of flash, but only 1 KB of RAM. So, to be able to store the new program in a string means your new program can only be, at most, 1kb.
Secondly, only the bootloader can write to flash. So you could write a new bootloader that downloads the new program (in parts) and writes it to the flash. You would however need quite a big bootloader, leaving less space for actual code. Also the main program still needs to access the server to see if it needs to "reboot" so the bootloader can run the update process.
An example of an OTA bootloader can be found at https://www.rotwang.co.uk/projects/bootloader.html which might be a good starting point. Similar idea https://ncrmnt.org/2014/02/27/rf24boot-a-universal-over-the-air-bootloader-for-all-those-ucs/
Another option is to write the new firmware to an external EEPROM. Then your modified bootloader only has to read the new firmware from EEPROM, making it a lot simpler and smaller. There is some useful info in the question OTA updates for Arduino using nRF24L01+
MySensors.org already made such a bootloader: https://www.mysensors.org/about/bootloader
I know there exists another bootloader that does just that, but I can't seem to find it.

Does arduino uno have internal (built-in) EEPROM? If yes, then can we use this internal EEPROM instead of using the external?

Internal EEPROM is only 1kb if I remember correctly. So too small to be of use.

Which EEPROM would you suggest me?

There are only two options. SPI or I2C. The choice depends on which bootloader you use/write. And maybe which other devices you have attached to the Arduino.

The guys at http://phoenard.com/ wrote a bootloader that loads compiled code from the SD card.


text:
Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems
So i've chosen to purchase a Wemos D1 R2 board in order that my old Arduino Uno R3 projects can get some new IoT features. However, even if my code is working in Uno perfectly, i want to test it using D1 before adding features. My problem is that, even if i have found tables showing differences between the 2 boards' pinouts, i cannot understand the correspondence between the pinouts.
So i am giving you the table below. Let's say i want to define echo and trigger pins for a sensor in my code. For example:
#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would be pins D3 and D4 at my Uno. But i cannot understand which those pins would be in Wemos D1 R2. Also, my two boards can be seen below for comparison

The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.
Sometimes you will see the digital pins on Arduino boards referenced with the Dn notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the Dn pin notation on their silkscreen. This is just a way of further differentiating the pins from the An pins. You will only refer to that pin by the number 4 in your code.
The WeMos boards are different. You actually need to use D3 and D4 in your code to control the pins marked D3 and D4 on the silkscreen:
#define TRIGGER_PIN D4
#define ECHO_PIN D3

We can take a peek at the source code of the ESP8266 core for Arduino to see why:
https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1_mini/pins_arduino.h#L40-L50
static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t RX   = 3;
static const uint8_t TX = 1;

Now you can see that if you use your original code:
#define TRIGGER_PIN 4
#define ECHO_PIN 3

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!

Perfect answer to sort that out. To the point and clear! Thanks.

If i choose to use numbers with Ds, f.e. TRIGGER_PIN D4, will i connect jumper wire of trigger to D2(Arduino pin) or to D4 (physical D4 on Wemos)?

Use the Dn names, as marked on the WeMos board, in your code and the pin with that marking will be used. i.e. if you write D4 in your code then connect the wire to the pin marked D4 on the board.


text:
Does the tone() generates unwanted signal?
I was trying to use the tone function for another project but I found that it also generates an undesired frequency (not the harmonics above of square wave it generates) but a lower frq square wave. Is this normal or somethings wrong with my implementation?
the code is pretty simple:
void setup()
{
    pinMode(7,OUTPUT); //set the pin as output
    tone(7,10000); //start a 10KHz tone
    while(true); //stay here
}

void loop()
{ }

hardware was an Uno also tried different pins above but same results. first I tried a 470R and an 8R speaker. then guess maybe the inductance, or something else causing it so I used a piezo buzzer as seen below:
Pin(x)--->10KR--->piezo--->GND

however it was the same. I measured the lower frequency as 19.55Hz for a tone(10000) and 39.05Hz for tone(40000); both are pretty annoying.
what causes this and whats the workaround?

What happens if you remove "while(true);" from the sketch?

@VE7JRO I just did that but nothing changed. guess the empty loop()  replaces my while. however I moved the the tone() AND the while(true) to the loop() and I still get the same result. but with tone() only in loop() the noise is more stressed I think because it repeatedly calls the function and tone sets the frq although it's the same as previous call.

or just a short or long jump to tone() needs more clocks. but that's not a good reason for noise when I call it once.

I could reproduce the problem with the posted code. This will be caused by the fact that the tone library uses interrupts and has to manually toggle pins, which will always have a bit of jitter. You are better off setting up a hardware timer to generate the tones, this does not require interrupts.
For example:
#include <TonePlayer.h>

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (10000);  // 10 kHz
  }

void loop() { }

This uses a fairly small library I wrote, which you can download from http://www.gammon.com.au/Arduino/TonePlayer.zip

Library code
If you don't want to trust some zip file from a random web site, here is TonePlayer.h:
/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
*/

#include <Arduino.h>

class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

/*

 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

 */

And here is TonePlayer.cpp:
/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
 */

#include <TonePlayer.h>

void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

/*
 PERMISSION TO DISTRIBUTE

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 and associated documentation files (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 LIMITATION OF LIABILITY

 The software is provided "as is", without warranty of any kind, express or implied,
 including but not limited to the warranties of merchantability, fitness for a particular
 purpose and noninfringement. In no event shall the authors or copyright holders be liable
 for any claim, damages or other liability, whether in an action of contract,
 tort or otherwise, arising from, out of or in connection with the software
 or the use or other dealings in the software.

 Example of use:

 #include <TonePlayer.h>

 ...

 TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

 or, on the Mega 2560:

 TonePlayer tone3 (TCCR3A, TCCR3B, OCR3AH, OCR3AL, TCNT3H, TCNT3L);  // pin D5
 TonePlayer tone4 (TCCR4A, TCCR4B, OCR4AH, OCR4AL, TCNT4H, TCNT4L);  // pin D6
 TonePlayer tone5 (TCCR5A, TCCR5B, OCR5AH, OCR5AL, TCNT5H, TCNT5L);  // pin D46

 ...

 pinMode (9, OUTPUT);  // D9 on Uno, D11 on Mega 2560
 tone1.tone (440);     // play 440 Hz
 delay (500);          // wait half a second
 tone1.noTone ();      // stop playing

 or, on the Mega 2560:

 pinMode (46, OUTPUT);
 tone5.tone (440);

*/

Just put those two files inside a folder "TonePlayer" inside the libraries folder inside your sketches folder, and it should all work.
The library is written for the 16-bit timers, and supports Timer 1 on the Atmega328, and Timers 1, 3, 4, 5 on the Atmega2560. Comments inside the library show how to set up the other timers.

You should probably warn that this library only works with 16-bit timers. 2. No need to split 16-bit writes into bytes, you can write *timerOCR_ = highByte(ocr);. This would save 4 bytes in the class. Since March 2005, gcc knows it must write the high byte first.

I got that code from my page about timers which had an extra sentence mentioning the 16-bit timers, which I have edited into my reply. You are right about the 16-bit writes, but to change that now would alter the call sequence for the constructors which could break existing code, so I'll leave it and take the 4-byte penalty. :)

@edgarbonet thanks for the clarification and detailed tweaks.

@nick thanks for providing the code, it works great. To correct myself I found that there are jitters or spikes with the tone() which increases with the frq. And a series of continius noise of with much less and constant  amplitude which i couldn't track down the source. I may add a photo later.

@user174174, when the standard Arduino tone() function changes to a new frequency, it does that in a nasty way. When creating a sound (for example a siren) it can be heard. That was also improved in the toneAC library.

I had a situation where calling tone() "broke" my IR Receiver. (Specifically, after calling tone(), the IR Receiver viewed all incoming signals as 0s.) This code fixed it! Thanks!

Did you measure it with good equipment? How much dB is the lower frequency? Can you show a spectrum plot?
It could be the software pin toggle. The tone selects a hardware timer, which is used to generate an interrupt. The output pin is toggled in that interrupt. It is in the file Tone.cpp. That interrupt could be delayed by a timer0 interrupt (for millis).
The timer0 runs at 16MHz/(64*256). With those numbers I can not get to the interference frequency that you mentioned.
You could try to use the output of a hardware timer. For example the toneAC library generates a tone at pin 9 and 10. That is as steady as the 16 MHz crystal (very steady).
It could be the equipment that you use to test.
It could be the speaker. Some speakers generate other tones. I had a ultrasound speaker which I could hear squeeking at a much lower frequency. After a search on the internet, I found that such a speaker is known to create lower frequency whistling noises.
It could be the 5V voltage is changed somehow by the circuit.

You wrote: “With those numbers I can not get to the interference frequency that you mentioned.” At 10 kHz, (41×f(timer 0) − 2×f(timer 2))/2 = 19.53125 Hz. At 40 kHz, (82×f(timer 0) − f(timer 2))/2 = 39.0625 Hz. The factor 2 in the denominator comes from the fact that interrupt collisions lengthen alternatively the HIGH level (when the fall is delayed) and the LOW level (when the rise is delayed).

@EdgarBonet, thank you. That is amazing that you could analyze that.

@jot thanks for your help, sadly I don't have any fancy equipment but I managed to record the signal with my laptop.