The root problem is that you send each several ms new key event and on receiver each time you get this event, you call Keyboard.press and right away Keyboard.release. So, it behaves as several key press-releases.
At sender side you should send 2 types of events:

Key pressed (and which button)
Key released (and which button)

At receiver side you should

When you receive "press" event, call Keyboard.press, and don't call Keyboard.release
When you receive "release" event, call Keyboard.release

Edit: I've made changes to your source code, please, try it
Transfer
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7);
RF24Network network(radio);

const uint16_t this_node = 03;
const uint16_t other_node = 00;

unsigned int laser_state=0;
const unsigned long interval = 5;
unsigned long last_sent;

unsigned int b1=1;
unsigned int b2=1;
unsigned int b3=1;
unsigned int b4=1;

unsigned int d1=10;
unsigned int d2=11;
unsigned int d3=12;
unsigned int d4=13;

//TR1
int btn1 = 3;
int btn2 = 4;
int btn3 = 5;
int btn4 = 6;

void setup(void)
{
//  Serial.begin(9600);
  pinMode(btn1,INPUT_PULLUP);
  pinMode(btn2,INPUT_PULLUP);
  pinMode(btn3,INPUT_PULLUP);
  pinMode(btn4,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);
}

void loop(void){
  network.update();

  unsigned long now = millis();

  if (now - last_sent >= interval)
  {
    last_sent = now;

    auto newB1 = digitalRead(btn1);
    auto newB2 = digitalRead(btn2);
    auto newB3 = digitalRead(btn3);
    auto newB4 = digitalRead(btn4);

    unsigned int packet[2];

    if(newB1 != b1){
//      Serial.println("F1");
      packet[0] = d1;
      packet[1] = newB1;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    if(newB2 != b2){
//      Serial.println("F2");
      packet[0] = d2;
      packet[1] = newB2;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

     if(newB3 != b3){
//      Serial.println("Ctrl");
      packet[0] = d3;
      packet[1] = newB3;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    if(newB4 != b4){
//      Serial.println("Shift");
      packet[0] = d4;
      packet[1] = newB4;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    b1 = newB1;
    b2 = newB2;
    b3 = newB3;
    b4 = newB4;
  }
}

Receiver
#include <Keyboard.h>
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7); // (ce,cs)
RF24Network network(radio);

const uint16_t this_node = 00;
const uint16_t other_node = 03;

unsigned int laser_state=0;
const unsigned long my_interval = 500;
unsigned long last_sent;

void setup(void)
{
  Serial.begin(115200);
  pinMode(9,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);
}

void loop(void){
  digitalWrite(4,LOW);
  network.update();

  unsigned int income[2] = {0, 0};

  if ( network.available() ) {
    RF24NetworkHeader header;
    network.read(header,&income,sizeof(income));

    auto keyCode = income[0];
    auto keyPress = !income[1];

    if(keyCode == 10){
      Serial.println("f1");

      if (keyPress) {
        Keyboard.press(KEY_F1);
      } else {
        Keyboard.release(KEY_F1);
      }
    }

    if(keyCode == 11){
      Serial.println("f2");

      if (keyPress) {
        Keyboard.press(KEY_F2);
      } else {
        Keyboard.release(KEY_F2);
      }
    }

    if(keyCode == 12){
      Serial.println("ctrl");

      if (keyPress) {
        Keyboard.press(KEY_LEFT_CTRL);
      } else {
        Keyboard.release(KEY_LEFT_CTRL);
      }
    }

    if(keyCode == 13){
      Serial.println("shift");

      if (keyPress) {
        Keyboard.press(KEY_LEFT_SHIFT);
      } else {
        Keyboard.release(KEY_LEFT_SHIFT);
      }
    }

    keyCode = 0;
  }

  unsigned long now = millis();

  if ( now - last_sent >= my_interval  )
  {
//    Serial.print("pin ");
//    Serial.println(digitalRead(9));
    last_sent = now;
    laser_state = digitalRead(9);

    RF24NetworkHeader header(other_node);
    bool ok = network.write(header,&laser_state,sizeof(laser_state));
  }
}


Can I connect a remote control relay to a arduino uno board by disabling the remote control in the relay?

I don't like to work with mains, so I use those outlets and connect a 433MHz transmitter to the arduino to activate the outlets.

You'd have to check the frequency of the unit, and see if anyone have decoded the transmitted data package.

If that doesn't float you're boat, you could open up the unit, and remove/desolder the relay. Add a transistor, and flyback diode and you're done. Just be careful with mains power.


How to learn electronics/programming with Arduino?

There are two main topics there: Digital Electronics, and C++ programming, and the Arduino happens to bridge the gap between the two.

That's why it's hard to find tutorials in the style you want.  So instead of looking for Arduino tutorials that do what you want you need to split the topics apart and deal with them separately.

Search for C++ programming tutorials. That should help you understand the structure and syntax of a program better. Search for digital electronics tutorials. Good keywords are things like logic gates, combinational logic or digital interfacing and just digital electronics. That should help you understand things like logic levels, logical functions, inputs and outputs, and such like.

Once you have basic understanding in both fields you can begin to see how the two relate together. One of the most important skills any engineer has is understanding and interpreting datasheets. From datasheets you can find how the hardware operates and what you would need your program to do to make the hardware do what you want.


Scope error in arduino PinChangeInt library

You have a typo:

PCintPort::attachInterrupt(SensorPin,blipCount,FALLING);

Should be:

PCintPort::attachInterrupt(SensorPin,blipcount,FALLING);
                                         ^

Note the lower-case "c".


Writing First Library - Serial Stream Object

Here is a simple example (built and tested with a mega2560), with a class that can be passed a Stream object, and sends a Hello over this generic stream object. When constructing the object, you can pass the Stream object you want to actually communicate:

#include "Arduino.h"

class MyProtocol
{
public:
    MyProtocol(Stream& s):serial(s){}
    void send(){
        serial.println("Hello");
    }
private:
    Stream& serial;
};

MyProtocol p(Serial);

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

void loop() {
    delay(1000);
    p.send();
}

NOTE: The serial.println() is not the Serial global object, note the lower case, it is the internal Stream class variable.

If you are confused with the OO and classes, take into account (while you gain more knowledge about it) that this approach can be also used with a simple function, you can pass the serial parameter. Furthermore, it is not necessary to hardwire the Serial interface for ever, you can in fact switch in run time and use a different channel depending on some condition:

#include "Arduino.h"

void send(Stream& serial){
    serial.println("Hello");
}

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

void loop() {
    delay(1000);
    if(someCondition)
        send(Serial);
    else
        send(Serial1);
}


It looks like you're trying to implement polymorphism without implementing polymorphism.

What you have done is create three completely independent structures and assumed that they will all work together just because they are the same size, with similar names, and fields named the same. That's not the case. They are all completely separate.

Instead you want just one structure but to use it multiple times to create different variables:

// from ODriveArduino.h, but move *outside* the class
struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
};

// in your code
struct motor_Params left_params = {
    1, 2.5f/10000.0f, 40.0f, 0.0f/10000.0f
};

struct motor_Params right_params = {
    0, 2.75f/10000.0f, 40.0f, 0.0f/10000.0f
};

// later
  odrive.SetParam(left_params);


I am currently experimenting with this module: http://www.uctronics.com/mega-pixel-camera-module-mt9d111-jpeg-out-p-227l.html

I2C connection and supplies are working fine with an Arduino Uno, but getting the image data with an Arduino might be not possible.
You can slow down the Pixel Clock of this module to 375kHz, bit I think the  GPIO read-out speed (at least with the standard digitalRead functions) and memory of the Arduino are not sufficient...


Instead of thinking of the PID output as pid_speed, think of it as motor_power, and what the PI controller is doing is translating errors in rpm into a motor power setting.

You are probably getting oscillation because of integral windup.  If your loop is fast relative to your system, each loop worth of error adds to integrator quickly/quicker than the system can adjust.   For example, if a loop takes 1ms, an error of 100rpm could overflow the "int integrator" past 32768 in only 0.327 seconds, and past the threshold where the integrator could peg the output 25500 (=255/Ki) in only 0.255sec  If the integrator is faster than the system, it can easily cause overshoot.  You might consider slowing the loop down to 10ms, 100ms or 1000s to match the physical process and make the kI term be a sane conversion of the integrator's rpmErrorseconds/100, rpmErrorseconds/10, or rpmError*seconds into output power.

To handle the numerics and constraints better, like overflowing integrators and negative output values, it would probably be best to use the Arduino PID library from http://playground.arduino.cc/Code/PIDLibrary as in Edgar Bonet's comment.


How to (optimally) fetch a button press?

You should use the millis function (see millis).

Create a variable of type unsigned long and check it against the current time, with some offset.

See also the debouncing example, how to use this function and maybe you want to implement the debouncing too.


Will analog servo work with Arduino servo library?

Jitter can be caused by a lack of power, in which case it will be an irregular pattern that leaves the servo in the wrong place or it can be caused by the increment commands not being sent to the servo smoothly enough.

Have you got enough power for the servo? Where is the power coming from, does this output match the datasheet?

This analog servo requires PWM, so is pin 3 of you board PWM capable?

How fast does you servo rotate?  At the moment you are saying 1degree every 15ms, I suspect that is too slow and that's why the arm is coming to a stop and then rotating again which is making it jitter.


Attempts with Sainsmart Motor Shield Not Working

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


How to declare char array[] using integers?

I think you are getting something wrong about shiftOut(). It will transfer exactly 1 byte (or 1 char). It does not take an array as parameter. I guess you want to write the 8 bits, that you are defining with your ints, as one byte out. Defining at byte directly would look like this:
byte information = 0b00101100;

The 0b tells the compiler, that the following number is encoded in binary. So you have one single byte, that contains all your information (all the bits). Then you can do
shiftOut(data_pin, clock_pin, MSBFIRST, information);

(Please note, that the data_pin and the clock pin need to be different).
If you want to print the information variable to Serial, showing the binary representation, you can use the corresponding parameter of the print() function.
Serial.print(information, BIN);

Will print the binary representation (zeros and ones as text) of the variable. So, to get "B1011001", you would do:
Serial.print("B");
Serial.println(information, BIN);

Note, that the print()/println() function will remove all leading zeros.

How to put the information byte with your ints? Each of them is either zero or one and represents one bit. So you can use the bitwise operators to put them together:
information = (a << 7) | (b << 6) | (c << 5) | (d << 4) | (e << 3) | (f << 2) | (g << 1) | h;

For each int only the first (Least significant) bit is important, since the others are always zero (because the int can be only one or zero). So we shift the int value to the left by the number of the corresponding bit minus 1 (so shifting a 7 places to the left to put its least significant bit to the most significant bit of information. We are doing that for all our int values. Then we put them all together into one byte by using the | (bitwise OR) operator.
Note: We don't know, where these ints are coming from. Even when stating, that you absolutely need those ints, you could organize them in an array instead of single variables. That would look like this:
int int_data[8] = {0, 0, 1, 0, 1, 1, 0, 0};
...
// in a function (like loop() or setup())
byte information = 0;
for(int i=0;i<8;i++) information |= int_data[7-i] << i;

It's up to you, if you want to do that.


Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee

The xbee network and the wifi network are both wireless networks, but, they do not communicate with each other.

You have two options.

Attach a second XBEE to your computer using one of these
https://www.sparkfun.com/products/11812
Get a WIFI shield http://arduino.cc/en/Main/ArduinoWiFiShield


How to connect a SilentStepStick TMC2130 stepper driver?

Answer: (from Electrical Engineering), yes both grounds must be connected.

In this example, +5V and GND from the arduino would connect to the two top left pins in the diagram (Vio & GND).

The two 24v power lines would connect to the bottom left two pins, Vm & GND


No ttyACM0 with Pro Micro on Ubuntu 18.04

A Pro Micro will only give a /dev/ttyACMx device node if the firmware installed on it creates a CDC/ACM interface.  That device obviously is running custom firmware which only provides the interfaces that the manufacturer wants to provide - in this case keyboard and mouse interfaces.

To use it as an Arduino you will first have to install the Arduino bootloader. That will then remove the existing manufacturer firmware, and you will have to write your own to make it act as a keyboard again.


usart sketch uploaded using makefile gives unusual behaviour

The -mmcu=atmega328p compiler flag is needed not only for the compile
phase, but also for the link phase. Otherwise the linker will not know
which CRT (C run time) to link with your program, and it will link none.
The CRT is responsible for things like initializing the stack pointer,
clearing r1 (as required by the AVR calling convention) and calling
your main().

Edit: the following simplified Makefile should work if you have a
modern version of avrdude that understands ELF files:

CC     = avr-gcc
MCU    = atmega328p
CFLAGS = -Os -DF_CPU=16000000UL -mmcu=${MCU}
PORT   = /dev/ttyACM0

led.elf: led.c
    ${CC} ${CFLAGS} $< -o $@

install: led.elf
    avrdude -c arduino -p ${MCU} -P ${PORT} -b 115200 -U $<

Otherwise you can keep your rules for led.elf → led.hex → install.


Problem 1

seconds = seconds ++;   //adds a second to the counter

This command grabs the value of seconds, increments the value of seconds, and then assigns the previously grabbed value to seconds. Or rather, it does nothing to change the value of seconds.

This mistake is repeated for minutes, hours, and displayHours in the clockConversion() function.

Instead

seconds++;

That was the main problem. The other problems described below are just for efficiency.

Problem 2

void loop()   //runs code repeatedly
{
  updateSeconds();   //runs the updateSeconds function
  clockShown();   //runs the clockShown function
  clockConversion();    //runs the clockConversion function
}

Why would you display the clock with clockShown() before you run clockConversion() to nice-up the minute and hour carry-over? Since you are running both clockShown() and clockConversion() at a high frequency, it doesn't matter much, but from a program flow point of view, I think it makes more sense to do the conversion before you display the values.

Problem 3

You are only updating seconds every 1000 milliseconds, using the millis() function. This is good.

However, nothing at all changes during the 1000 milliseconds between the incrementing of seconds. Why not pull the millis() parts into loop() and call all 3 functions only once per second?

void loop()   //runs code repeatedly
{
  unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
  if (currentMillis - previousMillis >= waittime)
  {
    previousMillis = currentMillis; //updates the last time seconds was updated

    updateSeconds();   //runs the updateSeconds function
    clockConversion();    //runs the clockConversion function
    clockShown();   //runs the clockShown function
  }
}


First, panels that you can use...

There are a few at Adafruit (here, here or here)

You just want to check that the barrel jack and plug are the same size.  I couldn't find dimensions in the documentation for the energy shield so you may need to dig a little deeper or just swap it for one that you know will work.

Also, the question about how long it will take also depends.  First, if we assume that the arduino is not running we can get ~500mA from the second solar panel listed.  If we can get all of that into the battery, it would take (1200mAH/500mA) about 2.4 hours to fully charge the battery.  It looks like you have to make some adjustments on the shield to get the most out of your solar panel.  And of course, you'll want to adjust those calculations based on the panel that you end up getting.

Now, if we assume the Arduino is running and consuming about 25mA you will have to subtract that 25mA from the 500mA that the solar panel is providing.  So, in general...

**

  (Battery Capacity)/(Solar Panel Current - Arduino Current) = Charge
  Time.

**

And you have a lot of control over the solar panel current and the arduino current based on the exact arduino that you use, etc, etc.

There is also probably some loss regulating the solar panel voltage from 5-6V down to charge the battery (which is probably at 3.7V). I also don't know if the charging circuitry will limit the amount of current going to the battery.

Take Away: There's a lot of stuff to consider when trying to answer this question.  I think your best bet would be to get a panel that fits and dump the fuel gauge values out to the console every few minutes.


restart counter of elapsed millis willingly with read

Thanks for the help, this code is closer to what I was looking for. This is for a water level pump, when the trigger is high it turns on, when the water rises the trigger goes low and stays on during the timer as a failsafe and then turns off with when the elapsed time is greater than the set time and also not in my code it turns off with a additional trigger. Here is my working code.

unsigned long induceTime = 0;
unsigned long elapseTime;
long setTime = 10000;
int openClose;
int openClosePin = 2;
int writeToPin = 3;
void setup() {
Serial.begin(9600);
}

void loop() {
  int openClose = digitalRead(openClosePin);
  elapseTime = millis();
  if (openClose == HIGH){                //reset count
    induceTime = millis();
    digitalWrite(writeToPin, HIGH);
    Serial.println(induceTime);
}
  if (openClose == LOW){
    elapseTime = millis() - induceTime;  //induceTime is set when leave high
    if (elapseTime < setTime){
      digitalWrite(writeToPin, HIGH);
      Serial.println(elapseTime);
      Serial.println("within setTime high");
}
    if (elapseTime > setTime){
      digitalWrite(writeToPin, LOW);
      Serial.println(elapseTime);
      Serial.println("within setTime for low");
}
    Serial.println(' ');
    Serial.println(elapseTime);
    Serial.println(' ');
    Serial.println(induceTime);
    Serial.println(' ');
}
delay(1000);                              //so that I can see serial monitor
}


What's the smallest (cheap) USB Host solution for Arduino?

The Arduino Due and Arduino Mega ADK can both serve as a USB Host. You can also use the chip that the Mega uses yourself


Read only selected Packet SoftwareSerial

Your reading methodology is flawed from the start and you need to completely change how you do things.  First off, you wait until there is at least one byte in the incoming buffer, then if that byte is 0x01 you then try and read 5 more bytes - even if there is only (say) 2 bytes in the buffer.

Instead you need to set up a sliding window for receiving the data. A sliding window is basically an array that is the same size as the data you are receiving, and as bytes become available they work their way down from the "top" to the "bottom" of the array. When the contents of the array match a certain pattern you know it is a "good" packet and you can use the data form it.

For example, you may have something like:

uint8_t window[8];

void loop() {
    if (RS485Serial.available()) {
        uint8_t b = RS485Serial.read();
        // Slide the contents of the array down
        for (uint8_t i = 0; i < 7; i++) {
            window[i] = window[i+1];
        }
        // Insert at the top
        window[7] = b;

        // If the array starts with 0x01,0x03,0x40,0x34...
        if ((window[0] == 0x01) && (window[1] == 0x03) &&
            (window[2] == 0x40) && (window[3] == 0x34)) {
            // Do something with window[4] and window[5]
        }
    }
}

You could also add checking the CRC to that by comparing the calculated CRC for the incoming packet (however that is done in this protocol) with the last two bytes of the array.


Try to connect your module with the power supply useing wires as short as are is possible. I was fight with this module for few months and now I know that almost all of issue with it are regarding power supply.
For short test you can connect module directly to LiPo 3,7V.
You have to be sure that your power supplay can handle 2A current. The voltage never can drop below 3,4V.

The power IC and the bypass capacitor should be placed to the module
as close as possible.

SimCom, SIM800_Hardware Design_V1.09, available 27.11.2020


If you had it working and it has changed, I would suggest trying a few changes to track down the issue. The schematic seems OK so assuming that all connections are sound, I would look towards proving the code. Maybe try a simple pure Arduino sketch designed for the 74HC595N and see if the results are the same. If not, the culprit is almost certainly Johnny Five.

Perhaps try this sketch which should work with your schematic (remap the I/O though to your 2,3,4 configuration). If the problem persists, throughly examine your connections because there is very little else which would prevent it from working - especially given that it did work a few days ago. Also, have you got another Leonardo to test with?

Finally, the schematic for the Arduino-only example shows a cap on the latch line - presumably for debouncing - which is missing from your schematic. I don't think you've damaged your registers but I wouldn't rule it out.


possible to preform VIO from two cameras/imu's on a dual-core esp32?

I haven't worked with the ESP-32, but it seems to me you're quibbling over pennies. Pis are cheap and very powerful. They run Linux, so there are tons of open source libraries available for them. You could install OpenCV, for example, and do computer vision quite readily.

I'd recommend at least a PI 3.

If you used an ESP-32 based system, would you run it as an Android device? Android's "OS" (And that the term OS is quite a stretch) is really just a setup function and a run loop. You should use a device with a real OS, including a file system, etc.


Arduino DC motor causes disturbance. What can cause it?

Thanks for the help everyone. I fixed it by using Capacitors. They suppress the noise that the dc motor produces. I found my information  here


That appears to be a 12 "solid state" relay. That means that it is designed to be both powered by and switched by 12V. You're trying to drive it with slightly more than 1/3 of its rated voltage. Don't do that.
Edit:
Note that none of the relays being discussed are true solid state relays. These are are all conventional coil relays that include cicuitry that allows them to be driven by CMOS logic signals. A true solid state relay does not have any moving parts, but uses solid state components to do the job of a relay. Those cost significantly more money however.)

It might be that you can get away with driving a 5V solid state relay with 3.3V, or 12V relay with 5V, but you shouldn't do those things either.
Also note that even if you are using the correct relay, your relay almost certainly takes more current than the 5V pin on an Arduino can provide (When driven from USB, the entire system is limited to 500 mA, including the power needed to the Arduino.)
Edit:
These solid state relays come in 12V, 5V, and 3V flavors. Get a 3V one: https://www.adafruit.com/product/3191?gclid=EAIaIQobChMIyY_dxM344gIVELbICh1ufwivEAQYBSABEgI3wPD_BwE


Processing printing sensor readings and raising NaN exception at the same time

//convert to an int and map to the screen height
sensorValue = float(inString);

You can't convert a String to a Float just like that by casting.  You have to interpret the characters within the String.  Oh, and a float isn't an integer.

All you're doing there is trying to cast the address of the String object to a float, which it really doesn't like, hence you get NaN.

Try:

int sensorValue;
sensorValue = inString.toInt();


Thanks to @Juraj, I fixed the problem. Deleted those files by manually formatting the SD card.

This is not really the answer, you can see the answer in this comment under the question.


How to get the firmware (hex) file from a .ino file containing the code

You are asking how to locate the compiled hex file. It's easy! Follow these steps:

In the Arduino IDE select Sketch > Export Compiled Binary. This performs a compile. Once complete, this command places a copy of the compiled .hex file into the directory of your sketch.

Then either browse to the sketch folder or in the IDE select Sketch > Show Sketch Folder.

This generates two hex files for the target micro-controller; one with the bootloader and one without the bootloader. These hex files can be uploaded to the micro-controller using a programmer such as the Atmel Ice or AVRISPmkII.


How to save a state - make an arduino run a code only once/make aruduino bahave differently the next time he is on

As one of the comments said, you will need to use the EEPROM library. When you save a variable in your code (e.g. int test = 10;) the variable along with its value gets stored in the RAM. The EEPROM is a piece of harddisk on your arduino that will remember its value when you power off your arduino.
If you implement a power-off button, simply save the state (or in your case, the wheel size) in EEPROM whenever the user inputs it. The next time you power up, you can check if there is a previous value in EEPROM and continue with that value if it exists. Otherwise ask the user for their wheel size.
You might want to implement a reset-button as well, to reset whenever you change bike or wheels. Look up a code example of EEPROM, as there are a lot online.


Can't store time over 9 hours and 10 minutes

Here's a hint: 32767 seconds is 9 hours, 6 minutes and 7 seconds.

What is the largest value that an int can hold?

EDIT: I can't add comments on this computer (old browser), so I have to respond to your question here.
time_t is an unsigned 32-bit value, but all of your input values are signed 16-bit values. When you take a product like 3600*10, you get a bit pattern of 1000110010100000, which is 36000 when interpreted as an unsigned value, but is -29536 when interpreted as a signed value.

When assigned to a time_t, the value is sign-extended to 32 bits, which makes it 11111111111111111000110010100000, which is 4294937760 when interpreted as an unsigned value.

If you want to write a statement like

time_t x = (hoursSet * 3600) + (minutesSet * 60);

you need to type-cast your input arguments to the correct type first:

time_t x = ((time_t)hoursSet * 3600) + ((time_t)minutesSet * 60);


Your whole question is not very clear, so I will mainly give you explanations, of how the Timer code works (since you don't seem to understand that) and give hints.
Let's look at ir_start(), where you configure Timer1 for the IR operation:
void ir_start()
{
  DDRB |= 10;
  ICR1 = 416;
  OCR1A = 104;
  TCCR1A = 2;
  TCCR1B = 24;
  TIMSK1 = 1;
  ir_on();
  TCCR1B |= 1;
}

First you should better not use the decimal representation of numbers here. Most of them consist of single or few bits, that a bound to a specific configuration option. You can better see, what is going on, when you use hex or better binary. So instead of DDRB |= 10; you would write DDRB |= 0b1010; (0b marking the binary representation, and 1010 being the binary representation of 10). That makes it easier to read by others or by you, when you leave that code for a time and come back to it. Using decimal is good in the cases, where you write registers, that represent a single value (like ICR1).
Now let's go through each line. Here I will only state, what the line does, not if that makes sense or if it is correct.
DDRB |= 10;

is equal to DDRB |= 0b1010 and will set will configure PB1 and PB3 (pin 9 and 11 on the Uno) as output pins.
ICR1 = 416;

sets the input capture register 1, which - when not in input capture mode - sets the TOP value of the Timer, meaning the max value, to which it will count until overflow.
OCR1A = 104;

sets the timer value, where the Timer will toggle the output compare pin A of Timer1 (PB1, aka pin 9) (of course only, if the output compare mode is activated).
TCCR1A = 2;

is equivalent to TCCR1A = 0b00000010. It disables the output compare mode, thus normal port operation. Also bit WGM11 is set to 1 and WGM10 is set to 0 (explanation with the next line).
TCCR1B = 24;

is equal to TCCR1B = 0b00011000. It sets WGM12 and WGM13 to one. Together with the other bits of the last line, this sets the Timer mode to FastPWM, counting to the value in ICR1, resetting there. Also the clock source bits are all set to zero, so disabling the Timer.
TIMSK1 = 1;

This enables the Timer1 overflow interrupt, and is of course equal to TIMSK1 = 0b1.
In ir_on() you use
TCCR1A |= 192;

which is equal to TCCR1A |= 0b11000000. It enables the output compare for OC1A, configured for setting it at the compare match and clearing it on resetting (also called inverted mode).
TCCR1B |= 1;

will set the clock source of the Timer to the main clock without any prescaler. A prescaler would scale the counter values. For example with a prescaler of 8 (setting the clock source bits to 0b010) would mean, that the Timer value would increment by one every 8 clock transitions, instead of on every transition. Here you have no prescaler, so the Timer runs with full speed. You can make it slower by changing the prescaler. The fine tuning can then be done by changing the ICR1 value, which is used as TOP. Setting the clock source will also turn the Timer on.
Then in ir_off() you use
TCCR1A &= -193;

Decimal -193 is a value, that needs 2 bytes as a signed integer (twos-complement). It's binary value is 0b11111111 00111111. You assign to a 1 byte register, so the high byte will be cut off. So you actually use the decimal value 63. It will disable the output compare for OC1A, so disabling the PWM output on the OC1A pin.
So, to sum up the actual function of that code: The Timer is configured to run from 0 to 416 without any prescaler. At the value 104 the OC1A pin is set, on timer reset/overflow it is reset. The frequency of the signal will be 16MHz / 416 = 38,5 kHz, with a duty cycle of (416 - 104) / 416 = 75%.
By changing ICR1 and OCR1A, you can go down to 16MHz / 65535 = 244Hz. So for a frequency of 500Hz, you could use the ICR1 value 32000. For the same duty cycle you then need the OCR1A value of 8000.
If you need an even lower frequency, you could use the prescaler by setting the clock source bits correspondingly.
Note: You use the timer overflow as your smallest time measure (since you are incrementing sent_array_numbers in the ISR). So by changing the Timer frequency, you also change the amount of time, that one increment of sent_array_numbers represents. While this time is 1 / 38.5kHz = 26.3us with 38.5kHz, it will be 1 / 500Hz = 2ms for 500Hz. Just keep that fact in mind, when writing the IR pulse values into the array.
You can read about all this in the datasheet of the Atmega328p, which is used in the Arduino Uno.

Notes besides the Timer configuration:

Make sure, that all variables, that get changed inside of an ISR, are declared as volatile, so that the compiler knows, that the variable can change at any time and that it cannot optimize the access to it.

Make sure, that the index, that you use with the array, is not exceeding the size of the array. Otherwise you will read from whatever was placed behind that array in the memory.

Every variable should have a fitting speaking name, which tells exactly, what it is. Its function might not be that obvious, when you look at your code after a few years.

The first 4 values in the array with the IR codes are not used. From your code I cannot understand, why. (Though you suggested, that this is not the complete code).

I hope, that helps. If not, then you need to be more precise with your question. And provide a complete compilable minimal example code.


How to measure relay current draw from Arduino

Have you noticed how the 5V current is, give or take a little inaccuracy on the part of your ammeter, the sum of the other two currents?

Without knowing what relay you are talking about, my guess is it is one of the SainSmart 5V relay modules with opto-coupler. Those, by default, use a common 5V input and split it between the opto-coupler (and then into your digital pin to be sunk through ground) and the relay to ground.  Therefore the 70mA is split between 66mA through the relay and 4mA through the digital IO pin.

So the correct place to measure the total current in this instance is the 5V pin since that is the common point for the circuit.

In answer to your second question, read the datasheet.  It quite clearly states:

  Although each I/O port can sink more than the test conditions (20 mA at VCC = 5V, 10 mA at V CC = 3V) under steady state conditions (non-transient), the following must be observed:

  ATmega48PA/88PA/168PA/328P:

  The sum of all I OL , for ports C0 - C5, ADC7, ADC6 should not exceed 100 mA.
  The sum of all I OL , for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100 mA.
  The sum of all I OL , for ports D0 - D4, RESET should not exceed 100 mA.

  If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.

And also a similar note for sourcing current.

So although they can sink or source more than 20mA, and theoretically up to 40mA, anything more than 20mA is not guaranteed and should be avoided.

Basically overcurrents cause increased heat dissipation in the MOSFETs which causes the internals to break down.  Hence the note about under steady state conditions.

So sourcing or sinking more than 20mA for longer than a few ms is asking for trouble. More than 40mA is just being irresponsible.

Furthermore, the MOSFETs in the IO pins act like resistors when turned on.  As you should know, according to Ohm's Law, the voltage across a resistor is proportional to the current through the resistor.  Increase the current and you increase the voltage across the resistor.  Since that resistance is in series with your circuit that voltage gets subtracted from your available voltage on the IO pin - so drawing too much current will cause the voltage to drop (or rise for sinking) below (above) the specifications for the logic voltage for that IO pin.  So not only do you risk damage to the IO pin and other parts of the chip through overheating, but you also then operate outside the specifications for the logic levels which can cause things that you are communicating with to not work right.


While you can create your own libraries for the Arduino, a simple way to make reusable code is to create a header (.h) file that contains the code you would like to make reusable.

Specifically, in the Arduino IDE create a new tab with some name foo.h, and in your main tab, add #include "foo.h" at the top of your code. What this does is essentially copy paste the code from foo.h into your code during the build process. While simple in execution, it really helps organize more complex code, and in your case, helps with reusing code.

You can alternativly use "Normal Arduino code files (no visible extension), C files (.c extension), C++ files (.cpp), or header files (.h)."

And one extra note to help you - the header files do not have access to some of the typical Arduino commands and functionality, such as delay() or Serial unless you add #include "Arduino.h". However, for IDE versions less than 1.0, use #include "WProgram.h". This will give you access to those functions.


Reliably reloading the calibration data of IMU BNO055

I found the solution. It is enough to add a function that when reperfoming the calibration of the magnetometer, checks ONLY if the magnetometer is calibrated (while the calibration for the accelerometer and gyroscope is reloaded from the EEPROM).

void performMagCal(void) {
  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;

  while (mag != 3) {

    bno.getCalibration(&system, &gyro, &accel, &mag);
    displayCalStatus();
    Serial.println("");
  }

  Serial.println("\nMagnetometer calibrated!");
}


If I try to pause my loop function my output screen starts printing trash

ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.

Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.

The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.

I would suggest adding a delay() or yield() to your while block will fix the problem.


The working of a MFRC522 and its Interface protocols?

Let's have a look at the datasheet of that chip:

Paragraph 8.1 says

  The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on this specific board the control pins are preconfigured for SPI. But, the supporting library only supports SPI so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK

what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

I think this is your board, and luckily they include a schematic on that page:

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.


Mac won't detect Serial Port for Leonardo

@IgnacioVazquez-Abrams's comment made me realize that the problem was the Micro USB cable I was using. It gave the Arduino 5V power from my computer, but didn't support any data connection. I'm buying a new cable.


What fixed the issue for me was to go to Boards manager on Arduino IDE and update to latest version:

Then I got the following error when compiling:

Board generic (platform esp8266, package esp8266) is unknown

In order to fix that, I followed these instructions.
And, I also removed rdm6300 library from C:\Program Files\Arduino\libraries and moved it in C:\Users\myusername\Documents\Arduino\libraries


Lots of things share pins. It's normal. The "how" is that those pins are connected, internally, to multiple bits of the circuitry.

The "why" is simply because if you had a discrete pin for each possible function you would end up with a chip the size of your desk.

Pretty much every single pin on the chip has multiple functions on it.


Difference between data type int and long on Arduino

On the Arduino (AVR models) an int is 16 bits, not 32 bits. Thus it goes from -32768 to +32767.

That is different from long which is 32 bits.


Changing PWM on Arduino Mega, pins 9 & 10 to 20 to 25 KHz

Fortunately, the timer for PWM on both pins 9 and 10 on the Arduino Mega (but not necessarily other boards) is timer 2, so changing the PWM frequency of one will change the PWM frequency of the other.

You should also check that changing the the timer frequency does not effect any other libraries (eg Servo, from memory typically uses timer 2).

The frequency for the timer is set by the TCCR2B register (bits CS22, CS21 and CS20) see p 185 of the datasheet for the Mega2560 IC http://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf

As far as code goes, try the following (just tested with a small speaker, appears to change to pitch as expected, but I don't have a motor to try it on:

Each line sets the frequency for timer2 (PWM 9 and 10), should be ok to do during setup, and settings will remain. Note that the first line is equivalent to normal default values:

  TCCR2B=(TCCR2B&248)|4;    //prescaler=64, f=977Hz

  TCCR2B=(TCCR2B&248)|3;    //prescaler=32, 1953Hz

  TCCR2B=(TCCR2B&248)|2;    //prescaler=8, 7812Hz

  TCCR2B=(TCCR2B&248)|1;    //prescaler=1 62500Hz

Also check that your motor driver can handle the frequency.


Where does the sound come from this board?

That looks like a piezo buzzer, the component that had the sticker on it. It's likely louder now, with the sticker removed.


How do I supply either (1) dual voltage or (2) negative voltage?

You can make -5 V if you use an external power source, like in the circuit below (untested).

Connect the GND (-) from the Arduino to the +5V from the External (5V) source, than 0V will be the GND (with respect to the Arduino), but the GND of the external source will be -5V with respect to the Arduino.

I only used the resistors to get no short circuits, you can replace it by your own circuit (connecting the 5V arrow to Vcc and the -5V arrow to Vee).

simulate this circuit – Schematic created using CircuitLab


The potentiometer and the internal resistance form a voltage divider. The voltage created by this voltage divider is essentially indistinguishable from 5V regardless of what the pot is set to because the internal resistance is so high.

What you want to do is to create an external voltage divider that will cause the voltage to vary full scale between 5V and 0V. You do so by connecting one end of the pot to 5V and the other end to 0V, and drawing the voltage from the wiper.


Any disadvantages on using Particle Photon over an Arduino?

Photon advantages:

The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.

A photon  about 1/4 the size of an Arduino UNO

Photon is much cheaper than arduinos

Arduino UNO advantages:

Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt

Arduino has many resources while Photons don't since Photons are fairly new

Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)

UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital

UNOs have female pins, so no breadboards are necessary for small, simple projects.
Photons have male pins, and they need to be plugged into a breadboard or soldered.

Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!


Arduino Mega Hall sensor interrupt for a speedometer

You either need to change your code to count the number of revolutions in the interrupt.  Then divide that value in your main loop by the elapsed time to get the angular velocity.  This may or may not work, as the number of revolutions may be small or even zero when you do the calculations.  Thus contributing to errors.

Or, change your code to record the elapsed time between rising edges in the interrupt.  Then find the inverse of this value.  This may be better as you could even miss an event in your main loop and still calculate the speed.  Careful not to take the inverse of zero.

To calculate speed you need to find the rotational speed of the wheel, and, consequently, how fast you are bicycling.  Use this equation:

...where omega is the revolutions per time as calculated by the 1st method above or reported by the interrupt routine in the 2nd method above.  Do not forget that the interrupt routine is probably using milliseconds and not seconds.

Also, do not forget to clear out the last value reported by the interrupt.  No matter which of the above 2 approaches you take.

Also consider special cases.  For instance, when you stop bicycling the interrupt will never fire.  In your main loop you may have a second counter which, when exceeded, indicates that your speed is zero.


That function is not obsolete. However, there is gratuitous use of it where it's not really needed.

The usage of the function that you alude to grew from the desire to make ATMega32U4-based boards (such as the Leonardo) which have a native USB interface act similar to the ATMega328P etc boards.

When you open the serial port on an Uno, for example, the main MCU is reset and the sketch runs from the start.  When you do the same on a Leonardo that doesn't happen. So by adding that code snippet to the beginning the sketch is paused until the serial port is opened.  This makes it appear that the board has been reset and the sketch is running afresh, like an Uno - but it isn't.

Placing that while loop at the start of your sketch without thinking about the consequences means that your sketch may never run. If a serial connection is required for your program then that's not such a problem. However, if all you're using the serial for is debugging, then as soon as you try and use your sketch without the computer opening the serial port it will fail.

So I would recommend not using that while loop unless you know that you want the effects that it provides.  That is, stalling the sketch until the serial port is opened by the computer.


Does serial communication between PC and Arduino has to be in a loop?

Just put a 10 µF capacitor between the 5v and RESET pins of your Arduino and do whatever you want, just make sure that the capacitor is connected after the board has been powered up, and also, remove the capacitor before uploading any code.


A simple DC motor would work. you have to pulse it in the right moment. for finding out the right moment and the pulse length (you don't want to push it so hard !) you need a simple accelerometer sensor to measure acceleration in specific axis.


No.

First, mmap() makes almost no sense on an AVR, as there's no memory management unit or concept of process memory to configure.  Some related concepts like sbrk() are occasionally implemented in a minimalist fashion to let library functions designed for larger computers work, but they typically only update a tracking variable or fail.  For things that are physically realizable you can write your own mmap() if you really want, either allowing (assigning) or disallowing a region, and even if you really want automatically copying part of a file off an SD card or whatever...

But more importantly, your actual goal is entirely unachievable, as the AVR is a strict Harvard Architecture which can only execute instructions from flash, never from RAM.

If you want to execute from RAM, try one of the various small ARM Cortex M0/M4/M3 platforms (many of which have Arduino ports), or even consider a larger Embedded Linux system, which will not necessarily be any more expensive than an Arduino.


In short, you don't.
The SoftwareSerial implementation for AVR doesn't have an outbound buffer at all.
It just turns the interrupts off during each character outbound and it sends them all immediately.
This means a call to SoftwareSerial's write simply will block until all of the data you've tried to send has in fact been sent.  If you can't afford to wait for your data to go out on the TX line now, then it's up to you to send it later when you can afford to wait.
SoftwareSerial has no flow control.  When you write(), the data is sent out on the TX pin regardless of whether anything is present on the other side of the connection.  And when present, the data is still transmitted regardless of whether other side considers itself "ready" to receive.  There's simply no feedback from the receiver to tell the sender to stop.  So SoftwareSerial itself will never block owing to these things.


How can I make YX5300 MP3 player play song in a loop?

I think you want to use the command [Single cycle play] which is 7E FF 06 08 00 00 01 EF (the 00 01 towards the end is the song number to play).

All the commands are detailed in the manual.


Serial connection two devices two power supplies

The 3.3V zener diodes are connected backwards. The anode should be connected to ground and the cathode (banded end) to the GPIO signal. Zener diodes work in reverse bias...as you have them connected now they are forward biased and will clamp the signals to about 0.7V.

The zener diode on the line for data transmitted at 3.3V to a 5V input doesn't do any good. You need to increase that signal voltage to a proper 5V logic level. The best thing to do would be to get rid of the zener diodes altogether and use a proper logic level converter.

Also, you really should have resistors between GPIO output pins and the zener diodes, to limit the current through the zeners when the GPIO pin is at 5V.


Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808

I'm interpreting your phrase “even without using delay logic, i couldn't get signal time period as comparable to 50 Hz” as meaning that the code shown runs Too Slow.  At 1000 samples per cycle and 50 Hz on an 8-bit 16-MHz processor, you only have 320 clocks to compute a sin(), which probably is not enough to compute a 32-bit floating sin().

To speed it up, you can either issue fewer samples per cycle or make the loop go faster.

For the “fewer samples per cycle” approach, you would make increment bigger; for example, instead of 3.14159/500, or 1000 samples per cycle, perhaps an interval of 2π/500, or 500 samples per cycle.

For the “make the loop go faster” approach, you could use a lookup table or fixed-point integer arithmetic or both.  Note, the lookup table only needs to cover 90° (or π/2 radians); index in reverse for quadrants 2 and 4, and negate values for quadrants 3 and 4.

Note, after you speed up the code, you will need to set up a time base for issuing samples.  This could use a clock-based interrupt routine that gets and issues the next array value, or that sets a flag so your main loop can get and issue a value.  Or you could spin until micros() exceeds a deadline, at which time you (1) issue a value, (2) set the next deadline, and (3) compute the next value.


You can absolutely use GPIO0 as an output. The ESP will read the state of GPIO0 once at boot (And never again thereafter) to determine what boot mode to enter. During this time it is an input, so, whatever you hook GPIO0 up to must not hold this pin low (Unless you want to enter bootloader mode, of course), at least until the chip boots. As long as you satisfy this condition, you can use the pin for anything else. On my board for example, I use it to drive a simple status LED, and have never seen any issue from it.


Communicating with Arduino Mega 2560 Serial ports through x2 RS232

Your main problem seems to be confused by all the information. I will give you some more.

The Arduino speaks UART (Universal Asynchronous Receiver Transmitter) with it's Serial interfaces (there are 4 of these on the Mega). This is partly the same protocol as RS232, but it uses TTL logic levels (in this case the levels 5V and 0V), while RS232 has different voltage levels and more lines (like control lines). When you connect your Arduino to a PC, the PC is not directly talking to the Arduinos chip (here the Atmega2560). Instead every Arduino with a USB port has an extra chip. It will handle the (very complex) USB communication, so that you can see an emulated COM port on your PC. The data, that the PC sends to that COM port, get's transmitted over USB to that extra chip, which in turn will convert it to UART signals and send them to the Atmega2560.

All Arduinos, that I know of, have only 1 USB-to-UART chip. But you can add your own USB-to-UART chip to one of the other Serial interfaces. You can use a FTDI chip, an Atmega16U2 or (if you don't want to program an extra chip) simply an USB-to-UART converter cable/module, which you can buy and use directly by just connecting their pins to the Arduinos Serial pins.

By the way, it doesn't really matter here, if you use USB3.0 ports, since chips this small cannot work with speeds that high. All these chips use USB2, more is not necessary, they aren't fast enough.


You need to install package openssh-client: it's available in the package list. See this tutorial about how to install optional packages.

You can call ssh on the Linux side using Process from the Bridge Arduino library.
Best is when you execute single or grouped commands using a syntax as:

ssh user@your_other_host 'echo 1; echo 2'

Managing an open ssh session is possible but I think may be troublesome, so avoid it if you can.


By "UTP", I'm assuming you're referring to Unshielded Twisted Pair. The shielding and twisting aren't really relevant, because they're just physical characteristics of the cable itself. They don't have any bearing on the sender or receiver.

The salient point about UTP is that it uses differential transmission. That is, the data is sent down two wires at the same time, but one is inverted. The receiver uses the difference between the two signals to reconstruct the original data, eliminating any interference which may have been introduced en route.

Assuming the voltage level is safe (0-5v for most boards), you could connect each wire directly to an analog pin on the Arduino. If you read both continuously, and apply suitable thresholds/triggers in software to identify level changes, you could probably reconstruct the original signal.

It's definitely not ideal though, as ADCs are comparatively slow, and you would never be able to read both at exactly the same time. That means the transmission would have to be quite slow in order to work. The exact speed would depend on how quickly your program could poll the ADCs and process the result.

It would be much better to use some external circuitry to handle the differential signal. It could then produce a nice clean digital output which you could feed directly to any input on the Arduino. It should be able to run a lot faster, and leave your program free to do other things. Any good electronics vendor will stock a variety of ICs which would do the job, depending on your exact requirements.

Setting up your computer/laptop as a sender is a totally separate issue though. Many different ports use differential signals in some form, including ethernet, USB, and RS-232 (old DE-9 serial ports). Unfortunately, it would be very difficult to get direct control of their signal lines. You would almost certainly have to write your own device drivers, which is a pretty huge undertaking.

If you want to send serial data from your computer to an Arduino, the easiest way is just USB-to-TTL conversion. Most Arduino boards have this built-in, connected directly to the hardware serial lines on the microcontroller (which is how you upload programs/sketches). Alternatively, you can get external cables which do the conversion, and you can connect it manually to other pins, processing it using software serial.


Communication between Arduino Uno and Mega

You can multiplex the trigger line. With 3 pins you can address up to 8 sensors. If you multiplex the reply line as well (so you can abstract out the latency) you only need 2 additional pins for the actual trigger and reply.


In the past I used the LM2917 for this purpose:

http://www.ti.com/lit/ds/symlink/lm2907-n.pdf

That IC is a frequency to voltage converter, so it perfectly suits your need. According to some quick calculations I made it can go to some tens of kHz, so if your signal is up to 1kHz it should be fine.

Now, this is the answer to your question. But... You can easily read the frequency directly with the arduino... If your purpose was to read the frequency, I suggest you to read something about the X-Y problem


In your “Loop to determin the arrangement”, you are erroneously using
time[i] in several places where you mean tempTime. Also, to update
tempTime you only have to subtract steps[j]. With these fixes, your
loop becomes:

for(int j = 3; j >= 0; j--){//Loop to determin the arrangement
  if(tempTime/steps[j] >= 1 && steps[j] > 0 && digitPins[i][j] > 0){
    Serial.print("\n");
    Serial.print(tempTime);
    Serial.print("/");
    Serial.print(steps[j]);
    Serial.print(" = ");
    Serial.print(tempTime/steps[j]);
    tempTime = tempTime - steps[j];
    displayer[counter1] = digitPins[i][j];
    Serial.print("\r\nAdded: ");
    Serial.print(digitPins[i][j]);
    counter1++;
  }
}

Now, if you learn a little bit about how binary numbers work, and about
the binary operators in C and C++, you can rewrite your loop in a
simpler form:

for (int j = 3; j >= 0; j--) {
  int weight = 1 << j;      // 2 raised to the power j
  if (tempTime & weight) {  // if bit j of tempTime is set
    displayer[counter1++] = digitPins[i][j];
    Serial.print("Added bit ");
    Serial.print(j);
    Serial.print(", weight ");
    Serial.print(weight);
    Serial.print(", output ");
    Serial.println(digitPins[i][j]);
  }
}

As a side note, it is considered good practice to print a new line at
the end of each string you print (using println()), rather than at
the beginning.

Edit: As your display() function is way too complex for what it
does, I did not resist the temptation to simplify it:

void display() {
  for (int i = 0; i < 4; i++)
    for (int j = 0; j < 4 && digitPins[i][j] >= 0; j++)
      digitalWrite(digitPins[i][j], time[i] & (1<<j));
}


Can I use a spare Darlington Pair on my ULN2003A to drive a DC motor?

Should work just fine. But you'd have to connect the motor to the positive rail, and since the ULN2003 can only sink current.

Normally when connecting a motor, you'd add a flyback diode. But the ULN2003 already has those inside the chip.

PWM is the easiest way to (somewhat) control the speed of a DC motor.


Shield interfere with Serial Communication

You really do need to provide information on the shield, there are many versions out there (and I own half of them ).

In essence, unless you are using an alternate serial port (SerialN) or software serial, then YES, your XBee will be using the same lines as your Arduino. If you are using Serial.print or Serial.write to talk to the XBee, then that is a giveaway too.

The reason for this is the XBee talks to your Arduino through the serial port, but the Arduino IDE also talks to your Arduino (for programming and Serial.print) as well. You can only do one successfully.

In answer to your second question, most likely not. It will be the XBee shield causing you your problems.

edit: I thought I would add, I actually have ONE shield that uses RX and TX but also allows for programming at the same time. This is achieved through a series resistor and (in the case of the shield) an amplifier as well.


Timekeeping isn't exact with any of the boards, though .05% - just over 7 minutes/day - doesn't sound like too high an expectation.

Restarting when you connect it to your computer is by design and doesn't indicate a fault. Opening the IDE's terminal or connecting another terminal program to a connected and running Arduino will - and is supposed to - reset it. Here is a forum discussion on how to disable the auto-reset function (Uno-specific) if you want to. Note that it involves modifying the board.

It's quite possible that this one board has a fault, though it still could be the cable. A couple of swaps should confirm it one way or the other.

I'm still not clear on where the error message,

  ser_open(): can't open device "/dev/cu.usbmodem14201"

came from, but I'm guess it's from AVRdude, the uploader application on your Mac, and still I'm wondering if the correct port is selected in the IDE's Tools | Port menu? For some reason, a USB device called "cu.usbmodem14201" is expected but not found. Since neither the Mac nor the IDE inherently knows this name - a USB device announces its name when you connect it - could this selection be left over from having previously used the genuine Arduino? Another reason to check the Ports menu. Also note that the Ports menu doesn't update its list spontaneously - only when you open it (and maybe only when you open the top-level, Tools, menu; I don't remember exactly).

Update:

  The regular Arduino at 0.5% is pretty crude, I'd pay more for a more
  accurate crystal, but I was able to develop a sketch that adjusts for
  the Arduino's inaccuracy.

You could try putting the Arduino in an "oven" - and I emphasize the quotes. This is not a heating chamber per-se but a temperature controlled chamber. If you're getting good results by adjusting the count, adding the oven should get you even better results, especially as the seasons change and if that makes enough difference where you are.


Where is Arduino.h on a Mac? Can I download a copy if missing?

On a Mac the Arduino.h file is within the Arduino application itself. It's not that easy to get to without resorting to the command line.

You also need far more than just Arduino.h - you need the entirety of the Arduino AVR core, which is a collection of .h, .c and .cpp files. They are all together in the application.

You would probably be best off getting them from the github repository (https://github.com/arduino/Arduino) - the files you need are all under hardware/arduino/avr

On your Mac you may find them as /Applications/Arduino.app/Contents/Resources/hardware/arduino/avr or somewhere similar (not entirely sure where it puts it within the app).


How to use a coma as the decimal separator?

Print the integer part, print a comma, then print the value minus the integer part.

float value = 123.45;
int ival = (int)value;
int frac = (value - ival) * 100;

Serial.print(ival);
Serial.print(",");
if (frac < 10) Serial.print("0");
Serial.println(frac);


Why Windows 10 does not see Nodemcu device?

Read through https://stackoverflow.com/questions/43007501/nodemcu-not-detected-by-computer#:~:text=I%20had%20to%20install%20the,Afterwards%2C%20it%20worked.&text=For%20future%20people%20with%20this,and%20it%20wouldn't%20detect. and  also search few ways to remove oxidation from pins like using autosol (I have never used it ) . Try uploading code through FTDI modules or just get it replaced.


Mac OSX Yosemite no serial ports showing for Uno R3

Probably, you have Chinese Uno analog which works on CH340 USB-to-serial chip, so you need to install driver for it.

Steps to fix:

Install the CH340 driver
Run the command in Terminal: sudo nvram boot-args="kext-dev-mode=1" (disable kext signing introduced in Mac OS X 10.9 Yosemite)
Reboot

Also you're right according to Uno and FDTI:

  Differences with other boards

  The Uno differs from all preceding boards in that it does not use the FTDI USB-to-serial driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a USB-to-serial converter.


Low Power Library 4 seconds ON, 10 minutes OFF

Your problem here is your 10 minutes mark. If you're willing to take a somewhat more complex route, you could use a low-power, programmable, external timer like TPL5110. You can set an interval of up to 120 minutes by selecting the appropriate value of the programming resistor.

This kind of timers can be used to drive the gate of a logic-level P-channel MOSFET that acts as a switch for the power line of the Arduino.

Then, you simply you do all your stuff on the setup() function and leave loop() empty. You can switch off the Arduino by sending back a DONE signal to the TPL5110 at the end for your setup().

If, for whatever reasons, you really want your Arduino to be running for exactly 3 seconds, then you should run a timer in it (beware: not related in any way with TPL5110). Set it up so you the ISR of the timer breaks a do-while waiting loop just before the line of code that sends back the DONE signal.


Arduino ESP8266 Ticker interrupted by DallasTemperature/OneWire?

Ticker does not interrupt your code. It is a OS-timer and will call your function once the time is elapsed.

The Tiker callback can be interrupted by a "real" interrupt or another Task with higher priority and does not provide any reliability - it will just be called.

A solution (not the best) would be to disable manually all interrupts, if you can't solve it in another way.

If you just want a blinking led, you should use a Timer interrupt as your callback is short and fast. Maybe with the ICACHE_RAM_ATTR attribute.


How to send data from an Arduino GPRS module to a Django application hosted on Heroku?

There's a number of errors in your program regarding your understanding of basic networking:

Let's start with this bit:

String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
scnt += s_ip ;
scnt += "\",80\r\n" ;

That constructs a string:

AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80

and sends it to the modem.  Now:

There is no such protocol as "TipCP" - I think you meant "TCP"
You need to provide an FQDN (Fully Qualified Domain Name), not a URL.  FQDNs don't start with "https://".  I think you meant to use "foobar.herokuapp.com" where "foobar" is the name of your application.

You then go on to form a GET request and send it.

Now: the URL you used instead of an FQDN starts with https:// - that tells me you want to be using SSL for your communications. I don't know if that is required for Heroku or not, but if it is then you cannot use AT+CIPSTART with it unless you feel like trying to implement the entirety of SSL in your program. Also you would be connecting to port 443 not port 80.

Assuming you don't need SSL fixing your protocol and FQDN may be enough. However using the AT+HTTP... commands instead of manual manipulation of a raw TCP socket may be an easier option.

If you do need SSL (and it is advisable that you do if you can) then you will have to use the SIM900's AT+HTTPS... command set (detailed here).


What is the difference between running code with the scope of the void setup() or void loop() vs. outside their scope?

In your test code, you declare Timer1 in global scope. This means its
constructor will be called right when the program starts, even before
main() is called. The first thing the Arduino main() does is
to call init(), which configures all the timers for PWM
operation, as expected by analogWrite(). Then, any initialization of
Timer1 done by the constructor will be undone by init(). That's why
you want to defer that initialization until setup().

Edit: I took the liberty to do a code review on your post. Below are
a few suggestions. I hope some of them might be useful.

Put the empty constructor in the .h file, this avoids it being
compiled into a real empty function.
Qualify frequency, clock_pulse and opening_time as const,
and make period_ms local to Timer1::begin(). This way all the
floating point operations are performed at compile time and you
don't get all the floating point support compiled into your program.
Your CRITICAL_SECTION_* macros are redundant with
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) from avr-libc. But
then, do you really need to block the interrupts the whole time?
I don't find the other macros in Timer1.h really useful either: just
put comments next to each access to a hardware register.
I would set TCCR1B last: the timer starts counting the moment you
set this register.
You should subtract 1 from the values you set in OCR1A and
OCR1B: the period and HIGH time are OCR1A+1 and OCR1B+1
respectively.
You may want to round the period and HIGH time to the nearest
integer. It may make no difference here but you users may want to
change frequency and opening_time.
Your variables ocr1a and ocr1b serve no useful purpose, they
just needlessly eat RAM.
You casting opening_time to float, then back to unsigned int,
serves no useful purpose either.
You may want to replace digitalWrite() with direct port access, as
this function is really slow and you are calling it from an ISR.

Below is my throw at Timer1.cpp. Note that port and bit could be
made private data of the class, and the pin number could be a parameter
to the begin() method.

#include "Arduino.h"
#include "Timer1.h"

/* The three constants below can be tuned to taste:  */

const float frequency    = 10;  // hertz
const float opening_time = 25;  // milliseconds
const int   pin          = 13;

/* Nothing should need to change below this line. */

const uint16_t prescaler = 256;
const float f_timer = float(F_CPU) / prescaler;
static volatile uint8_t *port;
static uint8_t bit;

void Timer1::begin() {
    // Prepare the output.
    port = portOutputRegister(digitalPinToPort(pin));
    bit = digitalPinToBitMask(pin);
    pinMode(pin, OUTPUT);

    // Configure Timer 1.
    TCCR1A = 0;  // undo the configuration done by...
    TCCR1B = 0;  // ...the Arduino core library
    TCNT1  = 0;  // reset counter
    OCR1A  = round(f_timer / frequency) - 1;
    OCR1B  = round(f_timer * opening_time * 1e-3) - 1;
    TIMSK1 = _BV(OCIE1A)   // enable TIMER1_COMPA interrupt
           | _BV(OCIE1B);  // enable TIMER1_COMPB interrupt
    TCCR1B = _BV(WGM12)    // CTC mode
           | _BV(CS12);    // prescaler = 256
}

ISR(TIMER1_COMPA_vect) {
    *port |= bit;
}

ISR(TIMER1_COMPB_vect) {
    *port &= ~bit;
}


You really shouldn't charge a lithium battery whilst discharging it. The charger may either never know that it has finished charging and overcharge it, or shut off early and never charge it up properly at all.

Instead you should arrange that your MCU is powered directly from the PSU so that it always has stable power, and feed that same power into a normal charger via some form of electronic switch so it can be turned on and off. The output of the battery can then be fed through another switch into your heavy load.

When it comes time for your load to be activated you switch off the power from the charger and switch on the connection from the battery to the load.

What you use to do the switching is entirely up to you - whether you choose P-channel MOSFETs or relays entirely depends on your situation.

Here's a block diagram to better illustrate it to you:

simulate this circuit – Schematic created using CircuitLab


Controlling I2C slave on Arduino with Python

Since you are using an arduino as a partial bridge to a PC, it appears that you already have a solution in hand.

There is a project on Git that is intended to perform this function that you could use for reference.  (Disclaimer -- I have not tested this code.)

The cheapest stand alone device that I found was a $15 breakout board from Adafruit.


Does int array[100] = {0} contruct work on Arduino?

I'm used to this way from my desktop C++ programming practice:

int array[100] = {0};

  I couldn't find any info on whether or not this construct works on Arduino.

The = {0} has no actual effect. It is the same as:

int array[100];

Uninitialized static / global variables, and variables explicitly initialized to 0, are placed in the .bss section of memory.

This section is initialized to 0 by the CRT (C Runtime) code (the startup code for the system).

The compiler is responsible for placing these variables in the .bss, but it is the job of the startup (CRT) code to initialize it to zero.

This is standard C operation and is not likely to ever change since it would break all sorts of things.

Note: this does NOT apply to local variables allocated on the stack. These must be initialized to 0 if you want them to start as 0.


Trying to move a stepper motor back and forth

Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.

Are you sure you're using a stepper?


Is a HC-SR04 fast enough to make decisions on moving robot (4 Johnson motors 300 rpm)?

On it's max speed, how far is it's braking distance?
Then you should start braking atleast from before that distance of the object.

Let's say your braking distance is 25cm, you should start braking >25cm.
But this is only when you would instantly brake at the moment you're within 25cm reach.

So we have to know how many distance we will travel during the calculation, before we start braking.
You could just try it out, set the distance a little higher everytime you crash into it (Assuming it doesn't fail and is always at the same time).

We have to know the top speed of your motor, RPM doesn't say a lot in this story, we'll need to know how big your wheels are to be able to determine how many cm's you'll travel per revolution, and doing that times the RPM, you know your top speed. (Or you can also measure this, but it can change depending on how full your battery is)

Also, your code should be real-time you'll likely want to use timers to trigger the trigPin and use an interrupt on the echoPin to be sure none of your code will delay your sensor. This will improve execution speed aswell as reliability/deterministic timing. Also, it will make it possible to run it aside from your regular code.

So if you know, your top speed = 10cm/second.

And you know that 1 calculation+reaction-time is 200ms.

You can safely assume that you need >2cm extra.

To be honest, you should add a little for when it's slippery/another surface or just so you won't touch the object.

So. The ping sensor is almost always fast enough, only if the calculated range is outside your max range, it will not work.
You could however, use an IR proximity sensor which will trigger at a set distance. This way you don't have to do any calculations and just brake whenever you receive the interrupt. But it won't tell you the distance to the object.

The cool thing on the distance sensor is that you can also scale the brake distance on your driving speed, so that it will brake later when you're driving on half your speed. That way you can come very close to an object, but still be 100% sure that you won't crash into it.


Can this Motor shield support other arduino functions?

Yes, this motor shield can allow other components to be used. You just have to make sure that the pins being used by the shield are not used by you for other tasks. Generally all shields are designed such that they do not hamper the productivity of arduino. What use would only a motor driver be? Therefore they ensure that they do not block other pins.


How to send keyboard signals to two separate computers (arduino due)

For one of them, use Keyboard as you normally would.

For the other, do whatever Can the 2nd MCU on the UNO R3 be used for keyboard emulation? tells you to do to reprogram the ATmega16U2 connected to the other USB connector.


A series of if() statements and some simple division should be able to provide you with your PPM results.

From the datasheet, Alcohol Gas Sensor（Model：MQ-3), figure 5 shows the sensitivity curve:

It can be seen here

that there are three regions that the curve can be broken into:

The relationship is linearly proportional between 2.25 V and 3.25 V
Between 3.25 V and 3.8 V there is a curve
The relationship is linearly proportional between 3.8 V to 4.25 V

The slope of the straight line regions described in points 1 and 3 can be represented by the use of a constant and the PPM value by a simple division of the voltage by the constant.

The curve from the second part could be:

approximated by a straight line (thus, once again, using a constant), for simplicity, or;
more accurately, using a lookup table.

Using a straight line approximation for the curve (shown in lurid green), the graph becomes:

To determine the constant for the three lines simply take two points on each line and use:

  (y2 - y1) / (x2 - x1)

So for region one, assuming (by approximation, 3 V corresponds to 100 ppm and 2.5 V corresponds to 85 ppm (my eye sight may be slightly off here), the slope is

(3 - 2.5)/(100-80) = 0.5/20 = 0.025

You can calculate the constants for regions two and three in a similar manner (if using a straight line approximation for region two).

Therefore the code would be alomg the lines of

const double kRegionOne = 0.025;   // region one constant
const double kRegionTwo = ???;     // region two constant
const double kRegionThree = ???;   // region three constant

int ppm;                           // ppm result

/*
 * your code here
 * ...
 */

if ((sensor_volt < 3.25) && (sensor_volt >= 2.25)) {
  ppm = sensor_volt/kRegionOne;    // we are in region 1
} else if ((sensor_volt < 3.8) && (sensor_volt >= 3.25)) {
  ppm = sensor_volt/kRegionTwo;    // we are in region 2
} else if (sensor_volt >= 3.8) {
  ppm = sensor_volt/kRegionThree;  // we are in region 3
}

If you wish to be more accurate then use a lookup table for region two, as jsotola states in their comment.


FC-16 led matrix module based on MAX7219

I haven't used this library, but reading through the documentation it seems it operates on the concept of zones.

Create a zone for each row (a zone is a contiguous block of modules forming a kind of sub-display)
Perform operations on the zones with the zone-specific functions.

For example, setting up your zones would be:

P.begin(4); // We will have 4 zones
P.setZone(0, 0, 3); // Modules 0-3 in zone 0
P.setZone(1, 4, 7); // Modules 4-7 in zone 1
P.setZone(2, 8, 11); // Modules 8-11 in zone 2
P.setZone(3, 12, 15); // Modules 12-15 in zone 3

Then you can clear a zone with:

P.displayClear(2); // Clear zone 2

And write text to a zone with:

P.displayZoneText(3, "P03", PA_CENTER, 0, 0, PA_NO_EFFECT, PA_NO_EFFECT);

I'm not certain about what all the parameters mean, but the prototype is:

void displayZoneText(uint8_t z, const char *pText, textPosition_t align, uint16_t speed, uint16_t pause, textEffect_t effectIn, textEffect_t effectOut = PA_NO_EFFECT);


How to flash/blink I2C LCD backlight without delay function?

Besides the standard 'compute a target millis() and compare' standard, which can get clunky when you have to handle more than 1 repeating or delayed event, there are also more than one decent library that abstract the concept, but also add features.

One example is the Ticker library.

With these methods, you create a callback function and pass that function name into the object constructor, along with the timing parameters.

So you might:

[various #include, #define, etc.]

Ticker flashBacklight(toggleBacklight, 100); //call toggleBacklight() every 100ms

// Create the callback function, which just toggles the backlight each call.
void toggleBacklight() {
  lcd.setBacklight( !lcd.getBacklight() );
}

setup() {
  [...]
}

loop() {
  // Start or stop the ticker based on your own situation. Once started, it will call your callback function at the specified interval until stopped.

  if (warningSituation) {
    flashBacklight.start();
  } else {
    flashBacklight.stop();
  }

  flashBlacklight.update();
}

Another related library is SimpleTimer

EDIT

Your code example, updated:

#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void toggleBacklight();

Ticker flashBacklight(toggleBacklight, 100); //when i use ticker here am getting not declared in scope

const int buttonPin = 3;
int buttonState = 0;
                      // pls declare   flashBacklight   , long flashBacklight = 100;   ??
                      //   pls declare toggleBacklight

void toggleBacklight() {
 // lcd.setBacklight( !lcd.getBacklight() );  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}
void setup() {
   lcd.begin(20, 4);
 lcd.setBacklight(HIGH);
 pinMode(buttonPin, INPUT);
 }
void loop() {
      buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH)          // if button goes high the back light must keep on flashing untill its released
   {
    flashBacklight.start();          //flash the lcd backlight
  } else {
    flashBacklight.stop();           // Stop flashing the backligh
 }
   flashBacklight.update();
  }


4 consecutive bytes in buffer to unsigned long

If they were in the same endian order as a long (little-endian on an Arduino, which they don't appear to be) you could just point to them:

uint32_t *l = (uint32_t *)&packetBuffer[40];

Then use *l to access the content as a long.

However since they look to be in a big-endian order it's not that simple. The simplest thing you can do is just re-combine them with bit-shifting:

uint32_t l = ((uint32_t)packetBuffer[40] << 24) | ((uint32_t)packetBuffer[41] << 16) |
             ((uint32_t)packetBuffer[42] << 8) | (uint32_t)packetBuffer[43];


Connect the output of an Arduino to the input from another Arduino

As you are trying to communicate with two arduinos I will suggest you to use some sort of standard communication protocol such as Two wire interface or I2c. There is the Wire.h library you can use and it has also a reference on the main Arduino site. If you have different necessity and want to carry on with you're methods you need to specify in more depth the connections you have made. As for now I can guess that the output is being connected to ground or some sort of load and that might be the reason you are seeing a drop out of voltage. But it might be also the case that you're output pin is changing so fast that the multimeter is not capable of reading the high state correctly


My computer dose not recognise my Arduino Uno

Majenko is probably right.  If it is a clone Arduino board you will need to install some CH340 drivers.  If it's an authentic board I would return it as it should work out of the box with the Arduino IDE.


Brushless motor + ESC with Arduino question

Like the previous answer stated, you should be using a 20-25c battery (can discharge up to 25A). I don't know exactly how much a 9V draws, but it definitely can't supply more than an AMP. Your motor pulls much more than 1 amp. Get yourself a nice LiPo from hobbyking.com, maybe an 8.4v or 11.1v

The ESC beeping could be telling you it can't draw enough Amps from the battery?


2D Tracking of an object - which sensor?

I feel that an array of IR transmitters and receivers could work for you.

If you put the transmitters/receivers in an recessed tube with (black, non-ir reflectant) separations, you can avoid crosstalk.
You should be wary that it may require some tweaking to find the right sensitivity.

Here is a video (and here) that shows this in practice. I like the fact that you don't need sensors on either side of the object.

You may also consider video-processing, but that's out of scope for Arduino.
Or use a Lidar.


Before and after the delay of 19 ms?

In setup add:

pinMode(2, OUTPUT); // LED pin output

Than changen in both cases:

  delay(19);

into

  digitalWrite(2, HIGH); // LED on
  delay(19);
  digitalWrite(2, LOW); // LED off


Cant's code against Yun Wireless Section

WiFi library won't work with the Yun: it's meant to work only with the WiFi shield.

On the Yun, everything but the pins is connected to the linux cpu. For the microcontroller to use all the devices available to linux, including wifi, you need to use the Bridge library. Try running example WifiStatus (Examples -> Bridge -> WifiStatus)

A drop in replacement (almost) of both Ethernet and WiFi libraries is the YunClient/YunServer pair, part of the Bridge library. Check out the docs at http://arduino.cc/en/Reference/YunBridgeLibrary.


How do I use 3 Hc-sr04 ultrasonic sensors to control 3 vibration dc motor?

There's a few things you need to consider when making multiple things happen at the same time.

Firstly is timing. You can't make two things happen concurrently with different timings if you have delay() in there, since nothing else can happen while delay() is executing.  So you have to get rid of all delay() calls and replace them with examining the difference between successive calls to millis().

For instance, imagine you're in the kitchen and you want to boil and egg and make a cup of tea at the same time.  You fill the kettle and turn it on.  You put a pan of water on the stove with an egg in it to boil.

Now you could sit and stare at the egg until it's boiled enough for you to eat, but what happens to the kettle while you're doing that?  It's boiled, turned itself off, and started to go cold.

So instead you put the egg in the pan and look at the clock.  Then you think "in 5 minutes I will take the egg out of the boiling water".  You might set an alarm for 5 minutes time if you have one, or you may keep glancing at the clock periodically to see if the 5 minutes have past yet.  Meanwhile the kettle has boiled and you've made your cup of tea.

Then the 5 minutes have passed.  You know that because you remembered what time you put the egg on to boil and you know what the time is now, so you can subtract one from the other to find that 5 minutes have passed.

Now let's make it a little more complex.  Imagine you want two eggs - one soft boiled and one hard boiled.  The hard boiled one may want 8 minutes, the soft boiled one 5 minutes.

So you put one egg on to boil and remember the time.  Roughly three minutes later you put the other egg in and also remember that time.

Once enough time has passed that the first egg has been in 8 minutes you take it out.

Once enough time has passed that the second egg has been in 5 minutes you take it out.

You have had to remember two start times which you then compare separately to decide what to do with each egg when.

To translate that to your program - you have to remember a start time for each action for your motors, along with the state of the motors - and when the right time has elapsed you change the state of the motor (motor on -> motor off - egg in pan -> egg on plate) and remember the time at which you changed the state so you can know when to change the state again.

That's exactly what the BlinkWithoutDelay example does to make an LED change state (on -> off -> on) at certain times by remembering when it last changed state so you know when to change the state next.


In programming, there are many cases where designing data structures is
more important than the code itself. Once you have a data structure that
makes sense, the code flows very naturally. I think this is one of those
cases, so let's start by looking at what data you have to store for each
of your passwords:

the password itself (let's call it the code)
whether it has ever been used and, if so, whether it has expired
if it has been used but has not expired yet: when it was used for the
first time

This can be saved in an object with the following data fields:

const char * const code;
enum { UNUSED, USED, EXPIRED } status;
uint32_t first_use;  // valid if status == USED

Now think about what kind of actions you want to perform on such a
password:

you want to be able to test whether it matches some user entry
you want check whether it can be used and, if so, take note that it is
being used

Based on these requirements, I propose the following class:

const uint32_t PASS_LIFE_TIME = 15000;

class Password {
public:
    Password(const char *c)
        : code(c), status(UNUSED) {}
    bool matches(const char *entry) {
        return strcmp(code, entry) == 0;
    }
    void update() {  // expire if it needs to be
        if (status == USED && millis() - first_use > PASS_LIFE_TIME) {
            status = EXPIRED;
        }
    }
    bool use() {  // returns true on success
        if (status == UNUSED) {
            status = USED;
            first_use = millis();
        }
        update();
        return status != EXPIRED;
    }
private:
    const char * const code;
    enum { UNUSED, USED, EXPIRED } status;
    uint32_t first_use;  // valid if status == USED
};

Now you need to store all the passwords in an array, and a couple of
functions to operate on the password collection as a whole:

const int PASS_COUNT = 10;

Password passwords[PASS_COUNT] = { "2028", "1234", "1294",
    "4795", "5651", "7616", "5648", "1487", "7095", "2554" };

void update_all_passwords()
{
    for (int i = 0; i < PASS_COUNT; i++)
        passwords[i].update();
}

// Returns true on success, and uses the matching password.
bool try_entry(const char * entry)
{
    for (int i = 0; i < PASS_COUNT; i++)
        if (passwords[i].matches(entry))
            return passwords[i].use();
    return false;  // no match found
}

The function update_all_passwords() is meant to be called on each
iteration of loop(). It may seem superfluous, as a password is updated
whenever you try to use it. However, without regular updating, a used
password could be reused 49.7 days later, because of the millis()
rollover.

Now, in your program, you just need to:

Put a call to update_all_passwords() at the beginning of loop()
Replace the big condition that tests for a valid password by
if (try_entry(readString.c_str()))


Find number in a reply returned via serial

Since you are being returned JSON, you can use the jsoncpp library found here
To split your return to an array. Then you simply retrieve whatever item you want using array index notation.

Here is another helpful post on creating arrays of strings in C++ from JSON.
C++ and JSON


Arduino Mega + SIM808 GSM + GPS Module + Program Switch ON without pressing Push Button?

There is a simple way of power the module without pressing the button. There is pin call D9 at the bottom right corner of the module. Just power the pin by Arduino digital pin or 5v pin around 3, 4 seconds. Then it will power the whole module. No need to press the press switch. Make sure you connect power(9V-12V) to the board and provide 5V and GND to the sim808 module. below figure shows the pin D9


What is the best board for setting up an SSH protocol to an Arduino?

Sounds like you want an Arduino Yun instead of an Uno.  Or a Dragino Yun Shield that turns your Uno into a Yun.


ypr contains the Yaw, Pitch and Roll. It is provided in radians.

Servo.write takes degrees.

Multiplying radians by 180/PI converts it to degrees.  Adding 90 centralises it around the 90 degree point (half way) of the servo.


What I understood from your question is you want only one limit switch to control the stepper motor in both directions.So here is the code that might be helpful for you in that case:

int dirpin_T1 = 2;
int dirH_T1 = 3;
int steppin_T1 = 4;
int limit = 10; // ASSUME LIMIT-SWITCH IS PLACED AT RIGHT CORNER
void setup() {
  pinMode(limit,INPUT);

  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);

}

void loop() { //STEPPER TRAVELLING LEFT TO RIGHT

    digitalWrite(dirpin_T1, LOW );
    digitalWrite(dirH_T1, LOW);
   do
   {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);

   }(digitalRead(limit)==HIGH); //AS LIMIT-SWITCH PRESSED MOTOR STOPS
  delay(500);
  //WHEN LIMIT-SWITCH IS LOW CHANGE THE DIRECTION OF MOTOR ROTATION
  if(digitalRead(limit)==LOW)
  {
      digitalWrite(dirpin_T1, LOW ); //CHANGE MOTOR DIRECTION (LOW TO HIGH)
      digitalWrite(dirH_T1, HIGH);
     for(int i=0; i<36000;i++)
      { //please try changing value of i as it depends on how much rotations you want your motor to step forward

      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
     }

  }
}

The simple logic would be to move the motor in one direction until limit-switch is HIGH. And to move it to the other direction when its LOW i.e already pressed.Correct me if I am wrong and try modifying the code as per this logic.However you need to change your code depending upon what type of driver you are using. Right now I am using TB6560 driver.You can use if loop instead of do while loop to make it easier to understand.


When reading an analog voltage an analog pin has a very high resistance - usually very very much higher than the resistance of any potentiometer used, and input current to A0 can be regarded as zero for practical purposes.

For practical purposes the current drain from the supply will be that which flows from 5V to ground via R1 & R2.
I = V/R = 5V/(R1  + R2)

As for a potentiometer the sum of R1 + R2 is constant, the position of the pot-wiper makes no difference to current draw.

eg 10k pot. I_supply  = V/r = 5V/10K = 0.5 mA.
An I_A0 ~= 0

The upper value of a potentiometer which should be used for an analog input is covered by the uC (microcontroller) data sheet. The key parameter is uC input bias currents flowing in the potentiometer and causing small voltages which affect the analog reading. A rule of thumb is to keep such voltages under about one LSB (least significant bit) of the ADC.


As always, ~ in C++ is bitwise negation.


I don't know what you need that Preferences thing for, but I would use SPIFFS/FAT anyway. Simply store the certificate in a file in flash and read that file when you need it. The required space is no problem as you can choose the size for file system in the partition table and also you can upload the file (there is a plugin in the arduino IDE for this purpose) after flashing the firmware, so having different certificates on individual devices is no problem.
I saw that you tagged the question with 'eeprom': the esp has no eeprom but emulates it with a blob in flash, so using any flash library is just as fine. The esp also supports wear-leveling, which makes using flash an even better option as the dedicated eeprom-partition, which was used in an older version of the sdk, would wear out orherwise. The "eeprom" is just there to be consistent with the use of other arduino's eeproms.


I2C Wire.write function doesn't seem to work

According to the captured communication NACK was received (confirmed in comments) and according to the Wire library twi_stop will be called (and sent) in this fault scenario.

case TW_MT_SLA_NACK:  // address sent, nack received
  twi_error = TW_MT_SLA_NACK;
  twi_stop();
  break;


PWM pins weird on Arduino Mega, works on Arduino Uno

Never mind; this was me making a mess of the bit masking.

See this github repository for working code with Arduino Mega.


Your problem here is that Animal current_animal = animalArray[i]; is making a whole new Animal object that starts as a copy of animalArray[i];, but after that the two are no longer associated. Then when you call current_animal.alive = true;, you are not actually changing the animal in animalArray[i] anymore.

The simplest way to fix this is to make current_animal a reference to the object you pick out of the array, although a pointer would work the same way. With this code:

Animal& current_animal = animalArray[i];
current_animal.alive = true;

current_animal becomes a reference to animalArray[i], instead of a copy. Then operating on current_animal changes the same data that is stored in animalArray[i] like you intend.


Fail programing a Sonoff Dual with Arduino IDE

Your code is not good to detect if it  works.

The esp8266 Serial needs some time until it prints. First print after the Serial.begin() isn't printed. I guess the reason is the USB chip.

According to schematic, the LED in Sonoff Dual is on pin 12