text:
Arduino Uno unable to detect usb port on Mac OS Sierra 10.12.5
Few weeks ago my Arduino Uno (IDE version 1.8.2) detected the USB port and I was able to do some small IOT projects. I updated my OS to Sierra 10.12.5 and now suddenly the usb serial option has disappeared.

I followed this link : https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac  where it tells us to download and install the FTDI drivers separately. I tried that but it did not help.
Then I came across this post: https://forum.arduino.cc/index.php?topic=427825.0 where the user is having this same problem with MacOS Sierra. He suggested we remove the FTDI drivers and rely on Apple's drivers. So I removed the FTDI drivers from my Mac so it will use Apple's drivers.
Now even after doing all this when I connect my Arduino Uno to my Mac via the USB it does not get detected.
I removed the kext and pkg files for the FTDI drivers and deleted them completely, still when I open the System Report I still see the FTDI USB Serial Driver entry.

When I go to System Report > Hardware > USB I see this:

What is happening? Did the FTDI drivers got removed? If they did then why wont the serial usb port get detected on Arduino? If they are not removed completely then what did I miss?

If you have a genuine Arduino you don't want the FTDI drivers. There hasn't been an FTDI on an Arduino for many years. If you have a cheap Chinese clone then you probably want the CG340G drivers (and good luck with those). Genuine Arduino boards use a CDC/ACM interface, and all modern operating systems have those drivers built in.

I am not sure if my Arduino is genuine or cheap chinese knockoff. I got it off from Amazon as a part of IOT starter kit. It worked properly in the beginning and as I mentioned I did some projects on it.

Unless you went through the rigmarole of installing the CG340G drivers (and you'd remember doing that, trust me) then it's probably like a genuine Arduino (with an ATMega16U2 chip as the USB interface) - however, is it actually genuine? Only a picture of the board could tell us that (there's telltale signs you can see if you know what you're looking for). If it's not genuine then it could be that the USB interface chip is dead (it may be a cloned chip or a factory reject).

Found this on youtube: https://www.youtube.com/watch?v=wyocdvAKo64&t=0s   what do you think?

That's for cheap chinese clones only - CH340G. Post a picture of your board please.

Here it is: https://drive.google.com/file/d/0B43t-lgy1BmXUHZ2cWJFdHZpSWc/view?usp=sharing

That's what we in the trade call counterfeit: it's pretending to be a genuine Arduino but isn't. Clues: there's no TM on the Arduino logo. They misspelled "RESET EN" calling it "RESET CN" instead. The silk screen isn't of a high enough quality. There's no "WWW.ARDUINO.CC - MADE IN ITALY" on the front. The font isn't quite right (too angular). So there is a chance the ATMega16U2 chip has died. I don't use a mac though so can't offer diagnostic suggestions.

So does this mean that the complete Arduino is useless? I have to buy a new one?

Not necessarily. As I say I don't use mac, so I can't help you diagnose it. There may be some other cause. If it is the ATMega16U2 though you can bypass it with a cheap USB to UART TTL adaptor connected to pins 0/1 and DTR to RESET through a 100nF capacitor. Just as if it were an ATMega328P on a breadboard.

Ok. Nevermind it worked. I followed the YouTube video I shared above and now the board is detected. Thanks for your help, I appreciate it :)

Strange that, since it doesn't use that driver. However it may kick the USB subsystem into action I guess as a side-effect.

I followed this you Tube Vedieo : https://www.youtube.com/watch?v=wyocdvAKo64&t=0s and I installed the CH340 driver but I do not found the more than ports in port option  but I still did't get my serial port

For me Peba's answer here helped me https://www.silabs.com/community/interface/forum.topic.topic.15.15.html/cp120x_vcp_driverno-G1Bu

I installed the CH340 Driver and the board now shows the USB serial as port option: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

This cannot be an answer to the question asked, as the Uno does not have a CH340.   Either the question or the answer is incorrect.

@ChrisStratton I am fairly new to IOT and electronics in general. I did what I could to find a solution to my problem and it worked. If you are so enlightened in this matter then please feel free to give a "correct" solution to my problem or "correct" the questions.

I had the same problem w/ an Arduino Uno after upgrading to Sierra--no issue with USB port detection before upgrade and issue afterwards. I downloaded and installed the driver from the said github repo and then after reboot, it worked! Thanks for offering this solution.

Hi, You have to install CoolTerm for mac. http://freeware.the-meiers.org/


text:
How can I make my Arduino Uno press Space on my laptop keyboard?
So I wanna build something which, when it receives a remote signal, presses the spacebar on my laptop keyboard. I tried using the Keyboard.press() but it is available only for Leonardo. Is there any way I can use it in my Uno, without having to mess with the firmware?
If not, what else can I use to accomplish my goal?

https://github.com/NicoHood/Hoodloader

@Majenko Are you sure this has no dangers at all?

You can do that without burn a new bootloader via an interface application. The disadvantage is that you have to code a new application. You can do that with Java, C++, C#, ... You can send a message through serial and received it with your app. Tha's not the best way.

you could send a signal character over serial ... run a Processing sketch on the laptop that generates a keypress everytime the signal character is received

Control a servo that physically presses the spacebar...

On Windows you can use a serial to keyboard redirector like this one
It can start with windows, Im using it for a long time without any issues.

if you have some knowledge in Java or Python you can interface your Arduino board to PC, through Arduino's SerialPort.
When Arduino sends a byte, for example, 0xAB, your Java or Python script sends a fake key-press event.
I hope this can help. Good luck!

are you sure you can send a keypress event to any application from other application?

source: Stack Exchange

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

sort: votes


text:
Circuit not working with 9 volt battery
I have made a simple circuit having an IR receiver and a Servo motor. Here is the diagram:

Red wire: power
Black wire: ground
Orange wire: digital signal
And here's the code:
#include <Servo.h>
#include <IRremote.h>
int receiver = 13;
IRrecv irrecv(receiver);
decode_results results;
Servo myServo;
int pos = 0;
void setup() {
  // put your setup code here, to run once:
  myServo.attach(9);
  Serial.begin(9600);
  irrecv.enableIRIn();
  myServo.write(0);
  delay(200);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results)){

    if (results.value== 0xC0000C){
      for (pos = 0; pos <= 90; pos += 10) {
        // in steps of 1 degree
        myServo.write(pos);
        delay(15);
      }
      for (pos = 90; pos >= 0; pos -= 10) {
        myServo.write(pos);
        delay(15);
      }
    }
  }
  irrecv.resume();
  delay(100);
}

It rotates the motor 90 degree and back when a button on a remote is clicked.
Here comes the problem: This is working perfectly when connected to my PC, but it doesn't when I connect it with my 9-volt (cuboid shaped) battery. The lights on the Arduino board still light up, but the circuit does nothing when I press the remote button.
I have also observed that the servo vibrates a little bit, but doesn't move.
Is this a problem in my circuit, or is it just that my battery power is low?

As many already have experienced, a 9V block can simply not deliver enough current for powering any significant load. You will have more luck with, for example, a 4- or 6- cell AA battery pack.

A 9V battery has both low peak current and low total power (low mAh rating). It is not a good choice for any circuit that draws more than ≈100 mA. (I pulled that number out of thin air, but it's probably a decent guess)
Build a battery pack from 6 AA alkaline cells instead. That will provide enough peak current. Or for much longer run-time, use 6 D sized cells.

you don't like the answer on the duplicate? or why you didn't vote for it?

I missed the duplicate vote. You're right, that would have been better than another answer.

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


text:
if I add a .cpp file, Serial becomes unusable
I am using the mega 2560. When I just use .ino and .h files, if I use Serial, it works fine, without even using:
#include <SoftwareSerial.h>

However, when I add a .cpp file I start getting 2 errors, one is solved by adding the aforementioned include, the second one, after adding it, is :
'Serial' was not declared in this scope

I know I can declare it manually and use the RX/TX pins, but I would like to be able to use the default Serial so that I don't have to occupy more pins. Especially since it works file w/o the .cpp file. Can anyone explain to me why this happens? Is it because I specify a C++ file so the compiler changes?

A CPP file isn't an Arduino file. It doesn't know about anything Arduino-esque unless you tell it about it.
The simplest way is to just add, at the top of the file:
#include <Arduino.h>

Ah, damn once you say it it becomes so obvious, thank you.


text:
Burning Digispark bootloader without an Arduino
I've been wondering if there is any method to burn a Micronucleus bootloader into a blank ATtiny85 Digispark using just Windows or a Linux distro, and not needing another Arduino board such as UNO that acts as ISP.

it will be hard even with programmer or other Arduino. only other option is a wiring on computers parallel connector. but most new computers don't have it.

I've found some guides about how to burn the bootloader using an UNO and the process doesn't seem to be very hard, my trouble here is that i don't have an UNO at the moment so i'm looking for alternative ways to do it. Could you explain which would be the way to go using a parallel connector?

the Digispark doesn't have reset pin. that will be a complication

https://www.instructables.com/id/Simplest-AVR-Parallel-port-programmer/

Here are some more simple programmers (including serial port, which may be easier to find).

it crossed my mind that a USB keyboard has three outputs ... a quick search found this ... https://hackaday.com/2012/11/26/usb-keyboard-becomes-an-avr-programmer/

@Vile Did you managed to burn the bootloader using the Arduino? I ran into the same issue.


text:
NRF24L01 integrated antenna exposed out of the box
I'm going to try my hand at making a few sensors that are to report status to a central server. To make them wireless, I'm going with nRF24L01 modules. I intend to enclose the sensors (Arduino Mini Pro + nRF24L01 + battery pack + a couple of other small components) in a simple PVC box.
A couple of the sensors would be about 10 meters away from the server, which, as far as specifications go, is about the maximum range of the radio modules. Especially the ones with the integrated antenna that I'm using. I thought that maybe I could squeeze some radio performance by exposing the antenna, so that the radio signal isn't attenuated by the PVC case. I could carve a small opening in the lid and have the nRF24L01 stick out, so that the electronics would be protected inside but the antenna strip would enjoy open air.
I would like some thoughts on this idea. I'm especially trying to understand if I just had the most novel idea ever, since I can't seem to find anything about it on the net. Has anyone ever tried this in real life? Does it make sense? Is it worth the trouble?  I'm not looking for a theoretical analysis (I get that fine), only for actual experience. Thank you.

How much suffers the range of your nRF24L01 while in the box compared to outside of the box? Maybe you can try another box that does not shield off your wireless signal?

You would do better adding a dipole to the board and ensuring they are orientated correctly. http://www.instructables.com/id/Enhanced-NRF24L01/

Only metal or other conductive materials (like water) impact the magnetic field. Also consider both PCB and Dipole antennas are not omni-directional: correct orientation might also be beneficial, even if it is probably a brittle solution.

@Kwasmich I still haven't tested the prototype. I'm still in the design phase, but I wanted to make sure I considered a possible case improvement (if it actually were an improvement, which does not seem to be the case).

Where did you get that 10meter figure from? Sound a bit low to me. Maybe indoors with multiple walls, but otherwise the range is much further. You could test different channels to see which works best in your situation. Also lowering the speed will increase the range.

@Gerben Yes, I'm referring to indoors, a few rooms away, with WiFi, and good old European brick walls from sixty years ago. I'll surely try different channels as you suggest; I'm not sure how to act on the transmission speed, though.

If I remember correctly the NRF24 has 3 speeds. 2MBit, 1MBit, and 250KBit per second.

In general no, this would make little or no difference. PVC has very little effect on RF signals.
After all, the antenna on your typical WiFi router is inside a PVC tube and it doesn't suffer from it.
Instead you would do better constructing a dipole antenna from a couple of pieces of carefully measured wire.
For instance this instructable tells you how.

Thank you! I will test the performance and consider building the dipole.

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


text:
How to manage dependencies?
I want to include a dependency like Logging. On its page it says:

Download zip file
Put the Logging folder in "libraries\".

I don't want to believe (with a Maven mindset) that this is the way we manage dependencies in Arduino projects. That means, everybody who checks out my package would have to repeat those steps locally (or do you include "libraries\" in the version control) What's the best practice for dependency management?

Nope, that is what everyone does.

Libraries is what libraries are. This is not Maven. This is Arduino. It's simplistic so that people without knowledge of microcontrollers can make an LED blink. If you want real IDE facilities then use a real IDE.

Well, I'm using the first hit in Google for Arduino IDE, but this doesn't help me with dependencies. Making a LED blink doesn't necessary require a library and I agree that things should be simple. That's the very reason why I ask for  dependency management.

Look for C++ IDE or G++ IDE instead. And for crosscompiling

Arduino is meant to be easy way for non-technical people and so it hides as much as it can from plain view to be simple.
For simple project it works at the cost of overhead of copying libraries here and there and using Arduino's "IDE". Calling programs "sketches" and manipulate it to hide, that it is in C++. And so on and so on.
If you want to make more complicated projects, version control, good environment and such, you need to leave "simply Arduino way" and start using more powerful and complicated tools.
I personally use
https://github.com/sudar/Arduino-Makefile
https://github.com/ladislas/Bare-Arduino-Project
and have it in GIT repositories.
This way I can share libraries between projects in group, also links to libraries outside the tree works, as well as gits submodules, both allowing you to have updated libraries from 3rd party aviable to all projects, also those old ones.
I still use a lot of Arduino (like setup/loop, digitalRead and such), but also I use "normal" g++ constructs on the way. Later I will diverge even more to plain C/g++/.. code probably, using some RTOS or so, but now my needs are not so far yet. (google "arduino rtos" I am currently reading https://github.com/greiman/NilRTOS-Arduino )
Arduino is not meant to be "best practice" anyway. It is meant to be "fast and easy way to do something, when you know nothing". And it works, as anybody and his dog can start with Arduino and if interested, he can go more far on his own, or he can stick with easy and have fun anyway.

If you want the project to be self contained you can put the library dependencies in the sketch folder. So the folder structure of the Foo sketch with the Logging library dependency would look something like this:
Foo
|_Foo.ino
|_src
  |_Logging
    |_Logging.h
    |_Logging.cpp

And in Foo.ino you will include the library like this:

#include "src/Logging/Logging.h"

Unfortunately some libraries use the incorrect include syntax which still works when the library is installed in one of the libraries folders but not when located in the sketch folder. The Logging library does use the correct include syntax but sometimes to put libraries in the sketch folder you will need to fix this. For example, let's say you have a library named Bar and in Bar.cpp you see this:
#include <Bar.h>

That won't work because if installed in the sketch folder Bar.h will not be located in one of the standard include paths so you need to edit Bar.cpp and change the include syntax to:
#include "Bar.h"

Which will cause the local folder to be searched for the included file.
The downside to this system is that you may end up with multiple copies of a library so it's more work to update or modify each copy. Of course that can also be a benefit because each project can have its own known-working version of the library that will not be affected by any updates you may make to the same library used in other projects.
I generally just add instructions for how to install library dependencies in the usual manner to the documentation for a project. That should be within the capabilities of the average Arduino user. If a specific version of a library is necessary then you document that. However, there are cases where I have wanted to hand over a self-contained project to someone who is not familiar with the use of the Arduino IDE and that is when I have used the system described above for all necessary 3rd party libraries.

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


text:
How can I move an arduino library into my project repo and use it from there?
I've got this project that that is using the LiquidCrystal.h library. My import looks like this...
#import <LiquidCrystal.h>

I've tried making a 'libraries' folder in my repo, and copying the LiquidCrystal directory from arduino's global libraries folder to my_project/libraries and changing my import to...
#import "libraries/LiquidCrystal/LiquidCrystal.h"

and it explodes on me. I know the path is right, because it gives me a different error if I change the import path to be wrong... but even when it's right, I get this traceback...
Arduino: 1.8.1 (Mac OS X), TD: 1.36, Board: "Arduino/Genuino Uno"

/var/folders/sz/cdsmvqws6rq9839mhd802prm0000gp/T//cc4gIISN.ltrans0.ltrans.o: In function `__static_initialization_and_destruction_0':
/Users/chris/art/greenhouse/greenhouse/greenhouse.ino:36: undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
etc....

What's the deal? Aren't I supposed to be able to import libraries with an absolute path to the library? This is literally the same file.
What is the difference between #import <foo.h> and #import "my_libraries/myfoo.h" ?

What's the deal? Aren't I supposed to be able to import libraries with
  an absolute path to the library? This is literally the same file.

Yes you can use both absolute and relative paths, but "libraries/LiquidCrystal/LiquidCrystal.h" is a relative path because it doesn't start from C:\\ or / basically. Also make sure you get the LiquidCrystal.cpp file which actually contains all the functions LiquidCrystal.h specifies.

What is the difference between #import  and #import
  "my_libraries/myfoo.h" ?

#include "my_libraries/myfoo.h" specifies that myfoo.h is in a folder my_libraries first searched for in current_folder/my_libraries/myfoo.h then quote directories and rest of the search paths later, #include <foo.h> specifies that foo.h is a system header, it's only searched for in search paths.
Solution here would be saying inside your sketch that it is in a subfolder, that the folder is one folder below and then two folders deeper for ex. #include "../libraries/LiquidCrystal/LiquidCrystal.h" this here assumes your sketch is in root_folder/Sketch/Sketch.ino and library in root_folder/libraries/LiquidCrystal/LiquidCrystal.h.

Try it with this folder structure:
my_project
|_src
  |_LiquidCrystal

and change the import to:
#import "src/LiquidCrystal/LiquidCrystal.h"

Since Arduino IDE 1.6.10, recursive compilation of the sketch folder has been limited to the src subfolder (see Arduino/arduino-builder#148).
By the way, it's much more common to use #include instead of #import, which is deprecated and will cause a compiler warning. Any properly written library will not require the use of #import.


text:
Digispark green led being the only one to turn on
I was doing some tests with an ATtiny85 Digispark module using Arduino IDE on my Windows PC. I was testing some stuff with the DigiKeyboard library from Digistump.
Everything was going fine until suddenly the Digispark stopped working and wasn't able to upload code through the module anymore. Now when I plug it in my PC, the only thing that the module does is turn on the green led; besides, Windows doesn’t recognize the module when I plug it in anymore and doesn’t even appear in Device Manager as an unknown device or something.
I reinstalled the drivers but nothing changed. I also tried to reinstall Micronucleous into the ATtiny85 using Zadig, but wasn’t able to do it because Windows doesn’t recognize the module when I plug it in, so Zadig won't see it either.
Since I’m not very familiar with electronics, I’m not sure if there is any way to fix this or if it’s due to some physical damage, so any help or direction with how to deal with this would be really appreciated.

are you certain that windows is not recognizing anything at all?

Yes. I double checked Device Manager and I couldn't see it there; besides, Windows doesn't play this sound that you hear when a USB device gets connected.

afaik digispark doesn't have USB chip and the Atiny doesn't have native USB. you must program it over ISP. and again afaik, software USB bootloader can be used. a new Digispark should have it.

@Juraj the digispark uses VUSB to implement USB in software. Programming over ISP isn't possible, as far as I know, since Digispark disables the reset pin (to use it as a GPIO).

@Juraj I'm not sure of what you mean, from what I know, the Digispark was made to be able to program the attiny85 via USB. I was able to program this exact Digispark in the past, but in some moment something went wrong and wasn't able to do it anymore

so lost USB indicates lost bootloader. it is time to find out how to burn the bootloader.

@Juraj looks like that is the way to go, thanks!

@vile Do you have any updates? I literally just ran into this issue today....I got various scripts loaded, worked fine, now today suddenly it stopped getting recognized  I tried everything so far, but it's not even showing up on the device manager.


text:
Object can't get the right value of its property
I'm doing a program for a robot and I got stuck at a weird problem:
I have classes defined for my robot's internals, for example for a StepMotor. I also defined a class for a Controller, which is going to control the speed of each StepMotor.
Here's a fragment of my code:
    #include <SPI.h>
    #include <Tone.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    /SILNIKI KROKOWE:
    class StepMotor: public Device
    {
        public:
            int motorPin;
            int dirPin;
            int sleepPin;
            int ForwardState;
            volatile double Speed;
            volatile int ControlValue;  //the value sent to the motor
            int MaxControlValue = 4000; //maximum ControlValue
            String Name;

            void Init ( void )
            {
                //init
            }

            void SetSpeed ( int speed )
            {
              toneObject.play(speed);
            }

            void SetMode(bool IsOn)
            {
              if (IsOn)
                digitalWrite(sleepPin, HIGH);
              else
                digitalWrite(sleepPin, LOW);
            }

            void SetDirection ( Dir direction )
            {
    //code for setting direction
            }

        private:
          Tone toneObject;
    };

    StepMotor motor_right;
    StepMotor motor_left;

    class Controller
    {
      public:
        ControllerType controllerType;
        double Kp;
        double Ki;
        double Kd;
        double Tp; //czas próbkowania
        volatile double e;
        volatile double e_old;
        volatile double P_result;
        volatile double I_result;
        volatile double D_result;
        StepMotor Motor;

        int Calculate ()
        {
          int Result;
     //Serial.print(Motor.Speed); HERE's THE PROBLEM
    /********************************
    /********************************
    /*******************************
          e = MoveOrder::speed - Motor.Speed;  //Motor.Speed is always 0.00, although it's not true

             //the rest is not important
        }

        void Reset()
        {
          //reset procedure
        }

    };

    Controller controller_right;
    Controller controller_left;

    setup()
    {
       controller_right.Motor = motor_right;
       controller_left.Motor = motor_left;
    }

    ISR(TIMER5_COMPA_vect)
    {
        motor_right.ControlValue = controller_right.Calculate();
        motor_left.ControlValue = controller_left.Calculate();
        motor_right.SetSpeed(motor_right.ControlValue);
        motor_left.SetSpeed(motor_left.ControlValue);

    }

I have cut the less important parts. The rest works properly, because my robot can drive when I use SetSpeed(somevalue); The only problem is that place where I need to read current speed of my motor.
In the Controller class, there's Calculate() method. In that method I want to calculate e = MoveOrder::speed - Motor.Speed; Unfortunately it can't be calculated properly, because Motor.Speed ALWAYS is 0.00 (when I display it with Serial.print(Motor.Speed) I see 0.00 all the time). It's very strange, because when I display speed of each motor (Serial.print(right_motor.Speed) or Serial.print(left_motor.Speed)) the value is correct (when the wheels are spinning, value is not 0.00).
The speed calculations are in a different function, which I didn't present here, because it would be too long - I'm sure it works, because, as I said, I can get speed values properly.
As you can see in setup(), I set each contorller's Motor porperty to the correct object.
I also used volatile keyword for the properties that are used in the interrupt.
What is wrong with my code?
If the code I provided isn't enough, here's the full version:
https://1drv.ms/t/s!Atl-jM_xUkz1hc1f-qYYotj-pJIgUw
I'm not sure if anyone would want to dive into it, because it's not so short.

My guess: controller_right.Motor = motor_right; makes a copy of motor_right. So you don't have the same class instance.
Basically Controller controller_right; calls default constructor which includes also default constructor for the StepMotor. And later all variables are copied into it by using default assigment operator, but still, it's not the same instance.

looks like you're right. So, I think I should: change StepMotor Motor in Controller class to StepMotor* Motor, to have a pointer. Then, in setup()   should do controller_right.Motor = &motor_right; and controller_left.Motor = &motor_left; Am I right?

@Loreno Or you can add StepMotor & motor_right = controller_right.Motor; after controller_* variable declaration. I guess, you can even skip these motor_right/motor_left variables as it's already in Controller

I need to be able to access motor_right and motor_left in other places (for exmple when I measure the speed of a motor and assign it to its Speed property). Your solution uses reference, right? i don't fully understand these, so I'm not sure what's the difference here. Today I can't check if the robot works correctly after applying those fixes, tomorrow I'll be able to do it and then I'll mark your answer as a proper one.

@Loreno It's basically an alias for referenced variable.


text:
A lot of "undefined reference" errors
I'm trying to create a program for my robot, but something is not right.
Here's the code:
#include <SPI.h>
#include <Tone.h>
#include <Wire.h>   // standardowa biblioteka Arduino
#include <LiquidCrystal_I2C.h> // dolaczenie pobranej biblioteki I2C dla LCD

//Enums:
enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

enum State
{
    movingForward = 1,
    movingBack = 2,
    turningLeft = 3,
    turningRight = 4,
    doingNothing = 5,
    readyToMove = 6 //Potrzebne?
};

enum SpeedState
{
  slowingDown = 1,
  maxSpeed = 2,
  accelerating = 3,
  notMoving = 4
};

//Classes:
LiquidCrystal_I2C lcd1(0x27, 20, 4);

//Base class for devices
class Device
{
    public:
        virtual void Init() = 0;
};

//STEPPER::
class StepMotor: public Device
{
    public:
        int motorPin;
        int dirPin;
        int sleepPin;

        void Init ( void )
        {
            pinMode(motorPin, OUTPUT);
            pinMode(dirPin, OUTPUT);
            pinMode(sleepPin, OUTPUT);

            toneObject.begin(motorPin);
        }

        void SetSpeed ( int speed )
        {
          toneObject.play(speed);
        }

    private:
      Tone toneObject;
};

//VARIABLES:
int a = 1; //przyspieszenie (przyrost prędkości i jej ubytek przy hamowaniu
int s_accelerating = 1; //droga przyspieszania [mm]
int s_braking = 1;  //droga hamowania [mm]

class Robot
{
    public:
        static float x;
        static float y;
        static float t;
        static State state;
        static SpeedState speedState;
        static int currentSpeed;
};

class MoveOrder
{
  public:
    static Dir direction;
    static int distance;
    static int speed;
    static int distanceRemaining;
    static int distanceMade;
};

//FUNCTIONS:
void SetInterrupt ( void )
{
    noInterrupts();           // disable all interrupts
    TCCR5A = 0;
    TCCR5B = 0;
    TCNT5  = 0;
    OCR5A = 310;            // compare match register 16MHz/256/2Hz   400 okolo 6.4ms  380-6.1ms 300-4.9ms
    TCCR5B |= (1 << WGM12);   // CTC mode
    TCCR5B |= (1 << CS12);    // 256 prescaler
    TIMSK5 |= (1 << OCIE1A);  // enable timer compare interrupt
    interrupts();             // enable all interrupts
}

void SetSpeed ( int speedValue )
{
   //currently empty
}

void setup()
{
    SetInterrupt();
}

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

}

ISR(TIMER5_COMPA_vect)
{
    if (Robot::state != doingNothing)
    {
        if (Robot::state == movingForward || Robot::state == movingBack )
        {
          if (MoveOrder::distanceMade < s_accelerating)
            {

                Robot::currentSpeed += a;

                SetSpeed(4);

            }
        }
    }
}

Compilation returns this:
Arduino:1.6.10 (Windows 10), Płytka:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_21':

ccU9OfJk.ltrans0.o:(.text+0x812): undefined reference to `Robot::state'

ccU9OfJk.ltrans0.o:(.text+0x816): undefined reference to `Robot::state'

C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_47':

ccU9OfJk.ltrans0.o:(.text+0x820): undefined reference to `MoveOrder::distanceMade'

ccU9OfJk.ltrans0.o:(.text+0x824): undefined reference to `MoveOrder::distanceMade'

ccU9OfJk.ltrans0.o:(.text+0x82e): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x832): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x838): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x83c): undefined reference to `Robot::currentSpeed'

collect2.exe: error: ld returned 1 exit status

exit status 1

I noticed that when I comment these lines:
        Robot::currentSpeed += a;

        SetSpeed(4);

errors are gone. Why?

Check the C++ syntax definition for static member data. They have to be defined; e.g. State Robot::state = initState;

"errors are gone" Because now the compiler isn't generating any code for anything, so there are no references to not find.

Just as a tip, when you see an error in a file ending in .o like this: ccU9OfJk.ltrans0.o - that is a linker error, not a compiler error. In other words, the syntax is OK, but you are missing something which the linker is trying to find.

Because you have only declared the class static variables; you never defined them.  For the Robot class, you must have:
class Robot
{
    public:
         ...
};

float      Robot::x;
float      Robot::y;
float      Robot::t;
State      Robot::state = doingNothing;
SpeedState Robot::speedState = notMoving;
int        Robot::currentSpeed;

void setup()
{

Ditto for other classes.  (Dangit, Mikael!  :) )

It's weird. In C# I wouldn't have to do it I guess.


text:
creating object of another class when initializing an object of a class
Here's what I want to achieve:
I'm building a class for controlling step motors. In that class I want to have a method called "init". In that method I'd like to create an object of class Tone, which I'll need to control a motor.
BUT I want to have seperate Tone class object for every object of my class that I create. How can I do it?
So, for exmaple, if I have:
myClass newmotor1;
memotor1.init();

After executing these two lines, I'd like to have my object newmotor1 (which I have, because I just created it) AND an object of class Tone, which I'll use.

Why do you want to create it in the init function? Why not just have one in the class already?

But I want to have seperate Tone objects for each object of my class

And? What difference does that make?

To be honest, I'm not sure what you mean. I'm actually new to classes, objects and all that stuff. Could you explan?

You use a class just like any other variable. Just use it in your class like any other variable.

I think I understand now, that's a good idea. I've been learning C# recently for my work, I wonder if it could be done in C# too (I'm not talking Arduino at all now, I'm just curious if similiar thing could be applied to C# program)

No idea. I have never used that inferior language ;)

Oh come on, I think it's quite good.

You don't need to "create" anything. Just have an object in your class:
class Tone {
    public:
        void dosomething() {
            // Whatever is in here
        }
};

class MyMotor {
    public:
        Tone tone;
        void init() {
            // Nothing much else to do in here now.
        }
};

You then:
MyMotor newmotor1;

And you can access:
newmotor1.tone.dosomething();

That's a perfect solution. Thanks Majenko!


text:
How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)?
//In order to connect,

SoftwareSerial esp8266(2,3);

// the TX pin of esp8266 is connected to pin 3 of
// arduino uno and RX pin is connected to 2
// we need to pass baud rate to begin function

void setup()
{
  Serial.begin(115200);
  esp8266.begin(???); // what should i do in order to make it work?
}

What should i do in order to make it work?

Simplest to just re-flash the AT firmware. Follow one of the many thousands of tutorials, or find all the answers here telling you how.

I tried to flash, everywhere it is asking for baud rate to communicate to esp8266,i tried 9600 which is configured for my arduino, it doesnt work.

You need the bootloader baud rate. Try 57600.

Hi Majenko, i tried all the possible standard baud rates(including 57600), did not work :/

I couldn't find a solution, So, bought new esp8266 and worked with it default baudrate (115200).

I encountered a similar situation where I accidentally set the baudrate to 8000 with the AT commands.
Thankfully I remembered the baud rate I set, so I used PuttY to create a serial communication with the port with the weird 8000 baud rate and changed the baud rate back to 9600.
The method can be found here: http://flower-platform.com/2015/12/16/esp8266-with-at-commands-connect-from-pc-with-putty/
The AT command I used to change the baud rate:
AT+UART_DEF=9600,8,1,0,0

I'm not going to vote this down, but you know "which I dont remember)" in the question title is probably designed to discourage this answer.


text:
Cycling LED's for specific time period with millis()
My goal in pseudo code is :
only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.
unsigned long currentTime;
unsigned long previousTime1 = 0;
unsigned long previousTime2 = 0;
unsigned long previousTime3 = 0;
unsigned long interval1 = 6000;
unsigned long interval2 = 2000;
unsigned long interval3 = 4000;

void setup() {

  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

}

void loop() {

  currentTime = millis();

  if (currentTime - previousTime1 >= interval1){
    previousTime1 = currentTime;
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
  }

  if (currentTime - previousTime2 >= interval2){
    previousTime2 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  }

   if (currentTime - previousTime3 >= interval3){
    previousTime3 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  }
}

A way to make this work is to use only one previousTime variable, rather than three of them.
When the program as shown above starts out, millis() is in fact close to 0, so none of the three LEDs should light up in the first 2 seconds.  At the 2 second mark, LED 7 comes on.  previousTime2 gets set to current time, so the second if is not going to be satisfied for 2 more seconds.  At that point, LED 7 and 8 are in a race to see which one turns on second; whichever turns on first at the 4-second mark gets turned off within milliseconds, because when any LED turns on, the code turns off the other two LEDs.  Whenever the condition for LED 6 is met, so is the condition for at least one of 7 or 8; so 6 can't stay on more than 2 seconds at most, and even then is in a race with 7 and 8 to come in third.
With a single previousTime variable, code like the following might work.
current = (millis() - previousTime)/1000;
if (current < 6) {
  digitalWrite(6, HIGH); // turn on 6
} else {
  digitalWrite(6, LOW);  // turn off 6
}
if (current >= 6 && current < 8) {
  digitalWrite(7, HIGH); // turn on 7
} else {
  digitalWrite(7, LOW);  // turn off 7
}
if (current >= 8) {
  digitalWrite(8, HIGH); // turn on 8
} else {
  digitalWrite(8, LOW);  // turn off 8
}
if (current >= 12) {
  previousTime = millis();
}

Note, the following code has the same effect.
current = (millis() - previousTime)/1000;
digitalWrite(6, current < 6);                 // turn 6 on or off
digitalWrite(7, current >= 6 && current < 8); // turn 7 on or off
digitalWrite(8, current >= 8);                // turn 8 on or off
if (current >= 12) {
  previousTime = millis();
}


text:
Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate?
I have made a 8*8*8 led cube using arduino. I have found two different codes from different developers having different animations in them. i wanted to combine them and get to run all the animations at once. Both the codes have some similar function names and some are different as well. I wanted to know if i can keep both these separate from each other yet run them one after another. Almost all parameters are different including setup() of both codes. Please help

Define "after". An Arduino program runs constantly until you tell it otherwise (by removing the power, pressing reset, uploading a new program, etc). There is no "after" to an Arduino program.

You can achieve this fairly simply by using namespaces. Inside a namespace, symbols are relative to that space. So you could put all of your first sketch into the namespace sketch1, and all of the second sketch into the namespace sketch2 (assuming it all fits, of course).
Now you can call the first sketch's setup and then loop, by qualifying it with the namespace name as illustrated below.
// FIRST SKETCH

namespace sketch1
{

  // FUNCTION PROTOTYPES

  void func1(int a, int b);
  void func2();

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch1 setup");
    func1 (5, 6);
  }

  void loop()
  {
    Serial.println ("Inside sketch1 loop");
    delay (1000);
    func2 ();
  }

  void func1(int a, int b)
  {
    // some function
  }

  void func2()
  {
    // some other function
  }

} // end of namespace sketch1

// SECOND SKETCH

namespace sketch2
{

  // DECLARE FUNCTIONS BEFORE CALLING THEM

  void func3(int a, int b)
  {
    // some function
  }

  void func4()
  {
    // some other function
  }

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch2 setup");
    func3 (7, 8);
  }

  void loop()
  {
    Serial.println ("Inside sketch2 loop");
    delay (1000);
    func4 ();
  }

} // end of namespace sketch2

// MAIN LOOP AND SETUP

void setup()
{
  pinMode (10, INPUT_PULLUP);
  if (digitalRead (10) == HIGH)
  {
    sketch1::setup ();
    while (true)
      sketch1::loop ();
  }
  else
  {
    sketch2::setup ();
    while (true)
      sketch2::loop ();
  }
}   // end of setup

void loop()
{

} // end of loop

In my example I am testing a pin (10) to see if sketch1 or sketch2 should run.

yet run them one after another

Yes, well sketches normally keep running inside loop forever, so you would need a way of deciding when to exit the sketch and run the other one. My example shows how you can choose between one or the other based on a digital input.

I tried it but it is showing that the functions are not declared in this scope.

Important note re function prototypes
It looks like the IDE's automatic generation of function prototypes doesn't work inside namespaces. Thus you need to do either:

Make your own function prototypes (that is the function declaration without the actual function code) - see sketch 1 above; or
Declare a function before it is used (sketch 2 above)

If this is someone else's code you may find it easier to just add the function prototypes as required. When you get the error message, find the function it is referring to, copy the "declaration" part, eg.
void foo (int a, int b)

Add a semicolon, eg.
void foo (int a, int b);

Then put that before it is called. Make sure it is still inside the namespace.

can I call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop?

Well, you can do that, but you need to realize what each sketch is doing. For example if sketch1 turns some pins to output, but sketch2 assumes they are still inputs, then you need to undo that.

And what is it to wrapup a function and 'how' to do it.

You need to inspect the sketches and see what they have done, so you can "undo" it. For example:
void wrapup ()
  {
  // set all pins to inputs and LOW
  for (int i = 0; i < 20; i++)
    {
    pinMode (i, INPUT);
    digitalWrite (i, LOW);
    }
  // if Serial used
  Serial.flush ();  // flush output
  Seral.end ();    // stop serial hardware

  // and so on

  }   // end of wrapup

I tried it but it is showing that the functions are not declared in this scope. The program didn't compile 2nd Q: And will sketch1::loop (); will run the loop of sketch1 forever?. I want it to run once and next sketch should run. The 2 codes should run one after another indefinitely without any condition. how shall i achieve that?. Or can you please provide me your email so that i can send you the codes and you could combine them if you've got a bit of time. please it would be a great help as i am a newbie and will truly appreciate your work.

Nick's code compiles for me. The problem is with your changes. Try and fix them, and if you can't, create a minimal, complete, verifiable example and post a new question.

Regarding making them one one after the other, I don't think there's a one-size-fits-all answer for that. Really you need to understand what the code is doing, and find a way to adjust it. That's the fun of Arduinos anyway.

As I said in my answer, most Arduino sketches are designed to loop forever. So to make one proceed after the other you have to redesign that paradigm. And no, I'm not giving you my email address.

See amended answer about generating function prototypes.

Thanks. that problem was solved by doing as you said. One problem still persists. one of the two codes that i mentioned also has custom libraries attached to it and has .h, .cpp files too. when compiling there are errors like undefined references. first code does not have any custom libraries.  so i removed the namespace from the second code(having custom libraries) and only called sketch1 in the second code like sketch1::setup ();. But this too gives only one error which is  undefined reference to `sketch1::SPIClass::begin()'

The #include statements need to be at global scope (not in a namespace). After all you need the library anyway and there won't be name clashes with the libraries (or hopefully not anyway). There is no point in hiding that inside a namespace. Also the automatic library detection that the IDE does probably won't work if you have the #include in a namespace.

Thank You @NickGammon The Cube now works fine and the program runs smoothly.

Just one more question i wanted to ask. At the main (final) setup and loop, can the functions which are inside the namespaces be called individually?.My Aim is to run one namespace sketch after another 'unconditionally'(the present condition is dependent upon the pin (switch) to be 1 or 0). i.e in the main loop can i call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop. Or is there any way you know to run these sketches one after another unconditionally.

Namespaces are just ways of organizing function (and variable) names. You can certainly call from one namespace to the other. For example inside namespace sketch2 you could call sketch1::setup ();. Just be careful that any resources used in one sketch are released before you switch to the other one. You might make a function wrapup that releases resources (for example, setting any output pins back to input).

Yes, the same problem is occuring to me.I first call sketch1::setup (); then  call a function from sketch1 like sketch1::func1 ();. then i call setup of sketch 2 and then func if sketch 2 for eg.  sketch2::setup (); then sketch2::func6 ();. here what happens is , func1 runs properly but func6 does not run.And  Suppose i first call setup and  fun6 from sketch1, funcs in sketch2 dont run after them.(i.e the functions called first called sketch work and the functions from next called sketch dont run) .how to solve this problem. And what is it to wrapup a function and 'how' to do it.

See amended answer.

Re. your wrapup(): you don't need to digitalWrite(i, LOW) after pinMode(i, INPUT) (doesn't hurt either...), as pinMode() takes care of both the PORT and DDR registers when setting the pin as either INPUT or INPUT_PULLUP. Only when you set a pin to OUTPUT it leaves the PORT register in whatever state it was before.

@NickGammon In the past I did something similar, but I did it in this way: void (*loop_ptr)(); /* in the setup */ if (..) { setup1(); loop_ptr = loop1; } else { setup2(); loop_ptr = loop2; } /* in the loop */ void loop() { loop_ptr(); }. This is because outside the loop there is some code in the arduino main. Another way would be to set a variable and inside the loop call void loop() { if (use_prg1) loop1(); else loop2(); }. What do you think? PS sorry for double comment, but I mistakenly pressed enter before and now I can't modify the previous one

That's OK if it works, but if you have other functions (say from example code) which happen to have the same name then you get name clashes. The namespace idea isolates each bunch of code into a non-clashing area.

@Nick, your answer is masterful.  As usual.  I always learn something new from your posts and I will keep this in mind.  But I think it might be a bit overwhelming for this user.

@SDsolar Thanks! It may or may not be too complex for some users, but it might give others an idea for how to fairly simply merge two sketches that have the same function or variable names. :)


text:
Aurduino Smart Wifi Wall Socket
i wanted to make a remote controlled wall socket over wifi (and maybe internet in the future) with an Arduino, i'm relatively new to Arduino, i know only the basics of programming. My idea was to use a Arduino Pro Mini, a relay, a Esp8266 wifi module to connect to my home wifi and maybe a module to monitor consumption like the ACS712 current sensor but i don't know how to make all of this work, maybe i can get the Arduino working but i don't know how to control it on the client side like an app or web interface on my phone/computer.

You only need the ESP8266, which can be programmed using the Arduino IDE as if it were "an Arduino"

Or buy a Sonoff, which contains an ESP8266, and hack it if it doesn't already do what you want.

@hapi how could you do that? Isn't the ESP8266 just a wifi module?

@MarkSmith the Sonoff is not bad but i want to control it over WiFi network not over RF so it doesn't do what i want.

They are wifi controlled. (Wifi is RF, given that it's radio...)

@MarkSmith you're right, sonoff is just what i want and what karx suggested i could do, but if I want to monitor consumption?

The hardware you have chosen is perfect for the job at hand.
But what @Hapi also mentioned was that you could probably do away by not using the Arduino !
The ESP8266 is in itself programmable. There are many Firmwares available to help you do so. (You can even program your own)
This can help you getting started : http://randomnerdtutorials.com/esp8266-web-server/
This is something like what you need at the end : https://hackaday.io/project/4562-esp8266-wifi-smart-garage-door
One thing to note : ESP8266 works with 3V, while your Relay would require 5V.
Happy hacking my friend.

All the Hardware mentioned are correct,
Arduino Pro Mini (Micro-controller) - To control the Relay
5V Trigger Relay(240V) which would be trigger using a digital Pin on the Arduino.
http://www.instructables.com/id/Controlling-AC-light-using-Arduino-with-relay-modu/
Once you accomplish the steps above you must hook up your wifi module.
Then write a software in your preferred/environment for example, Visual Studio C#, and Use the a UDP or Telnet or HTTP Web-Server ( http://blog.nyl.io/esp8266-led-arduino/ ) connection to sends command to the Arduino though the Wifi Shield, which will trigger the Relay and therefore turn on the Switch.
Also you must find an adapter that sits into the socket and convert 240V AC to 5V DC power to match the consumption of your Arduino.

The adapter to convert 240V AC to 5V DC is not a problem, i can use an old cellphone charger, the HTTP Web-Server connection is very interesting i took a quick look at it maybe i will use it. I still haven't all of the hardware to make a proof of concept but i will soon.

@alex3850 well keep me updated,  hope the answer help you out.

For now I'm waiting for the Arduino and other stuff to arrive then I will try to do some thing, your answer is really helpful.


text:
Battery voltage monitor right after deep sleep
i have my esp32 module in deep sleep and i use it with a couple of buttons using a wake up that detect the button pressed
now i'd like to have a battery level to send to a server right before going back to deep sleep. How can i do it?
and what cheap rgb led do you suggest using?

what cheap rgb led do you suggest using?  ... use for what?

for usage in combination with low power device drived by an esp32

Using "battery level" (voltage)  is poor way to monitor its useful life. Battery discharge  characteristic varies with its technology.
On the other hand many electronics devices are very tolerable as far as "supply level " AKA voltage.
RGB LED light intensity can be made to monitor different voltage, however, I fail to see how you propose to send the LED intensity level /state to other device.
Addendum
As I pointed out - the battery useful life depends on technology.
You mentioned AAA , hence I assume alkaline battery.
Then I would suggest software solution.
Let the server monitor the actual running time of your device.Then measure or calculate the load your device is drawing from the battery.
Then determine or calculate the discharge curve of your battery and let the server "output" the battery life / discharged level in relation to time. Perhaps I misunderstood and you actually wanted the RGB LED to be connected to the server. Then you can display green LED up to 80% of battery life and so on ...Keep in mind that the discharge curve is pretty abrupt at the end of battery useful life,

i need the esp32 to know the battery level, and power source will always be 2 aaa battery, so it can send to a server the estimated battery lifer remaining


text:
Power management circuit
i'd like to have a esp-01 powered on and controlled with a push button only.
so imagine the device is off, the user press the momentary push button. in the setup the esp8266 turn on a mosfet or something similar to give himself power using another line. the user release the button and the device is on. i want to be able to understand long button press and double press and similar stuff too. even when device is already powered on. so i need to have a pin attached to the button somehow
this is what i have till now, thanks to a very skillfull friend of mine
the vcc is 5 v and pin tollerance is only 3v
it must be completely off when not pressed for long battery duration

Q2 looks upside down to me...

yeah probably yes

You need to isolate your button from the logic output using a diode. For example:

simulate this circuit – Schematic created using CircuitLab
In this method M1's gate is normally pulled up by R2. It can either be pulled down by M2 (switched by the "HOLD" signal) or by the switch via D1.
The BTN input is pulled up by R1, and can be pulled down by the switch. M2 can't pull it down because the diode is reverse biased and blocks current trying to flow from BTN via M2 to ground.
R3 is just a pull-down on the gate of M2 to keep it off when HOLD is floating (the power is off).
If you need to interface the 5V "BTN" signal with a lower voltage-tolerant input pin just use a couple of resistors as a voltage divider to reduce the voltage to within the proper levels for the pin.

this is a good solution. the problem is that I'll use 3v as in, and the btn should work  the opposite: high when button pressed and low all the rest of the time

3v for control (HOLD) is fine as long as M2's threshold is suitable. 3V for sensing (BTN) can just go through a simple voltage divider. Why do you need the button reversing? It needlessly complicates things.


text:
how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6
I have to switch 2 MOSFET IRF640 at a duty ratio of .6 and the frequency of  switching is  50khz how can I generate it with a single aurdino

Please read How do I ask a good question?.

This could be achieved either with software (with a timer interrupt or
by polling micros()) or with hardware. The software methods, however,
are prone to a high level of jitter. If you want to have a steady
signal, you should use a hardware solution.
The most straightforward hardware option is to use a timer in PWM mode.
I would avoid fiddling with timer 0, as it is used by the Arduino
timekeeping functions. You are left with either timer 1 or timer 2. The
following program configures timer 2 to output the desired signal:

period = 20 µs = 5 × 64 CPU cycles
signal HIGH for 12 µs = 3 × 64 CPU cycles.

The output goes to pin 3, which is one of the two PWM pins controlled by
timer 2.
void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 = digital 3 as output
    OCR2A  = 5 - 1;       // period = 5 * 64 CPU cycles
    OCR2B  = 3 - 1;       // HIGH for 3 * 64 CPU cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22)   // ...ditto
           | _BV(CS22);   // clock at F_CPU / 64
}

void loop(){}

For some in depth information on how timers work, see
Nick Gammon's tutorial on timers.

Lots of ways.

Use a timer interrupt.
Use a pwm module.
Use the output compare module.
Use the SPI module.
Use a timer.
Use a pwm generator.

.......
Literally endless ways of doing it.

Endless ways of naming the same things: 2, 3 and 6 are the same, 5 is the same as either 1 or (2, 3, 6).


text:
LCD Display Issue
Hi I am a newbie I am trying to test LCD but it always show me a fading boxes It was working before .
connection
LCD p1 - gnd
Lcd p2 - VCC
Lcd p3 - potentiometer middle (10k)
lcd p4 - pin 7 microcon
lcd pin 5 - gnd
lcd pin 6 - pin8 microcon
4 vacant lcd spaces
lcd pin 11- pin9 microcon
lcd pin 12 - pin10 mocrocon
lcd pin 13- pin 11 microcon
lcd pin14- pin 12 microcon
lcd pin 15- 5v
lcd pin 16- gnd

Try pressing down on the metal surrounding the display, and see if that changes the display. If so you'll have to reseat the display. Probably something wrong with the zebra-strip not making proper contact.

it keeps blinking and showing boxes when I pressed it thank you very kuch for your response

Your pin arrangement makes no sense. You have one pin connecting to the potentiometer, yet the potentiometer doesn't seem to be connected to anywhere else. Check your wiring against one of the many tutorials out there.

potentiometer connected to gnd and vcc


text:
Is my arduino board broken?
Last night I had my arduino connected to pc and mc connected to 9 volts in the same time then today I tried to connect my arduino to pc and i removed any connection i just wanted to display a string it i used this code
 void setup() {
  Serial.begin(9600) ;
  }

   void loop() {

    Serial.print("NO FORMAT");
     }

its not showing anything in serial montor I tried to blink led no output still
And  i have another arduino i used the same code it showing the message in serial monitor is my previous board broken ? thank you for help when i tried to click the reset button in arduino the orang led built in is not blinking

I assume that PWR LED is turned on?
If on USB connection PWR LED is off and on 9V connection it turns on you should check fuse. It is on the right side of USB connector and is protection only from USB voltage source.
If it works you should check level of voltages or try connect usbasp and then using avrdude check if it is connecting normally.
Few ideas for voltage levels:

Voltage on "main" ATMega328 (You can check it through ISP header)
Voltage on Arduino's chip which is ATmega16, or CH340 if you have chinese one (or something like that). It should be the same as on main Arduino, but to be sure...
Voltage on reset

You need around 5 volts to be sure that it works properly because of construction of arduino's board.
If you still have no answers, no voltages you should check Arduino's schematic for more information: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
If there is electrically everything all right and you did not check with usbasp (or other AVR-compatible programmer) I believe that next step is to check bootloader on your board.


text:
Deep sleep hangs when used with D0 pin when we connect to reset pin in nodemcu
I am using a nodemcu and running a code using hall effect sensor and ultrasonic sensor with deep sleep except the deep sleep keeps hanging when I use this code. With code taken from online it does not hang. What is wrong with my code Please help me!
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define sleepInterval 30 // 6 minutes

// Update these with values suitable for your network.

const char* ssid = "Thief_3h";
const char* password = "lan";
const char* mqtt_server = "ipaddress";
const char* mqtt_topic = "sensors/test/";
const int trigPin = 2;  //D4
const int echoPin = 0;  //D3
long duration;
float distance_cm;
const int hallSensorPin = 14;                      // connect the hall effect sensor on pin 2
const unsigned long sampleTime = 1000;
float radius = 10;
float velocity;
float rdepth = 5;
float cm;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[75];
int value = 0;
int rpm;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("/test/river/rpm", "starting");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void ultra(){
  delay(2000);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
   // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  //cm = microsecondsToCentimeters(duration);
  distance_cm = ( duration / 29 ) / 2;rdepth;
}

int getRPM()
{
  int count = 0;
  boolean countFlag = LOW;
  unsigned long currentTime = 0;
  unsigned long startTime = millis();
  while (currentTime <= sampleTime)
  {
    if (digitalRead(hallSensorPin) == HIGH)
    {
      countFlag = HIGH;
    }
    if (digitalRead(hallSensorPin) == LOW && countFlag == HIGH)
    {
      count++;
      countFlag=LOW;
    }
    currentTime = millis() - startTime;
  }
  int countRpm = int(60000/float(sampleTime))*count;
  return countRpm;
}

void goToSleep() {
  ESP.deepSleep(1000000 * sleepInterval);
}

void setup(){
  pinMode(hallSensorPin,INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  //pinMode(D0, WAKEUP_PULLUP);
  delay(1000);
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(100);
   rpm = getRPM();
  velocity = (rpm * 2 * 3.14 * radius)/60;
  ultra();
  delay(1000);
  senddata();
  delay(1000);
  goToSleep();

}

void senddata(){

distance_cm = ( duration / 29 ) / 2;rdepth;

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;

    snprintf (msg, 75, "Velocity:%6.2f Depth:%.2f", velocity, distance_cm);
    Serial.print("Publish message: ");
    Serial.println(msg);

    client.publish(mqtt_topic, msg);
  }
    Serial.print("RPM:");
  Serial.println(rpm);
  Serial.print("Velocity:");
  Serial.println(velocity);
  Serial.print("depth:");
  Serial.println(distance_cm);

}

void loop(){}

"With code taken from online it does not hang" With what code taken from online?

Move client.loop(); into the loop(), if your esp going to sleep for 6 minutes, you may also want to #define MQTT_KEEP_ALIVE 300. If you are expecting data to be received before go to sleep, then move ESP.deepSleep(1000000 * sleepInterval); into the end of the callback function.


text:
Is the DHT.h library compatible with ESP8266 Arduino IDE compiler?
I'm using the following 'compiler' to program my ESP8266-01 direct with Arduino IDE:
https://github.com/esp8266/Arduino
and I'm trying to read the temperature and humidity with the following library:
https://github.com/adafruit/DHT-sensor-library
since the DHT library was developed to be used on an Arduino board, should I be able to run it on the ESP8266?

Yes, it does work. You may have a look at http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html where a list of libraries running with ESP8266 can be found. Furthermore, @anrieff's remarks regarding hardware-specific features are a good hint.

As far as I see, the DHT sensor library does bit-banging, which is kind of expected given the ad-hoc nature of the protocol that DHT type of sensors utilize. It should be compatible, as the library doesn't use any Atmel-specific features of the MCU.


text:
Communication between 2 nRF24l01s and 2 Arduino unos
I am having a logical error that I can not figure out with the communication. I am communicating fine with the two boards such that I can send and receive data. Code to my Transmitter and Receiver. Serial outputs here. Using library from this site: (Sorry reputation too low to add another link)
www.instructables.com/ORIG/FV6/0AAE/IBXM5ZIY/FV60AAEIBXM5ZIY.zip
(WARNING: will download with out permission if you visit link above. Use below link if dont want to download)
www.instructables.com/id/Wireless-Remote-Using-24-Ghz-NRF24L01-Simple-Tutor/?ALLSTEPS
(Scroll down to step 4, library's are labeled as "library files.zip". Names inside the zip folder are "nRF24L01" and "RF24")
From the Serial outputs I do not understand why on my transmitter it says it sent the time in milliseconds, 5873, but on my receiver output it says it received 241. Also I do not understand how the millis() function on the receiver returned a lesser value than what the transmitter should have sent.
I have novice understanding of c++ and the nRF24L01 radio at best. Any information is appreciated.
Thank you in advance!

Hint: 5873 = 22 x 256 + 241. It seems you transmit (or receive, or print, I did not check your code) only one byte.

@jfpoilpret Good catch. This looks like the culpret: radio.write(msg, 1); - wite just one byte from the msg start address.

@Majenko Thank you for the feedback I changed the .write(msg, 1) to .write(msg, 2) but after a while it goes back to sending the wrong time i'm assuming the byte got larger. How would I write it to receive all bytes?

A long is 4 bytes.

Use sizeof() to get a type's lenght. Also check out github.com/TMRh20/RF24Network and RF24Mesh.


text:
Start/Stop/Reset the melody using buttons
I have 2 buttons.  Button 1 will start/stop the melody while the button 2 will reset the melody. My melody is "Happy Birthday".
How am I going to use the buttons to start/stop/reset the melody?
Here's the code:
#include "pitches.h"

int melody[] = {
    NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, NOTE_C4, NOTE_B3,
    NOTE_G3,NOTE_G3, NOTE_A3,NOTE_G3, NOTE_D4, NOTE_C4,
    NOTE_G3, NOTE_G3, NOTE_G4,NOTE_E4,NOTE_C4, NOTE_B3, NOTE_A3,
    NOTE_F4, NOTE_F4, NOTE_E4, NOTE_C4, NOTE_D4, NOTE_C4
};

int noteDurations[] = {
    8,8,4,4,4,2,8,8,4,4,4,2,8,8,4,4,4,4,3,8,8,4,4,4,2
};

boolean needtoPlay;

void setup() {
    pinMode(4, OUTPUT);
    pinMode(2, INPUT); //START/STOP
    pinMode(3, INPUT); //PAUSE
}

void loop() {
    for (int thisNote = 0; thisNote < 26; thisNote++) {
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(4, melody[thisNote], noteDuration);
        int pauseBetweenNotes = noteDuration * 1.60;
        delay(pauseBetweenNotes);
        noTone(4);

        if (needToPlay == true) {
        }
    }
}

Step one is to make it work without using delay().

this one? delay(pauseBetweenNotes);

That's the only delay there is, yes...

Modify your code so notes will play using timer interrupts instead of delay(). Once your program is inside delay(), no button will be responded. Done that, you just have to read buttons either by polling them with digitalRead or using interrupts.

Easiest way would be to add this to the end of the for loop (inside the loop).  Assuming buttons are pulled up.
//setting pause with pause button
if (digitalRead(pauseButtom) == LOW) {
    //it will not play while in this loop
    while (true) {
      //if the button is pressed again, exit the loop
      if (digitalRead(pauseButtom) == LOW) {
        break;
      }
      delay(10);
    }
}

For the reset, just break;  it will exit the for loop and start again.
Alternately, instead of using a for loop, use a counter and increment / reset it.  You will need to store most variables globally.
if(!paused) {
  //play note
  if (counter < numNotes) {
    counter++;
  } else {
    counter = 0;
  }
}

if (digitalRead(pauseButtom) == LOW) {
  pause = !pause;
}

if (digitalRead(resetButtom) == LOW) {
  counter = 0;
}

You could move those last 2 conditionals to interrupts.


text:
Alternative ways for read Serial Output
its possible to read serial ouput from ICSP or Tx Rx pin instead from USB port? If it's possible how? thanks for reply

You can connect directly to the tx and rx pins to get UART communication

The TX and RX pins are connected directly to the USB to UART adaptor embedded in the board (an ATMega16U2 on the Uno R3, or a CH340G on a cheap Chinese clone). Anything that goes through the USB also goes through those pins.
You can also, if you must, use SoftwareSerial to get serial on any other pair of pins of your choice.


text:
How to pass 'Serial' as an input argument in Arduino function?
I have one integer value which I should pass through Serial1, Serial2, Serial3, and Serial4 after performing some algebraic operation on this integer. For this algebraic operation, I made a function and input arguments is an integer and Serial number.
Simple code is given below: (I deleted every extra part of my code to make easy to understand)
String stringG; int d1; int d;

#include<SoftwareSerial.h>
//Software Serial #1: Rx = digital pin 10, Tx = digital pin 11
SoftwareSerial Serial4(10, 11);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  Serial4.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0)
  {
     String  XX = Serial.readString();
    int d1 = XX.toInt();
    Serial.println(d1);
    int yy;
    yy = compareFunction (d1, Serial4);
    Serial.println("Now the final values are:");
    Serial.println(d1);
    Serial.println(yy);
  }

}
int compareFunction (int d, String Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

As you see in  compareFunction I receive value using Serial (it may be 1,2,3 or 4) So I have to pass Serial as an input argument in this function. If I can't pass Serial then I have to write 4 functions each for Serial1, 2, 3 and 4 which I want to avoid. Is it possible? How can I do it? when I tried with above code it shows error

exit status 1 could not convert 'Serial4' from 'SoftwareSerial' to
  'String'

It's obviously not a String. Did you try to find out what type it actually is?

The Serial object is the end of a chain of classes, each with a different set of functionality.
Print -> Stream -> HardwareSerial => [Serial]

Since you are reading from it the best class to use is Stream since that is the one that is the one that contains the reading functionality.
You should pass it by reference or as a pointer since you don't want to copy the object.
int compareFunction (int d, Stream &Serialx)
{

  int ZZ = Serialx.readString(); // I will receive some values from motor using serial4
  //to avoid long code I deleted unnecessary parts
  // I will use ZZ and d values and output will be yy
  return yy;
}

By using Stream you can use any object type that also uses Stream in its class inheritance chain - even things like a WiFi socket connection.
This behaviour is called polymorphism and is one of the more powerful features of classes in C++ (and other OO languages).

Thanks @Majenko. It works i.e. now I am able to use Serial as input argument in function. But there is one little problem. When, I used Serial1 or  2 or 3, in comapreFunction, in codeString ZZ = Serialx.readString();   Serial.println(ZZ); it gives accurate value like P214 or P417 etc. But when I used Serial4, it gives values like P‚’j or “‚j. What is wrong with Serial4. I used Serialx.println("P"); to get current position of motor.

Well, Serial4 seems to be SoftwareSerial - and it's any one's guess what would happen with that. I never used it. Ever. It's crap. Try one of the replacements, like AltSoftSerial.


text:
Connecting an Ultrasonic Sensor to Arduino (4-Wire)
I have an ultrasonic sensor that came with a couple of images about the pin-out and wiring diagram.
I am used to the popular ultrasonic sensors that have lots of documentation about how to connect to an Arduino - but I am wondering about to connect this sensor to an Arduino.
The Power Supply is 5V DC, with an operating current less than or equal to 12mA.
Any support or similar tutorials that will help me connect this to an Arduino, to see the output in the Serial monitor, would be great!
VCC and GND are self-explanatory, but how should I connect the Output 1 and Output 2 to the Arduino?
Thanks!

First, identify the sensor, and where you found. A snapshot would help as well.

Maybe this can help: http://www.instructables.com/id/Ultrasonic-Range-detector-using-Arduino-and-the-SR/


text:
Send serial command and wait for reply
I am new to Arduino and have tried all kinds of code for attempting to achieve this. None with any luck, however. I feel that it should be a relatively easy task and therefore, figured that someone out there with more proficiency with an Arduino than me, would be able to help.
Essentially, I have two commands sent to a device via the Leonardo serial port. One is the single character "R", and the other is the single character "O". The device then sends back 8 binary bytes (non ASCII) in floating point format per command. So if I send O, it will return 8 binary bytes, and then the same goes for if I sent R.
The commands O and R need to be simultaneously sent via the serial every 250ms and wait for their respective responses before sending the next command.
I also need to store the device's response to O and the device's response to R in respective variables that will have a new value every 250ms. I am not familiar with single point format and therefore am unaware of what variable system to use.
Here is my best, yet unsuccessful attempt:
unsigned long previousMillis = 0;
const long interval = 250;
int responseO;
int responseR;

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

    while(!Serial);
}

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

    if(currentMillis - previousMillis >= interval) { //timer for every 250ms
        previousMillis = currentMillis;
        Serial.println("R");               //Figured that "println" with a string for the character R should be ok

        if(Serial.available() > 0) {          //Don't know if I am correct here, I was hoping that the serial would only be read if the device responded to the command R
            responseR = Serial.read();       //Read serial for device's response to command R and save it in a variable
        }

        Serial.println("O");               //Do the same thing for the command O

        if(Serial.available() >0) {
          responseO = Serial.read();
          }
    }
}

However, whenever I test this, it appears that the program is unable to differentiate between which responses are due to one command, and treats one response as if both commands requested it when only one did. Also is a floating point format variable just a float?
Thank you so so much, I really need some help this has been burning away at me for days........
Cheers, Harry

The code shown in two previous answers is problematic.
For example, in Look Alterno's code, Serial.println("R") will trigger an R response.  The while(!Serial.available()); construct will wait for the first byte of the response.  Then responseR = Serial.read(); will read one byte.  Next, Serial.println("O") will attempt to trigger an O response.  The second while(!Serial.available()); will wait for a byte to be available, which should happen when the second byte of the R response arrives.  Then responseO = Serial.read() will read that byte.
In ratchet freak's code, each quarter second bytesToReadFromR and bytesToReadFromO are set to 8.  In the next several passes through loop(), if(bytesToReadFromR) and if(bytesToReadFromO) are satisfied, so while(bytesToReadFromR && Serial.available()) and while(bytesToReadFromO && Serial.available()) will be controlled by whether a character is available.  At 9600 bps, about one character per millisecond will become available, so most of the time we are just spinning through loop() dozens of times per millisecond, waiting for characters.  The if statement for bytesToReadFromR has a slightly higher chance of catching fresh characters, but which buffer (responseR or responseO) gets any given character still is left to chance.
Instead of the code previously shown, consider something like the following:
enum { dataBytes = 8, interval=250 };

float getResult (char trigger) {
  union { byte d[dataBytes], float f[2] } u;
  byte rin=0;
  Serial.print(trigger);
  while (rin < dataBytes) {
    if(Serial.available())
      u.d[rin++] = Serial.read();
  }
  return u.f[0];        // Assumes bytes in forward order
}

unsigned long prevMillis = millis();
float RValue, OValue;

void loop() {
  if(millis() - prevMillis >= interval) {
    prevMillis = millis();
    RValue = getResult ('R');
    OValue = getResult ('O');
    // put code here to consume the results
    // ...
  }
}

Note, this code will get stuck if too-few characters arrive from the R&O device, or if some characters get lost for any reason.  One could add a timeout to the loop in getResult(); it could check for millis() - prevMillis >= interval and if so, break the loop and return a NAN.
Note, this code assumes the byte-order of floats from the R&O device matches that of the Arduino.  That will be so if both are big-endian, or if both are little-endian.  If they differ, store bytes in reverse order into the u.d array, and return u.f[1] instead of u.f[0].
Note, union is a C / C++ technique for accessing data multiple ways.  The declaration union { byte d[dataBytes], float f[2] } u says that u is a structure where the array d starts at the same address as the array f.  Thus, the float u.f[0] corresponds to the first four bytes of u.d, and u.f[1] to the next four.
Note, if the R&O device requires an end-of-line character, change  Serial.print(trigger) to Serial.println(trigger).

each call to Serial.read will read a single byte. So to read multiple bytes it needs to be called multiple times.
int bytesToReadFromR;
int bytesToReadFromO;

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

    if(currentMillis - previousMillis >= interval) { //timer for every 250ms
        previousMillis = currentMillis;

        Serial.println("R");
        bytesToReadFromR = 8;              //mark that there is data to read from Serial for R

        Serial.println("O");
        bytesToReadFromO = 8;              //Do the same thing for the command O
    }

    if(bytesToReadFromR){
        while(bytesToReadFromR && Serial.available()){
           responseR[--bytesToReadFromR] = Serial.read();       //Read serial for device's response to command R and save it in a char array
        }
        if(bytesToReadFromR){
             //finished transfer, trigger what you need
        }
    }
    if(bytesToReadFromO){
        while(bytesToReadFromO && Serial.available()){
           responseO[--bytesToReadFromR] = Serial.read();       //Read serial for device's response to command O and save it in a char array
        }
        if(bytesToReadFromO){
             //finished transfer, trigger what you need
        }
    }
}

Cheers for the quick reply! The floating point format is IEEE. The device essentially sends 8 bytes in response. 4 bytes of which equal a number, and the other 4 equal another number. (For what it's worth, it's just returning coordinates as 8 bytes). Can I somehow interpret those 8 bytes into the two numbers, which would likely be decimals?

As others have mentioned, you have to read the serial input byte by byte. 4 bytes means you have to read it four times and store the values in an array. Then do your calculations with the array.
After a little googling I found this: https://stackoverflow.com/questions/3991478/building-a-32bit-float-out-of-its-4-composite-bytes-c
Which is basically what you want to do. Try this code:
unsigned long previousMillis = 0;
const long interval = 250;

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

void loop() {

  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) //timer for every 250ms
  {

    previousMillis = currentMillis;

    Serial.println("R");               //maybe substitute with
    if(Serial.available() >0)          //Serial.println('R'); or
    {                                  //Serial.write("R");   or
      byte buff1[4];                   //Serial.write('R');
      byte buff2[4];
      float firstNumber;
      float secondNumber;

      for(int i=3; i>=0; i--){
        buff1[i] = Serial.read();
      }
      for(int i=3; i>=0; i--){
        buff2[i] = Serial.read();
      }

      memcpy(&firstNumber, &buff1, sizeof(firstNumber));
      memcpy(&secondNumber, &buff2, sizeof(secondNumber));

      Serial.print("first number is: ");
      Serial.println(firstNumber);
      Serial.print("second number is: ");
      Serial.println(secondNumber);

    }

    //do the same thing with your "O" command, or write a function

  }

}

There are two things to consider though:

As you can see I am looping the buff1 and buff2 arrays backwards. This is because the endianness of the float depends on how your device sends them. If you were receiving gibberish change the loops to count from 0 to 4.
You said your device expects a single 'R' character but what you are doing is sending a "R" string and then a new line character after that(because you are using println()). It's possible that you will have to substitute that with one of the options I mentioned in the code comment.


text:
Using SlickEdit to compile Arduino files
I would like to compile my Arduino sketches in SlickEdit.  I have turned on the verbose compile output in the standard IDE and I can see the compile and switches, but it doesn't appear that there is a Makefile in use.  I don't see the "Entering" and "Leaving" messages that I associate with Make anyway.  Is using a third party tool to control the build an Arduino no-no?  Has anyone used Make to build Arduino?

Can you elaborate please? What is SlickEdit? (link). I don't see the "Entering" and "Leaving" messages that I associate with Make anyway. - make doesn't have such messages per se. Is using a third party tool to control the build an Arduino no-no? - no, a lot of people do that.

Arduino doesn't use Make. In the settings there is an option to use an external editor. If you enable this you can write code in SlickEdit, but you'd have to use the Arduino IDE for compiling and uploading.

Try to see if you can live with using slickedit as the externally editor. I havent used slickedit as a project mgmt but have done so with si and pn. Both are fairly straight forward but thee setup process is fairly manual. On the automation from sublime text can be used as a full blown Arduino environment so you may check that out as a possible alternative.

Many people use Make to compile Arduino software - but the Arduino IDE doesn't. There are many projects online to implement the build procedure using Make. Try googling for them.

The first two lines of the arduino verbose output show you how to call the arduino builder api. It will then do the rest.

@VisualMicro, you should add this as the answer.  After creating two tools(one for each line) in SE, a dump-prefs and a Build, I get a binary.  Adding a third tool called Download, lets me perform all basic operations in SE that I do in the IDE.


text:
Problem with TIMER in Arduino DUE
I'm writing a code to print/update the value of sensors for each 10 ms, and I decide to use Timer instead of delay function (I'm afraid it's not exactly 10ms with delay function).But when I watch the result on terminal, it stops running at about 0.5s. I guess there is a problem with my code in using Timer because when I remove timer, it prints normally. I debug all day but still cannot find any errors. I guess this is related to memory or pointer or print function.
Please help me :( !!
Here is the code. The code is very long but you can ignore all the unnecessary things:
  #include <DueTimer.h>

  int mod_11k = 12;
  int mod_17k = 13;

  int analog1 = 0;              //output pin of signal 1
  int analog2 = 1;              //output pin of signal 2
  int analog3 = 2;              //output pin of signal 3

  float xf; float yf;
  unsigned long t1;
  unsigned long t2;

void myHandler(){
    Serial.print(t2-t1);
    Serial.print(" ");
    Serial.print(xf,3);
    Serial.print(" ");
    Serial.println(yf,3);
}

void setup() {
  Serial.begin(38400);
  pinMode(mod_11k,OUTPUT);
  pinMode(mod_17k,OUTPUT);
  Timer1.attachInterrupt(myHandler).start(10000);
  digitalWrite(mod_17k,LOW);
  digitalWrite(mod_11k,HIGH);
}

void loop() {
    afficherSig(analog1,analog2,analog3);
}

void afficherSig(int pin1, int pin2, int pin3){
  unsigned int i;
  float mes[3];
  float mesflt[3];
  float x; float y;
  int  nb_ech = 10000;
  float res = 0.0049;
  float Te;
  float Tbeg;
  float QR1[2],QR2[2] ;
  float *sol1;float *sol2;float *sol3;
  float P1[4];float P2[4];float P3[4];
  float xprec1[2];float xprec2[2];float xprec3[2];
  float *s1_11k;
  float *s1f_11k;

  float H = 80;

                                       //------------------------------>>>
  QR1[0] = 1;
  QR1[1] = 10;
  QR2[0] = 1;
  QR2[1] = 100;
  P1[0] =QR1[0]; P1[1] =0; P1[2] =0; P1[3] =QR1[0];
  P2[0] =QR1[0]; P2[1] =0; P2[2] =0; P2[3] =QR1[0];
  P3[0] =QR1[0]; P3[1] =0; P3[2] =0; P3[3] =QR1[0];
  xprec1[0] =0; xprec1[1] =0;
  xprec2[0] =0; xprec2[1] =0;
  xprec3[0] =0; xprec3[1] =0;
                                      //------------------------------>>>
  t1 = millis();
  Tbeg= millis();
  mes[0]  = res*analogRead(analog1);
  mes[1]  = res*analogRead(analog2);
  mes[2]  = res*analogRead(analog3);

  xprec1[0] = mes[0];
  xprec2[0] = mes[1];
  xprec3[0] = mes[2];
  Te = (millis() - Tbeg)/1000;
  Tbeg = millis();
  sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
  sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
  sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

                                      //------------------------------->>>
 for(i=1;i<nb_ech;i++) {

    P1[0] =sol1[2]; P1[1] =sol1[3]; P1[2] =sol1[4]; P1[3] =sol1[5];
    P2[0] =sol2[2]; P2[1] =sol2[3]; P2[2] =sol2[4]; P2[3] =sol2[5];
    P3[0] =sol3[2]; P3[1] =sol3[3]; P3[2] =sol3[4]; P3[3] =sol3[5];

    xprec1[0] =sol1[0]; xprec1[1] =sol1[1];
    xprec2[0] =sol2[0]; xprec2[1] =sol2[1];
    xprec3[0] =sol3[0]; xprec3[1] =sol3[1];

    free(sol1);
    free(sol2);
    free(sol3);

    mes[0]  = res*analogRead(analog1);
    mes[1]  = res*analogRead(analog2);
    mes[2]  = res*analogRead(analog3);

    Te = (millis() - Tbeg)/1000;
    Tbeg = millis();
    sol1 = Fkalman(xprec1,mes[0],P1,QR1,Te);
    sol2 = Fkalman(xprec2,mes[1],P2,QR1,Te);
    sol3 = Fkalman(xprec3,mes[2],P3,QR1,Te);

    mesflt[0] = sol1[0];
    mesflt[1] = sol2[0];
    mesflt[2] = sol3[0];                               // Envoie des résultats  à la sortie série

//Traitment du signal
    s1_11k = traitement1(mes[0],mes[1],mes[2]);
    s1f_11k = traitement1(mesflt[0],mesflt[1],mesflt[2]);

    x = H*s1_11k[0];
    xf = H*s1f_11k[0];
    y = -H*s1_11k[1];
    yf = -H*s1f_11k[1];
    t2 = millis();
  }
}

float *Fkalman(float xprec[2],float ymes,float P[4],float QR[2] ,float Te){
                     // Filtre proprement dit
    float *sol = NULL ;
    sol = (float*) malloc (sizeof(float) * 6);
    float xpred[2];
    float Ppred[4] ;
    float Kf[2] ;
    int q = QR[0];
    int r = QR[1];

    xpred[0] = xprec[0] + Te*xprec[1];
    xpred[1] = xprec[1];
    Ppred[0] = q*q + P[0]+ Te*(P[2] +P[1]+Te*P[3]);
    Ppred[1] = P[1] + Te*P[3];
    Ppred[2] = P[2] + Te*P[3] ;
    Ppred[3] = q*q+ P[3];
    Kf[0]  = (Ppred[0]/(r+Ppred[0]));
    Kf[1]  = (Ppred[2]/(r+Ppred[0]));

    sol[0] = xpred[0] + Kf[0]*(ymes-xpred[0]);
    sol[1] = xprec[1] + Kf[1]*(ymes-xprec[0]);
    sol[2] = Ppred[0]*(1-Kf[0]);
    sol[3] = Ppred[1]*(1-Kf[0]);
    sol[4] = -Kf[1]*Ppred[0]+Ppred[2];
    sol[5] = -Kf[1]*Ppred[1]+Ppred[3];
    return sol;
  }

  float *traitement1(float mes1,float mes2,float mes3)
  {
    float *sol11 = NULL ;
    sol11 = (float*) malloc (sizeof(float) * 2);
    sol11[0] = (mes1-mes2)/(mes1+mes2);
    sol11[1] = (((mes1+mes2)/2)-mes3)/(((mes1+mes2)/2)+mes3);
    return sol11;
  }

Here is the result using Timer (stop at about 0.5 second):

Using Serial.print inside the timer interrupt routine is not advised. It also doesn't look like it is doing what you actually want, and that is to measure every 10 ms. It just reports the last measurement every 10 ms (which might be stale). For now try increasing the baud-rate of the serial connection, and see if that helps.

I increased baud-rate, it still stops in the middle (but the program can print results longer). Can you suggest any modification of the code to achieve my objective? (I tried using millis() but it still stops in the middle).

As noted in the last part of Nick Gammon's answer to the question How does the Arduino handle serial buffer overflow?, if the serial output buffer fills up, serial output blocks, waiting for an interrupt telling it it's ok to send the next byte out the serial port.  When interrupts are turned off, that interrupt is never processed, so the program deadlocks. Don't do Serial prints in an ISR.
Looking at your code, it looks like a typical message has about 20 characters.  Sending at 38400 bps, or 384 characters per second, it seems to me the buffer shouldn't fill, even if it's small (16 bytes) instead of large (64 bytes).  However, I don't know of another explanation for the behavior you describe.
Summary:  In your ISR, just store the current time and other relevant data in volatile variables, set a flag in a volatile variable, and in your main loop print stuff and clear the flag (or clear the flag and print stuff) whenever you see that the flag has been set.

Edit 1: I've struck out some erroneous numbers above.  Here is a correction:  100 sends per second at 20 characters each is 2000
characters per second.  38400 bps of asynchronous data at 10 bits per transmitted byte is 3840 characters per second.  So the raw data rate should be fast enough that the buffer ordinarily doesn't overfill.

In the summary above, I suggested that the ISR store the current time and other relevant data in volatile variables and set a flag in a volatile variable.  That is, read millis() and store it, perhaps as follows:
// at file level ...
volatile unsigned long isrMillis;
volatile byte isrFlag;

// in ISR ...
  isrMillis = millis();
  isrFlag = true;

// in main loop ...
  unsigned long mlMillis;
  ...
  // when flag is true...
  cli();
  mlMillis = isrMillis;
  isrFlag = false;
  sei();
  // Now do stuff with mlMillis
  ...

However, looking at your ISR, perhaps it should go like the following instead:
// at file level ...
volatile float xf, yf, xfc, yfc;
volatile unsigned long t1, t2, tdelt;
volatile byte isrflag;

// in ISR ...
void myHandler(){
  tdelt = t2-t1;
  xfc = xf;
  yfc = yf;
  isrFlag = true;
}

// in main loop ...
  // when flag is true...
  isrFlag = false;
  // Now do stuff with tdelt, xfc, and yfc
  ...

Note that if an interrupt occurs while xf and yf are in the middle of being computed via your Kalman filter or whatever, the statements  xfc = xf; and   yfc = yf;   may pick up partially-stored results.  You can avoid that problem at least in part by protecting stores of t1, t2, xf, yf in the main loop:
  cli();
  xf = someXResult;
  yf = someYResult;
  t1 = someT1Result;
  t2 = someT2Result;
  sei();

In the above I've pointed out a few issues with races and concurrency and suggested technical solutions.  Those suggestions may be quite wide of the mark rather than appropriate.  In general I don't have a precise understanding of what you are trying to do with the software and don't know what redesign should be done to make it coherent.

As you said, I will set the timer for 10ms, and print stuff in loop() or another function. But my typical message is about 20 characters, which mean each time printing, it will take me ~5.2ms to print all. I'm wondering if I have to adjust the time setting for Timer or not? I want to be as close to 10ms as possible to match my sensor reading with another external reading.

@NguyễnThanhVũ, see edit