Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate?

You can achieve this fairly simply by using namespaces. Inside a namespace, symbols are relative to that space. So you could put all of your first sketch into the namespace sketch1, and all of the second sketch into the namespace sketch2 (assuming it all fits, of course).

Now you can call the first sketch's setup and then loop, by qualifying it with the namespace name as illustrated below.

// FIRST SKETCH

namespace sketch1
{

  // FUNCTION PROTOTYPES

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

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

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

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

  void func2()
  {
    // some other function
  }

} // end of namespace sketch1

// SECOND SKETCH

namespace sketch2
{

  // DECLARE FUNCTIONS BEFORE CALLING THEM

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

  void func4()
  {
    // some other function
  }

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

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

} // end of namespace sketch2

// MAIN LOOP AND SETUP

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

void loop()
{

} // end of loop

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

  yet run them one after another

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

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

Important note re function prototypes

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

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

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

void foo (int a, int b)

Add a semicolon, eg.

void foo (int a, int b);

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

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

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

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

You need to inspect the sketches and see what they have done, so you can "undo" it. For example:

void wrapup ()
  {
  // set all pins to inputs and LOW
  for (int i = 0; i < 20; i++)
    {
    pinMode (i, INPUT);
    digitalWrite (i, LOW);
    }
  // if Serial used
  Serial.flush ();  // flush output
  Seral.end ();    // stop serial hardware

  // and so on

  }   // end of wrapup


There is no facility in the stepper library to do what you want - however the stepper library just sequences IO pins in the right order.

There's nothing to stop you just placing those same IO pins in a different state - the library won't care.

void sleepStepper() {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
}

That will effectively set every port of the L298 LOW, which is equivalent to "brake" mode on a normal DC motor, or "not actively driving" on a stepper (not perfect freewheel, there is still some flyback braking).

Another option is to connect the EN pin(s) of your L298 chip to a GPIO and use that to turn the whole system on and off. That will disconnect the drivers from the motor and give you even less movement resistance than the "all low" method above.


Arduino SPI Communication with H3LIS100DL accelerometer

The basic SPI operations looks like this. First read single register:

uint8_t readRegister(int index)
{
  digitalWrite(CS, LOW);
  SPI.beginTransaction(SPI_SETTING);
  SPI.transfer(READ | index);
  uint8_t res = SPI.transfer(0);
  SPI.endTransaction();
  digitalWrite(CS, HIGH);
  return (res);
}

And second write single register:

void writeRegister(int index, uint8_t data)
{
  digitalWrite(CS, LOW);
  SPI.beginTransaction(SPI_SETTING);
  SPI.transfer(WRITE | index);
  SPI.transfer(data);
  SPI.endTransaction();
  digitalWrite(CS, HIGH);
}

Some more details:

const uint8_t WRITE = 0x00;
const uint8_t READ = 0x80;

It is also possible to read/write a sequence of registers by providing the register index with the MS set. This will auto-increment the register index.

SPI_SETTING is left as an exercise (to be updated).

Cheers!


The best way to handle this exception is to identify what's using so much space on the stack and rewrite your code to avoid it.
The three most common ways you'd use too much stack space are:

large local variables - for instance, declaring a large array as a local variable inside a function, like:

#define VERY_LARGE_STRING_LENGTH 8000

void loop() {
  char my_very_large_string[VERY_LARGE_STRING_LENGTH];

  for(i = 0; i < VERY_LARGE_STRING_LENGTH; i++)
    my_very_large_string[i] = ' ';
}

Local variables are stored on the stack, so a large array of them will use up a lot of stack space.

recursive functions - each time a function recurses it uses stack space. If it recurses deeply enough then it will trample the stack guard and cause this exception. For instance:

int count(i) {
  i--;

  if(i > 0) {
    Serial.println(count(i));
  }

  return i;
}

void loop() {
  count(8000);
}

Each time a function recurses, its return address and its arguments and local variables are all stored on the stack. If it recurses too many times it will use more storage than is allocated to the stack.

mistakes in your code like wild pointers and buffer overruns

void loop() {
  char my_bad_string[10];
  char *wild_pointer;

  // buffer overrun
  for(i = 0; i < 8000; i++)
    my_bad_string[i] = ' ';

  // who knows where this will end up pointing
  wild_pointer += rand();
  wild_pointer = ' ';
}

when you overrun an array on the stack you'll probably overwrite other variables and corrupt their values. Do it enough and you'll hit the stack guard. Remember that C strings (char arrays and pointers) need n+1 characters to store a string of length n because they're terminated with an extra null '\0' character.
If you're using recursive functions, look at ways to limit the recursion or use tail recursion which the compiler may be able to optimize to avoid using excessive stack space.
If you're using large variables, think about why and rewrite your code to be able to use smaller variables. For instance, if you're reading a large file, try to process it a line at a time rather than reading the entire file into memory. If you're downloading large JSON from a web server, try using a streaming JSON parser rather than downloading the entire thing and then processing it.
A mistake in your code will be the hardest to figure out, given that it's a mistake. Be careful about pointers and memory allocation. Although memory is allocated from the heap and not the stack, if it's overwritten or reused after it's been freed using it as a pointer can still cause stack corruption. Also be careful to not return pointers to local variables inside functions:
int *do_not_do_this() {
  int this_will_not_work_the_way_you_hope = 0;

  return &this_will_not_work_the_way_you_hope;
}

can also lead to stack corruption as the space occupied by the variable will no longer be reserved for it and may be used by something else.


Help with parts identification from arduino starter kit from aliexpress

Those are tilt sensors. The rattling is a metal ball that contacts two pins inside, closing the connection.
The 1838B is a full module that partially decodes the received IR so that a MCU can fully decode the rest easily. What you have there is a bare phototransistor with an IR window on the top. You would use it for proximity or presence sensing. Instead of varying its resistance, it varies the amount of current it will pass.
Probably the single-digit 7-segment display, as opposed to the 4-digit display they have listed as "4 digital tube".


How can I set 4 Arduino Leonardo PWM-ports between 200Hz and 1kHz?

The ATmega32U4 on the Leonardo has 4 timers, named Timer0, Timer1, Timer3 and Timer4. Timer0 would be used for millis().

Timers 1 and 3 are 16-bit timers, and Timer4 is a 10 bit timer.

You can get a wide range of frequencies by changing the prescalers and other factors. A bit would depend on whether you want them to all have the same frequency (but maybe with different duty cycles) or different frequencies. Each timer has two "ports" associated with it, so you can have different outputs - up to a point - for each timer. A given timer can only be in one mode at a time, which limits a bit what its two output ports can be doing at one time.

I have a page about timers which is for the Atmega328P, but the Leonardo timers have a lot in common with that. For more details see the ATmega32U4 datasheet.

You could get a more detailed answer if you clarified what the exact frequency you want is, what mode (eg. PWM, fast PWM or something else) and whether each output should be the same or different frequencies.

According to the Leonardo product page:

  PWM: 3, 5, 6, 9, 10, 11, and 13. Provide 8-bit PWM output with the analogWrite() function.

So even if you lose two to Timer 0, you should have 5 outputs left (it looks like the "B" side of Timer 1 and Timer 4 share the same pin).


Using the Logging library, sometimes doesn't exit setup()

The constructor (called in a rather weird way) doesn't do anything, so I don't think that is the issue.

Logging.h:

    /*!
     * default Constructor
     */
    Logging(){} ;

Logging.cpp:

 Logging Log = Logging();

You should be calling Log.init(whatever) once in your code (as in the example). Are you doing that?

Please post a Minimal, Complete, and Verifiable example.

Without any posted code, we can only guess at what you are doing.

  I thought it was bad form to initialize object, or even have any running code, in a .h file. Is this a possibility, and do I have any options to fix this?

That is not done in the library you linked to.


What is the proper way to implement PID?

Each unique variable you want control over should have a single pid loop, and each loop should only ever stretch across one "order" of time.

For example, to control the craft's roll rate, you should have one PID loop that takes the target roll rate and outputs the controlled roll torque value, which gets transformed somehow into motor accelerations. The trig weights for that part can be precalculated so it doesn't have to happen at runtime.

To control the craft's roll rotational position, you would need one PID loop that takes the target roll position and outputs the target roll velocity, that target roll velocity then becomes the setpoint for the roll-velocity pid loop.

I don't see why each motor would need its own PID loop unless you are measuring the actual thrust each motor produces. If you did measure each motor's thrust their pid loops would still come after the target torque value were calculated. The target torque PID calculations don't need to know about what motors exist or where they are located.

I may not be understanding the intention of your diagrams or what "order" the PID loops are in, so feel free to comment with clarifications. This is complicated stuff.

Its also worth noting that the actual implementation pid often has some features that don't appear in theoretical pid loops like integral windup prevention. You also need a way to either call them at exactly the same interval each time, or accurately keep track of the time delta since the last update. You may want to take the derivative of the process variable only, not the error, so you don't observe setpoint changes in the D term; you could also "outsource" the derivative term if you IMU has a better calculation of it (like the raw gyroscope values).


How to prevent flickering relay upon waking from deep sleep using ESP01 board?

The only two pins that don't glitch or change state during reset and boot are GPIO4 and GPIO5, and neither of them are brought out to the 2x4 header on an ESP-01.
https://rabbithole.wwwdotorg.org/2017/03/28/esp8266-gpio.html
All of the other pins will make your relay click or chatter.  Pick a different module, or try soldering a wire onto GPIO4 or 5. The boot time is ~ 150ms long, so it'd take a long time constant R-C circuit to filter it out, on the order of 1/2 second or more.


Arduino - Windows can't find the drivers

You may not have installed the drivers when installing the IDE. The only way I know to reinstall the drivers is to reinstall the IDE and make sure when you get to this screen you tick every box:

Otherwise you may not have selected your board correctly. To select your board in the IDE, go to Tools > Board > Arduino Uno/Genuino Uno

Your port select may then appear, it should be COM1 or something similar. If you have multiple, just try them all by selecting one and then upload a sketch to it. The Arduino Uno should flash some lights if it worked correctly.


What components I need for a small GPS tracker

You have two options. Option 1. Buy a ready made pet tracking device from online market e.g (https://www.aliexpress.com/item/Pets-Smart-Mini-GPS-Tracker-Anti-Lost-Waterproof-Bluetooth-Tracer-For-Pet-Dog-Cat-Keys-Wallet/32887784462.html?spm=2114.search0104.3.1.26793604pFMLma&ws_ab_test=searchweb0_0,searchweb201602_3_10065_10068_319_10059_10884_317_10887_10696_321_322_10084_453_10083_454_10103_10618_10307_537_536,searchweb201603_52,ppcSwitch_0&algo_expid=09c58262-a0e7-4205-8fba-cd8265c15b3e-0&algo_pvid=09c58262-a0e7-4205-8fba-cd8265c15b3e). Then you can download the app and start tracking movement.

Option 2: The other alternative is to build one from scratch by purchasing all the necessary components. This is option is most appropriate for students. You can check this page for more https://electronicsforu.com/electronics-projects/hardware-diy/gsm-gps-based-vehicle-tracking-system. However, you may not be able to achieve the small size as you wanted but you should have something close to it if you carefully select your components.


Sending data through esp8266 using arduino

SoftwareSerial can't listen on two instances. There is a .listen() function to switch between SoftwareSerial instances.

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to receive data from GPS module over hardware Serial.


Can I use a HC-05 and a GPS without a breadboard on a Arduino Uno?

I don't see why not. The breadboard is just something to help you prototype yuproect, in the end, your project should always be on a perfboard or a custom PCB.

Note that some male-female header might get handy.

I'm not sure that the HC05 can handle 5V though. You migh want to check.


What's your last error message?

no matching function for call to 'PubSubClient::publish(const char [11], String&)'

Read the documentation for the publish() method in PubSubClient:

  int publish (topic, payload)

  Publishes a string message to the specified topic.

  Parameters

  topic - the topic to publish to (const char[])

  payload - the message to publish (const char[])

Look at the parameters you're using. You're passing a String as payload. publish() expects payload to be a char[] (essentially the same thing as a char*) - a C language string. This is the error you're seeing.

Read the documentation for String. How do you get a char* from a String? The c_str() method.

You need to change

client.publish("esp32/data", jsonString);

to

client.publish("esp32/data", jsonString.c_str());

As for your other warnings, it looks like your Arduino libraries are a mess with multiple conflicting libraries installed; if you want to get rid of the warnings, clean up your libraries.


I have experienced many issues when using RadioHead library on ATTiny85 together with the Arduino IDE. Your issue is not the Dallas temp sensor.

The problem lies in that RadioHead uses timer 0 on the ATTiny and changes the prescaler on the timer to match the baudrate you have requested for your tranciever. The change of prescaler changes the way Arduino IDE functions like delay()works since those also use timer 0. I believe your Dallas library depends on delay() to synchronize the signals on the 1-bus so there you have a conflict between the two libraries.

I solved this by rewriting the RadioHead RHASK files to allow for ATTiny85 timer 1 to be used instead. Here's my code. Although I use TinyHead instead of RadioHead, the change will be the same as TinyHead is a RadioHead clone.

The only change I made to RH_ASK.h is the code to define whether to use TIMER1 or not.

// Flag to indicate whether to use timer1 in attiny85.
#define RH_ASK_ATTINY_USE_TIMER1

The below changes goes into RH_ASK.cpp

First change. Update pre-scaler code and add the pre-scalers used by timer 1:

// Put these prescaler structs in PROGMEM, not on the stack
#if (RH_PLATFORM == RH_PLATFORM_ARDUINO) || (RH_PLATFORM == RH_PLATFORM_GENERIC_AVR8)
#if defined(RH_ASK_ARDUINO_USE_TIMER2)
// Timer 2 has different prescalers
PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 32, 64, 128, 256, 3333};
#else
  #if defined(RH_ASK_ATTINY_USE_TIMER1)
   PROGMEM static const uint16_t prescalers[] = {0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16834, 3333};
  #else
   PROGMEM static const uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333};
  #endif
#endif

Second change. This code sets up the timer 1 and goes before the existing code for ATTINY timer0 in function RH_ASK::timerSetup(). please note the "... existing code" part. The existing code for setting up timer 0 goes between the #else and the #endif

#if defined(RH_ASK_ATTINY_USE_TIMER1)
#warning RH_ASK_ATTINY_USE_TIMER1 set.
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);
   if (!prescaler)
       return; // fault

   TCCR1 = 0; // Stop the timer
   TCNT1 = 0; // Zero the timer
   GTCCR = _BV(PSR1);  // Reset the prescaler

   // Number of ticks to count before firing interrupt
   OCR1A = uint8_t(nticks);

   TCCR1 = _BV(CTC1); // Turn on CTC mode / Output Compare pins disconnected

   // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
   TCCR1 |= prescaler; // set CS00, CS01, CS02 (other bits not needed)

   // Set mask to fire interrupt when OCIE1A bit is set in TMSK
  #ifdef TIMSK0
   // ATtiny84
   TIMSK1 |= _BV(OCIE1A);
  #else
   // ATtiny85
   TIMSK |= _BV(OCIE1A);
  #endif
#else
#warning RH_ASK_ATTINY_USE_TIMER1 not set.
   // use timer 0 (default)
   // figure out prescaler value and counter match value
   // REVISIT: does not correctly handle 1MHz clock speeds, only works with 8MHz clocks
   // At 1MHz clock, get 1/8 of the expected baud rate
   prescaler = timerCalc(_speed, (uint8_t)-1, &nticks);

... existing code

   // ATtiny85
   TIMSK |= _BV(OCIE0A);
  #endif
#endif

Third change goes where the vectors are set up. Note the added #if defined for TIMER1 and the corresponding vector. Note also that the vector for timer0 is now called TIM0_COMPA_vect in later RadioHead/TinyHead but the names TIMx and TIMERx are interchangeable.

#if (RH_PLATFORM == RH_PLATFORM_ARDUINO)
#if defined(RH_PLATFORM_ATTINY)
 #if defined(RH_ASK_ATTINY_USE_TIMER1)
  #define RH_ASK_TIMER_VECTOR TIMER1_COMPA_vect
 #else
  #define RH_ASK_TIMER_VECTOR TIMER0_COMPA_vect
 #endif
#else // Assume Arduino Uno (328p or similar)

Mind you that I have had other issues using the DallasTempSensor library. I'm not sure whether the issue is a low quality crystal in my ATTiny or not, but I get garbage readings from my sensor. The same code works flawlessly on my Arduino Nano, so I'm currently investigating whether my ATTiny is too far off in its timings to work properly with that library. I'm also going to try the OneWire protocol to see whether that one works better. However, the above code change resolved my issues with Arduino IDE and RadioHead/TinyHead.


Wiring is your problem. Use soldering iron/solder and flux. Solder your wires. Intermittent connections and accidental shortages with current setup may damage your Arduino and display (and possible your PC/laptop).


Accidentally shorted 5V to GND on Arduino Nano, can I reuse the ATmega328p?

On a Arduino Nano, there is a diode that prevents an external 5V source from back feeding into the USB source. If your clone equivalent has that as well, I suspect that is the part that got fried.


How to fix this error (expected ',' or ';' before 'int' exit status 1)?

Change your program like this:
int Led1=13;
int Led2=10;
int tone1=6; // <-- Add the missing semicolon here
int D=300;

void setup(){
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(tone1,OUTPUT);
}

void loop(){
// Remove the declaration of D here, it's already defined in the outer scope
digitalWrite(Led1,1);
digitalWrite(Led2,0);
delay(D);
// Set the leds inverse (otherwise, nothing happens, since setting the state twice doesn't do anything)
digitalWrite(Led1,0);
digitalWrite(Led2,1);
delay(D);
}


Porting "far" flash memory access from Arduino Mega to Due

The Due, being ARM, is a von Neumann architecture. That means that it has no concept of "progmem", "near" or "far" pointers, etc.  There are no _P or _PF variant functions, but the Arduino core provides simple stubs as a convenience.

Instead all "flash" memory access is just simple memory accesses using const.

The best thing you can do is to use preprocessor macros to select between AVR and ARM code:

#if defined(__AVR__)
    strncpy_PF(buffer, enumstr+c, sizeof(buffer));
    buffer[sizeof(buffer)-1] = 0;
    outBufLen+=sprintf(outBuf+outBufLen,"%d - %s",val,buffer);
#else
    outBufLen += sprintf(outBuf + oufBufLen, "%d - %s", val, cmdtbl[i].enumstr);
#endif

In fact, given the huge amount of "hackiness" involved in that program with regards the cmdtbl, and the massive amounts of code that just aren't needed on the Due, it may be better to start a fresh program that is Due specific and delete the swathes of unneeded code.


Arduino Nano, Uno and Mega - XBee connection difference

Not all arduino Mega pins support 'change interrupts', which is needed for Software Serial.  Only the following can be used for RX:

10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).


9 volt battery not being able to power motor driver

It is likely not a question of the voltage being "big enough". You do need to feed the correct voltage to your robot, but max current and capacity are also very important.
Those "9V transistor batteries" have very low peak current and very low total power capacity (measured in milliamp-hours, or mAh.) They are not up to the job of powering motors. You could easily drain a 9V battery like that in 15 minutes, much less a week.
You should connect 6 D cells in series, and use that instead. That would give you enough peak current and total capacity for your robot.


Can I power a 9g servo from an arduino nano with USB power only?

The max current of the Arduino-Nano 5V Pin is 200mA. So if you draw more than that it might damage your Arduino.

Here is an interesting summary regarding the Maximum Ratings of the Arduino Nano: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

  The 5V pin of the arduino is not connected through the
  microcontroller. As such, it can source significantly more power. When
  you are powering your arduino from USB, the USB interface limits your
  total power consumption to 500 mA.

So yes, it actually seems you can draw 250mA out of the 5V PIN.

  do I use the VCC or the +5v?

You use +5V, because VCC is for powering your Arduino with an external Power Source. It allows you to use up to 7-12V (recommended), or up to 6-20V (limits).

  does it matter which ground I use?

Doesn't matter

  should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something?

A breadboard makes it easier for you, to test your circuit. But you can do it without if you like. Then you possibly have to solder some connections

See also the offical Arduino Page for the Nano.


sleep mode and watchdog at the same time

When you sleep the Arduino is locked up. So yes, the watchdog timer will time out and reset the Arduino.

But, since you're in sleep mode, it's not so much a "reboot" as a "wakeup".

The watchdog timer is one of the normal ways of waking up periodically to do things.  If you want to use the watchdog for its other "anti-lockup" purpose then you will have to arrange some other way of waking up before the watchdog is due to expire so you can "kick" it.

Or you disable the watchdog entirely before going to sleep so that the only wakeup source is whatever source you have configured. Then you can turn the watchdog on again when you wake up.

However that probably means that the watchdog is useless, since chances are you won't be awake for long enough periods for the watchdog to have any effect.

Sleeping and using the internal watchdog as a watchdog are pretty much mutually exclusive.  If you sleep, then the watchdog is a periodic wake-up source.


Micronucleus is a bootloader - in the same way that Optiboot is a bootloader used on the Uno. It provides the USB connection to program the chip.

Without it you can't do anything at all with that, since the USB port just plugs direct into the ATTiny chip. With no software on the chip the USB port doesn't do anything.  It's kind of a catch-22 situation - you need software on the chip in order to put software on the chip.

In essence Micronucleus turns the ATTiny into a kind of Mini Leonardo.

You need to first put Micronucleus on the chip (which you can do with an Arduino as an ICSP programmer) and then once that is installed you should be able to start using that little board with the chip to program it.

Since you're on a decent operating system there's no need for "drivers".


Use of additional i/o ports in Arduino Mega

Additional I/O pins means more inputs and outputs. Therefore, you can have more signals. There are also some more specialized pins. For example, there are more PWM pins, more TX and RX pins for serial communication and more analog read pins.


You need this: https://www.sparkfun.com/products/11002
"The Go-Between Shield “goes between” two shields that aren’t compatible and effectively reassigns the pins. This trickery is achieved by isolating the top and bottom sides of the shield with surface mount headers and breaking them out into tables of jumpers that can be bridged to divert signals to and from different pins."


I have found a solution. There is a library called Ticker.h
I found this on github: https://github.com/esp8266/Arduino/tree/master/libraries/Ticker

Following is my demo code:

#include <Ticker.h>
Ticker ticker;
void setup() {
  pinMode(D7,OUTPUT);
  ticker.attach(1,isrFunc);//tickerObj.attach(timeInSecs,isrFunction)
}

void loop() {}
void isrFunc(){
  digitalWrite(D7,!digitalRead(D7));
}

For me, this code worked seamlessly on nodeMCU. Thank you.


Is SRAM erased when putting Arduino into sleep_mode_pwr_down?

Generally, Atmega sleep modes do not erase RAM. Their memory is static and as long as voltage (above 2.7V I believe) is applied, data is held.

However, this also depends on how you plan to wake up the device.
If it receives a RESET, RAM is cleared and program execution starts from the beginning.

  If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the Register File and SRAM are unaltered when the device wakes up from sleep.

Check out the AVR's sleep modes to see which fits your application best and how to safely wake it up again


UART between arduino UNO and pc via USB not in sync

There's a number of things going on here that combined give you the results you're seeing.
First off there's the delay at the start:
Enter the string: a

Enter the string: v

Enter the string: v
 You sent me: v
Enter the string: s
 You sent me: v

This is because when you first open the serial port the Arduino resets and enters the bootloader. Thus the first few things that get sent are discarded, and nothing is sent back from the Arduino - your sketch just isn't running at that point.
Next is the format of what you're sending compared to how you're receiving it.
You input a string and then send that string verbatim.  But on the Arduino you are reading all data up until a terminating newline character, which you are not sending.
But the reading function also has a timeout in it so it will return whatever it has managed to read in that time even if the terminator hasn't arrived. That timeout is 1 second by default.
So everything that gets sent within a 1 second window gets grouped together, which is what you see here:
Enter the string: d
 You sent me: r
Enter the string: s

Enter the string: e
 You sent me: ds

The "out of sync" appearance is because of that 1 second timeout - you are seeing what was sent a second ago.
The fix is simple enough: make sure that you send the terminating newline character from Python:
ser.write(str.encode(string + "\n"))

And wait a few seconds after starting your program and opening the serial port before asking for anything to be sent. Maybe add a time.sleep(2) after opening the port to enforce that delay.


How do I connect Arduino directly to MySQL server using the URL?

You are using DHCP, so this step might be optional.
Specify your network addresses (actually we want to specify DNS only but have to specify IP in 2nd argument, so likely have to specify gateway and subnet too):

IPAddress dns_addr( 8, 8, 8, 8); // GOOGLE DNS server, could be any DNS
IPAddress gateway_addr( , , , );   // put your gateway addr
IPAddress ip_addr( , , , );   // put your IP addr
IPAddress subnet( , , , );   // put your subnet mask

void setup(){
                  Ethernet.begin(mac_addr, ip_addr, dns_addr, gateway_addr, subnet);...

Now you could modify Connector::mysql_connect method (or create new method) as follows (only function declaration is changed, body is not):

boolean Connector::mysql_connect(/*IPAddress server*/const char *server, int port, char *user, char *password)
{
  int connected = 0;
  int i = -1;

  // Retry up to MAX_CONNECT_ATTEMPTS times 1 second apart.
  do {
    delay(1000);
    connected = client.connect(server, port);
    i++;
  } while (i < MAX_CONNECT_ATTEMPTS && !connected);

  if (connected) {
    read_packet();
    parse_handshake_packet();
    send_authentication_packet(user, password);
    read_packet();
    if (check_ok_packet() != 0) {
      parse_error_packet();
      return false;
    }
    print_message(CONNECTED);
    Serial.println(server_version);
    free(server_version); // don't need it anymore
    return true;
  }
  return false;
}

Modify the header file also:

boolean mysql_connect(/*IPAddress server*/const char *server, int port,
                                 char *user, char *password)

Now you can supply URL:

if (my_conn.mysql_connect("http:\\www.mysqlserver.com", 3306, user, password))...


I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.


Two problems:

Your first program sends an ASCII representation of the temperature with no line ending.  So after a few readings you get something like:

20.2520.2520.5021.0021.25

etc.  You need some line endings in there to break them up.

Secondly your second program reads one byte at a time as a number (float) and prints it - so would get something like:

50.00
48.00
46.00
50.00
53.00
50.00
48.00
... etc ...

You need to, in association with sending line endings in your first program, read each character of a single line either into a string and then parse that as a float (with dtostrf()) or directly into a float using a state machine.

You can read more about working with serial here and working with a number reading state machine here.


Measuring voltage on an analog pin - What do I need to know about amperage?

Yes. The only thing you need to be concerned about is the voltage. It needs to be less than the Arduino Vcc.

The voltage sense circuit (analog inputs) typically have a high impedance and should draw a negligible current from the circuit being sensed. I didn't have much luck finding the actual spec for any of the AVR chips, but I did find this answer to the question on Electronics.StackExchange – where they say "hard to tell, the specs are incomplete, but 10 KΩ seems like a reasonable guesstimate/assumption" (I paraphrase). The reasoning is interesting and worth a read.


Finally, here is how I did the job. In short, I separated the two topics of getting a trace of any user using socket.io and giving a limitations of the number of users.

First, my Arduino Yun is on a Ethernet network where a router, acting also as the internet gateway, is a dhcp server. My Arduino Yun have a static IP address in the subnet of this router (so it is not a dhclient). This can be set either by modifying the file /etc/init.d/network.

Including the lines:

config 'interface' 'wan'
        option 'proto' 'static'
        option 'ifname' 'your_interface_name'
        ipaddr xxx.xxx.xxx.xxx

or by using the LuCi interface.

For more information about the way to properly configure the network in OpenWRT, see Network configuration.

Then the router is set to authorize only few IP addresses.

The last step is to bridge the Wi-Fi and the Ethernet (WAN and LAN) keeping the configuration of the Ethernet interface. This can be done using the LuCi interface. Be careful of what interface configuration you keep. How to setup an OpenWRT router as a Wi-Fi bridge to an Ethernet router gives the way to do this.

Note that this can also be done using the Arduino Yun as a DHCP server if you don't want to be connected on a network.

In the end, any connections on the Arduino Wi-Fi will get its IP address in the authorized range (up to 16 users at the same time in my case) by the router/DHCP server through the bridge.

In socket.io, I took the id that is given to any connected client and the IP address to ensure that I have a same user.

About the NFC dynamic tag, I developed a NFC specific board with a dynamic tag in the Arduino Yun/Uno format and its library to push through the bridge between ATmega and Atheros any new Wi-Fi code or any webpage. I think it is outside of this scope so if you need anything about this I can give you in PM.

I finally get at the end a device:

Connected to an existing network and accessing the internet,
Serving the webpages I want using my node serve,
Able to push any information on any other devices on the network through my nodeJS server,
Enabling access to people to local or network content,
Serving some specific local information through the NFC shield.


The sensor you specified states:

Output: SPDT Relay Output

If accurate, it may be inferred that the output is simply 3 contacts where one is normally open and the other is normally closed and the 3rd is the common.  If true then you can treat the output as if it were an ordinary Single Poll Double Throw (SPDT) switch.  Note, with regard to processors, an ordinary switch may need to de-bounced.  This depends on how the state of the switch is used.


What is causing this 'narrowing conversion' warning?

That warning message arises when a compiler complies with C/C++ specifications.

According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),

  Each of the operands shall have integer type

Thus, in the evaluation of bx_0 | bx_1 within the statement const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};, the operands bx_0 and bx_1 are converted to int type before being OR'd together.  This produces an int result, which then must be narrowed to byte before it can be stored in the  byte array.

Knowing that the (byte) cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”.  :)


Receive sms on android phone without GSM module

There are exactly two ways of sending an SMS. Both of which require more than "just" an Arduino.

Directly using GSM - for which you NEED a GSM shield
Indirectly using an Internet Gateway - for which you NEED some form of internet connection.

Since you have an aversion to 1, 2 is your only option. So you require some extra hardware (unless you have an Arduino with built in WiFi or Ethernet) to connect your Arduino to the internet. Then you have to pay an SMS gateway provider to allow you to send SMS messages through them, and implement their API in the Arduino.

Also you need an internet connection available wherever the Arduino happens to be.

All in all a lot of work and you're really no better off than using a GSM shield.


I2C is designed to have multiple devices connected. Assuming the gyro and accelerometer have different I2C addresses they can both be connected to the same SDA and SCL pins.

For more information see http://www.gammon.com.au/i2c

Naturally you can only "talk to" one at a time. You may need pull-up resistors on both SDA and SCL, unless the hardware already has them.


Long term connection between Arduino and computer

I think the easiest option may be to keep the USB (ACM) link, so you
don't have to do anything special on the Arduino, and try to figure out
a way to identify the correct device on the computer side.

On Linux, providing consistent device names for specific peripherals is
normally the job of udev. You could add your own udev rule to create a
symbolic link for your Arduino every time you plug it in. Then, your
custom software would always open /dev/neopixel-monitor, which would
be a symlink to the proper /dev/ttyACMx device.

Actually, you may not need write your own rule. I took a look at the
udev rules installed by default on my Ubuntu 16.04 and found a file
named /lib/udev/rules.d/60-serial.rules meant to populate the
/dev/serial/by-path/ and /dev/serial/by-id/ directories. Then I
plugged in my Arduino Uno R3 and saw the symlink
/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_93140364233351E00101-if00
automatically created, which right now points to ../../ttyACM0. In
this name, 0043 is the USB device ID of the Uno, and the following
alphanumeric sequence looks like a serial number. The if00 looks like
an interface number, and may vary (it won't, se Majenko's comment).
The link name should
be a good way to uniquely identify that particular Arduino.


What will happen if I give my Arduino Uno more or less than 5 volts?

Will it break at < 5V? Not likely.

Check the datasheet for the IC's on the board and find the minimum power supply voltage the device works at.
At typical ATmega328 Safe Operating Area (under "Speed grades" in the datasheet) specifies approximately 4.1V for 16MHz.
If you require to use the USB interface, you'll have to check the datasheet for that chip too.

Will it run at < 5V? Maybe.

If the supply voltage gets below the minimum operational voltage, the controller may behave erratically. That means it can do anything (un)expected. This value is in the datasheet and probably somewhere around 2.7V.
If the Brown Out circuit is configured (in fuses), then the controller will switch itself off when supply voltage gets too low to prevent undefined situations. Once the supply voltage returns, it restarts.

Will it break at > 5V? Depends on where you apply it.

V(IN) should work fine for 7-20VDC as it is fed through an on board regulator. Notice though that the regulator has to dissipate the excess voltage and can get pretty hot when you draw a fair bit of current. The regulator will fail if the voltage goes over 20V or gets too hot too often;
+5V should work fine up to 5V, and I personally wouldn't worry if an external supply delivers up to 5.5V unloaded. Above that 5.5V you will probably release the magic blue smoke.


Solution needed for sending HTTPs requests from multiple Arduino units in the field

For secure TCP connection with WiFiNINA library use WiFiSSLClient instead of WiFiClient.

The Arduino firmware in the NINA ESP32 module has certificates of well known CA authorities so the server's certificate verification should work. If necessary, you can add public keys of server certificates to NINA.


It turns out the problem is a fairly common one - Actiontec wireless access points break this way when set to Both, not AES - see https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network

Apparently on other routers this bug is marked as a feature, "Wireless Isolation" or something.


This is basically two questions: how to get your SD card and WiFi working at the same time (in which case memory limitations are not an issue), and how to deal with the memory limitations if you choose in-memory storage of your data. I'll address the second one here; you should split out the WiFi/SD conflict into a separate question where you detail the exact hardware you're using and how it's connected.

You've got only 2 KB of RAM in an Uno and similar models, so you will have to discard data at some point, whether or not it was successfully sent in a reply to a web request. The key here is to use a fairly compact method of storing the data and to have an easy way to get rid of old values to free up space for new values.

One common way to deal with this is to use a ring buffer. This is a fixed size storage array with a pointer or index, which I'll call head, indicating the next storage location to use. You start with head = 0 (the beginning of the buffer) and every time you receive a new value you store it at head and then increment head by one. You also need to compare head to the end of the buffer and, when it would pass the end, reset it back to the beginning of the buffer. After the first pass through the buffer, storing at head will overwrite the oldest value previously stored.

Going back through the buffer to read out the old values is easy: you just start by reading the value at head - 1 (or the end of the buffer if head is 0) and work downwards, wrapping around when you hit 0, and stopping when you reach head.

You can handle the initial states where the buffer hasn't been filled yet in two ways: just fill the buffer with a value such as 0 that you don't mind returning as a "nothing stored here" value, or just set a flag at the start to say that the buffer hasn't been filled yet and you should stop at 0 when reading it out; this flag would be cleared the first time that head reaches the end of the buffer and wraps around.

Since you're getting data that are ints, storing them as (larger) strings would be silly; just create an array of ints of the smallest type that can store all possible values of your sensor, e.g., uint16_t if you're getting unsigned 16-bit values. With some experimentation and checking, you should be able to figure out how large a buffer you can use based on how much storage you have free after the RAM for other parts of the program has been allocated. I'd imagine that if you're careful and you're making sure you store strings in program memory you could make room for a buffer that would hold a couple of hundred entries.

Since this seems to be a student assignment, I won't provide sample code here; writing your ring buffer code will prove an excellent exercise in the details of programming.


I think there are 2 mistakes in your code:

First, you should ensure that the 3AT3 commands are termintaed by a new line character:

GPRS.print("AT+CREG/r");

should be changed into:

GPRS.println("AT+CREG/r");

or:

GPRS.print("AT+CREG/r\n");

Nite that I am not sure why you added /r at the end of the AT command, is that supposed to be part of the command? If your intention was to force a new line, then you meant \r not /r, which is not really a new line character but a carriage return (that might be interpreted the same by yur GSM module, but not necessarily).

The the second mistake in your code, is directly calling GPRS.read() without first waiting for a character to be available; in this situation, GPRS.read() will always return -1 as a specific value meaning "no available character to read".

So you should change your code to something like:

// 1st wait for a character to be available
while (!GPRS.available()) {
}
// Then read all available characters and log them to Serial
while (GPRS.available()) {
    Serial.print(GPRS.read());
}


The analog outputs aren't real analog outputs, they are PWM.

That means that they rapidly switch from OFF to ON and back to OFF again.  The analog value is the ration of OFF time to ON time, known as the Duty Cycle.

You can convert that rapid switching to a real voltage by passing the signal through a low pass filter.  The simplest form is the RC filter:


Using an Arduino as a electrical mains switch

You need to use Relays.  There all kind of relays.

Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)

There are a lot of guides for Arduino and Relays (for example)


Resistors/capacitor used in connecting 23LC1024 SRAM 1 Mbit

It's better to use external pull-up resistor at least on CS. It's because MCU pins are configured as INPUTs without pull-ups just after the startup/restart before it gets into the setup().

Also I'd recommend decoupling capacitor as close as possible to the SRAM power supply pins (between Vcc and Gnd). You can google what the decoupling capacitors are (they are also called bypass capacitors).

Edit: First two examples are supposed to be on bread board. So it's not so hard just rewire it, if you have to use for example /HOLD too. However the third example is soldered on prototype board and therfore it's not so easy to rewire it. That's why NU and /HOLD inputs are connected to the Vcc through 10k resistor. If you have to use /HOLD in the future, it's easier to just solder new connection, than rewire hardwired connection to the Vcc.

About decoupling caps - there are even sockets with builtin cap:


Shift between the carrier frequency of the signal transmitted with arduino and my garage door RC (433 mhz)

The reason is that your garage door opening is operating on a different carrier frequency than your transmitter module.  The plot you are showing is called a "waterfall" plot and shows the frequency on the "x" axis with time progressing from top-to-bottom.
The garage door remote appears to be centered just above 433.900 MHz while your transmitter is around 434.000 MHz.  While that might not seem like a large difference, these things are designed to be receptive in a very narrow band.
So you need to read the specifications of your transmitter module and see if its frequency is adjustable and, if so, adjust it upward to the correct frequency.


Splitting a Serial.readString into string array

Your main problem is this:

char buf[vst.length()+1];

You can't initialize an array with the return value of a function.

Instead you would need to use alloca to perform the same function:

char *buf = alloca(vst.length()+1);

However, the way you're doing it is wasteful. You don't need buf at all.  You can directly access and manipulate the internal char buffer inside the string using vst.c_str();.

For convenience you can point buf at it:

char *buf = vst.c_str();

To complete the picture here's a routine that takes the string and gives you three integers. Since we expect a specific format with only 3 sections to it we don't really need a loop.

// Use readStringUntil to avoid the 1 second delay.
String vst = Serial.readStringUntil('\n');
char *buf = vst.c_str();

char *hourString = strtok(buf, ":");
char *minuteString = strtok(NULL, ":");
char *secondString = strtok(NULL, ":");

if (secondString != NULL) { // Will only be true if we have two colons
    int hours = atoi(hourString);
    int minutes = atoi(minuteString);
    int seconds = atoi(secondString);

    Serial.print("It is ");
    Serial.print(minutes);
    Serial.print(" and ");
    Serial.print(seconds);
    Serial.print(" seconds past ");
    Serial.println(hours);
} else {
    Serial.println("Invalid time format");
}


Is it possible to move a servo without knowing it's current position?

A normal servo is an absolute positioning device. The position of the servo is directly proportional to the length in time of the sync pulse.  This means if you tell the servo to be in a given position, it will seek that position with out regard to the initial position.  It will simply figure out which way to go on it's own and stop when it gets there.

I should add, that in all likely hood, when you manually moved the servo you moved the positioning potentiometer inside the servo.  So it is expected that if the servo is told to go to a particular angle, it will still go to the same angle as it did before you manually moved it.


Bluetooth transfer problem with big files

I suspect that this is a String class heap-fragementation issue (again). To test this you could sending a fixed string buffer (vector of characters, "Hello world" :). Do not use String and SD/FAT in the test. Just send a large number of lines with dummy data.

If this works replace the String usage with a character buffer. Fill it from the SD file (buffer size at a time) and write to Serial.

Cheers!


Increase the resistance of a photoresistor with increase in light intensity

Arduino can not measure resistance. It can measure voltage.
To measure resistance you can convert resistance to voltage using a voltage divider.

In Arduino world a voltage divider consists out of 2 resistors in series between 5V and gnd. The connection to the 2 resistors is connected to a analogue pin.
Depending whether your LDR is connected to gnd or 5V the measured value on the analogue pin will go up or down with the resistance of the LDR.

In other words swap the resistor and your LDR from position.


IR signal: different libs, different bit/byte ordering?

It is the receiver (IRremote-based) which is decoding bits in reverse order. IRremote and IRLib2 implement the NEC protocol incorrectly (both on sending and receiving sides). More details in the issue report https://github.com/bengtmartensson/Infrared4Arduino/issues/52 .


Will bootloader communicate via TX0 / RX0

Problem solved. The standalone CH340-based converter for whatever reason isn't man-enough to reliably pull down the RX0 line when connected to the Mega 2560 (also with a CH340 converter on board). I've seen suggestions posted in various places that this can be a problem with respect to DTR (though I don't have a problem with it). My solution is to insert a 7417 open-collector non-inverting buffer between the output of the stand-alone converter and the RX0 input on the 2560 board. I've not been able to find a schematic for the Mega 2560 board to determine its pull-up resistor size but imagine it must be relatively small. Thanks to those who made suggestions.


I solved the problem using a Nextion timer. (tm0)

I got a timer and change tim value. ( unfortunately Nexion allow to maximum to 65535mS). vscope should be globle, otherwise you cant use timer in every page.

I reset the timer in page touch event. In timer event I put this code.

if(tm0.tim==60000) //reset time in mS
{
   page 0 //specific page to load
}


What sensor would detect the black stripe on an analog electricity meter?

A low cost option is the TCRT5000 infrared proximity sensor. While this is designed to sense objects coming close to the sensor, by reflection of the infrared light emitted by the integrated IR LED, it also does very well in detecting black versus reflective surfaces placed near it.

There are two parts to making this work:

Reduce the drive current for the IR LED of the TCRT5000 to the bare minimum which causes detection of the non-black portion of the electricity meter disc. While the datasheet specifies a forward current of up to 60 mA absolute maximum, a quick experiment I conducted shows appreciable detected signal at as little as 4 mA forward current, for a metallic target surface 2 mm away. Tune the forward current to work with the actual distance and reflectivity of your particular electricity meter wheel.
Place a black piece of card or plastic in front of the detector part of the TCRT5000, with a thin slit cut in it to align with the black strip on the electricity meter wheel. I am getting good results using a 1.2 mm plastic sheet with a 0.3 x 1.5 mm slit cut in it.
Note that the two hemispherical plastic parts of the TCRT5000 look more or less the same, so you will have to identify which one is the detector, and ensure that you do not obstruct the emitter by mistake. The side with the angled vertical edges (right side of image below) is the emitter and must not be obstructed.

With this arrangement, the collector current through detector will dip significantly each time the black stripe passes in front of the detector.


How to pass 'Serial' as an input argument in Arduino function?

The Serial object is the end of a chain of classes, each with a different set of functionality.

Print -> Stream -> HardwareSerial => [Serial]

Since you are reading from it the best class to use is Stream since that is the one that is the one that contains the reading functionality.

You should pass it by reference or as a pointer since you don't want to copy the object.

int compareFunction (int d, Stream &Serialx)
{

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

By using Stream you can use any object type that also uses Stream in its class inheritance chain - even things like a WiFi socket connection.

This behaviour is called polymorphism and is one of the more powerful features of classes in C++ (and other OO languages).


Serial.print start prints unreadable character without any reason

The problem was about high baud for SoftwareSerial. Changing it to 9600 the problem disappears.


Trying to power multiple servos at once using a Arduino Mega

Here is a spec-sheet for the MG996R servos. Notice at the top of the 2d page, they require a supply of 4.8 - 7.2 volts, and can draw .5 - .9 Amps running and 2.5 Amps when stalled.

You'll need a supply of 6 volts (+/-) that can handle that current, times however many servos you need to operate simultaneously. The 3.7 volt batteries don't even meet the minimum voltage for the servos (unless you have two of them in series, but then they're slightly over the maximum).

You need to figure out your power budget first, then how your are going to meet it. You might be able to use a lighter supply than the worst case (6 stalled motors) would require or even than 6 motors at full operating torque (0.9 Amp each), if you monitor the current on each motor and shut down the or sequence the one(s) with the highest draw. You might even try monitoring just the battery-pack voltage, which won't tell you which motor(s) are stressing, but will let you know that you're unable to supply the total requirement for that present move.

If it were me, I'd use battery voltage sensing first (easier, simpler) to see if I have a problem that I can't solve by sequencing the motors. I might find I don't need to measure each motor's current.

Update:

  So its either i use 3.7 bat or 9v. Or.can you suggest any other power
  source?

A single 3.7v battery won't work well) for a motor that needs 4.8v minimum. Two of them in series will be slightly over the max voltage spec (7.4v vs. 7.2v). Will that slight overage damage or overheat the motor? Will be OK for intermittent use? Maybe, if you're careful to shut down a stalled motor quickly. The alternative is to build a voltage regulator that will drop the 7.4 to around 6v, but the regulator must also be able to meet your power budget, too.

A 9v supply is definitely too high and will need to regulated to within the motors' spec. (I assume you're not considering the four or five cm high ones with snap-on connectors, usually used in smoke-detectors? They have very little capability to deliver current and will be totally unsuitable for your application.)

My first try would be to experiment with 1 motor at 7.4v with a typical (for your project) mechanical forces on it, and see if it overheats and how soon, with how much load. You'd be taking a bit of a risk with that motor but the potential advantage is you might save yourself having to build a high-current voltage regulator.

Update2:

  NiMH AA cells are 1.2V

Good call. Just know that Nickle-based batteries have the twin disadvantages of long charge cycles (or degradation of capacity with faster charging) and higher self-discharge rate of about 1%/day. Their advantage to you is that it's easier to make a battery pack whose voltage falls within the motor spec. If this is a one-time project, this may well be more important to you than their disadvantages.


You got me ;)

Since a UID is a fixed size you don't need to think in "lines", only in bytes.

The most efficient way of storing the UIDs is as pure bytes. I am not familiar with that specific card and reader combination, but I will assume as an example an 8 byte UID (though this all holds true for any other length you care to choose).

You treat your file on SD card like a kind of database with a number of records in it. Each record is the exact same size (8 bytes in this case) . To read or write a specific record you just "seek" to the record number multiplied by the record size - so multiples of 8 in this example.

myFile.seek(recordNumber * 8);

If .seek() returns false then you have reached the end of the file.

So to find a tag you can:

myFile.seek(0); // Start at the beginning of the file
int recno = 0;
char foundUID[8];
bool found = false;
while (myFile.read(foundUID, 8)) {
    if (strncmp(foundUID, myUID, 8) == 0) { // 8 bytes match
        found = true;
        break;
    }
    recno++;
}

At the end of that found will be true if there is a match, and recno will be set to the record number. Now the magic begins...

If it has been found and you want to delete it, think again. That's a very wasteful idea. Instead you just want to "invalidate" it - that is, replace the UID in the database with something the UID can never be - all 0xFF is a good choice. Simply:

myFile.seek(recno * 8);
for (int i = 0; i < 8; i++) {
    myFile.write(0xFF);
}

Now the tag has gone from the database. You may want to add a filter at the card reading phase to stop anyone using a card that has a UID of all 0xFF, of course.

Now for adding a new card...  This is where the fun starts.  You could just add 8 bytes to the end of the file, but then the file will grow and grow and grow. Instead, you can first search through the file for a tag entry that is all 0xFF and replace that data with your new UID. Just the same as when you deleted it - seek to 8x the record number and write 8 bytes.

It might help to write a function to wrap the tag seeking routine so you can easily call it multiple times from multiple places. Returning the record number would be most useful - and you could return -1 if it's not found.

If you really want it to be plain text you can do the exact same thing but work with the ASCII representation of the UID bytes instead of the raw values - maybe as HEX. So your 8 byte records would become 18 bytes (16 bytes for 2 ASCII characters per UID byte, plus two for the \r\n line ending). Doing the conversion between bytes and text and back to bytes again though is wasteful if you don't really need it.

In case you're wondering why I recommended 0xFF as the deleted tag fill value and not 0x00 or anything else, it is simply because when you erase flash memory it is set to 0xFF. When you change the contents of a block on an SD card the block is read, it is modified in memory, the block is then erased (the whole lot set to 0xFF), then the modified block re-written back to the card. The act of erasing the block slightly damages it as it forces electrons through bits they don't really want to go through to make it all 0xFF. By setting your empty records to 0xFF, when it comes time to filling them again, the flash doesn't have to work as hard to erase that block since those bits are already in the erased state. Therefore the lifetime of the flash card should be extended slightly.


This is what I expect for val = 1
PORTD |= (1 << DATA)
As PORTD is the data pin on the shift register, it should get 00000001.

your deduction is correct and the code is correct -> remember this is the case for LSBFIRST. so "val = 0x01" should be sent out as "0b1000 0000", which is precisely what the code is doing.

!(val & (HIGH << 0))

the "!!" operator is often used to turn a logic value into either '1' or '0'.
the code for shiftout() can be greatly improved.


Adafruit DHT22 Library + Arduino Due not compiling?

There are several Arduino libraries for reading DHT22 and related DHT sensors.  The Adafruit DHT library does not compile for the Due since it uses AVR specific functions not available on ARM (Due).

For the Arduino Due use Rob Tillaart's DHTstable library available from his github page where you can download a zip file.  Note that his project also has a "DHTlib" library which does not support the Due.  There exists yet more DHT libraries which Rob has listed on the DHTLib page on arduino.cc.


Run Stepper with A4988 driver in highest resolution

You can drive the MS pins from the Arduino if you want, but there is no need.  You can just hook them all up to 5V.

Have you seen this page, there seems to be load of details that you might find relevant.
https://www.pololu.com/product/1182


Oscillating Output from Arduino Pins when not in use, why?

I'm thinking along the same lines as CrossRoads and dandavis above. Would you be able to post a circuit diagram? If you haven't grounded the input, it could be floating or picking up noise from the surrounding environment. A 5k pulldown resistor may fix the problem, depending on what your circuit looks like and the environment its in.


Dynamic Serial port selection and use without instantiating all Serialx objects

You can create an instance of HardwareSerial referencing a hardware
port that depends on a function parameter, as in

void initPort(uint8_t port) {
    switch (port) {
        case 0: {
            HardwareSerial serial(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            serial.begin(9600);
            break;
        }
        case 1:
            // etc...
    }
}

However, since only a local variable can be created in this manner, it
is not of much use. Ideally, you would want to have a global variable
for the serial port, and initialize it in initPort(), as

HardwareSerial serial;

void initPort(uint8_t port) {
    switch (port) {
        case 0:
            // Invoke fictional init() method.
            serial.init(&UBRR0H, &UBRR0L,
                     &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            // etc...
    }
    serial.begin(9600);
}

Alas, this is not possible, as the HardwareSerial class has no default
constructor. This means that binding the object to the hardware port can
only be done when it is constructed.

Short of modifying the Arduino core (adding a default constructor and an
init() method), the only option I can see is to have the global
variable be a pointer. Then, in initPort() the object is
instantiated while initializing the pointer. I tried this approach in
the example program below. There was a slight technical difficulty
though: since the object files from the core defining Serial,
Serail1, etc. will hopefully not be linked to the program, the
interrupt service routines defined therein must be also defined in the
sketch itself. And since an ISR cannot be bound to an interrupt at run
time, the ISRs have to be defined for all the ports, even though only
one ends up being actually used.

Here is my test program:

#include <HardwareSerial_private.h>

HardwareSerial *serial;

ISR(USART0_RX_vect) { serial->_rx_complete_irq(); }
ISR(USART1_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART2_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART3_RX_vect, ISR_ALIASOF(USART0_RX_vect));
ISR(USART0_UDRE_vect) { serial->_tx_udr_empty_irq(); }
ISR(USART1_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART2_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));
ISR(USART3_UDRE_vect, ISR_ALIASOF(USART0_UDRE_vect));

void initPort(uint8_t port)
{
    switch (port) {
        case 0:
            serial = new HardwareSerial(&UBRR0H, &UBRR0L,
                         &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
            break;
        case 1:
            serial = new HardwareSerial(&UBRR1H, &UBRR1L,
                         &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);
            break;
        case 2:
            serial = new HardwareSerial(&UBRR2H, &UBRR2L,
                         &UCSR2A, &UCSR2B, &UCSR2C, &UDR2);
            break;
        case 3:
            serial = new HardwareSerial(&UBRR3H, &UBRR3L,
                         &UCSR3A, &UCSR3B, &UCSR3C, &UDR3);
            break;
    }
    serial->begin(9600);
}

void setup() {
    initPort(0);
    serial->println("Hello, World!");
}

void loop(){}

It should be noted that the ISRs do not take that mush flash space.
There are actually only two of them, even though each is referenced four
times in the interrupt vector table.


Can't burn arduino bootloader to atmega8a with usbasp

Did you set the SLOW SCK jumper on the USBasp Programmer? Completely new ATMegas use the internal RC-Oscillator at a frequency of 8MHz, but the divide clock by 8 fuse is set too. That means that (before burning the fuses) the AVR is running at a clock frequency of 1MHz and the standard SCK clockrate of the USBasp is too high for this clock frequency. Therefore, you need to set the SLOW SCK jumper to get a lower SCK clockrate.


Try with something like:

#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);

    }

    void loop()
    {
        delay(2000);
        myservo.write(50);
        while(1);
    }

and let us know.
But more important: disconnect the servo +5V wire from Arduino and use another power supplier!!!


16*2 LCD display doesn't display my result

Your variables are int, which on an Arduino is a 2-byte signed type by default, and has a range of -32768 to 32767.

When you execute:

LineFreq = 25000000/countC;

is the result of the math a 2-byte int, or a 4-byte long? Regardless, you are possibly assigning a 4-byte value to an int.

You can declare LineFreq to be type long, and also append an L to the end of the constant value 25000000 to force long math, so that you have:

long LineFreq;
[...]
LineFreq = 25000000L/countC;


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

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

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


Store them with const byte PROGMEM with bit 0 as MSb and bit 7 as LSb per byte. E.g. 011100100101001010101011 would become const byte[] var PROGMEM {0x72, 0x52, 0xab}

Use the following macro to retrieve them (untested):

#define loadbit(mem, pos) ((pgm_read_byte(&(mem[pos / 8])) >> (7 - (pos % 8))) & 0x01)

So if you had const byte[] data PROGMEM {0x72, 0x52, 0xab}; you would call loadbit(data, 3) and it would return bit 3 starting with 0 on the left, i.e. 1.

Naturally if you needed more than one bit at a time there are probably situation-specific routines that could be used, but without knowing anything about the actual program the above will work.


Will unnecessary Serial.print() statements slow down my program?

No, there is no USART wasn't enabled so skip all prints. Everything must be done anyways (calls, conversions to strings, writes to UDR - USART Data Register). It is just not sent outside by USART and it doesn't have to wait for UDRE (USART Data Register Empty flag) so it might be slightly faster.

You can use similar technique as Loggers - log level variable and ifs (this can be changed runtime).

Or you can use macros:

// comment out this line, if you want to show logs:
#define NDEBUG

#ifdef NDEBUG
  #define LOG(...)
  #define LOGLN(...)
#else
  #define LOG(...) Serial.print(__VA_ARGS__)
  #define LOGLN(...) Serial.println(__VA_ARGS__)
#endif

And later:

LOG(F("Something: 0x"));
LOGLN(variable, HEX);

And how it looks after macro substitution? For code:

if (...) LOG(F("something")); else LOG(F("something else"));

With NDEBUG defined it's expanded to:

if (...) ; else ;

And without NDEBUG defined it's expanded to:

if (...) Serial.print(F("something")); else Serial.print(F("something else"));


How to upload an arduino sketch from java / processing?

I'd first would try to find out the right command when running on command line (cmd.exe).

When you launch an external command from Java which generates output, you should/must read the output (p.getInputStream(), p.getErrorStream()) using separate threads. Otherwise your application might hang for no obvious reason.


I translated you program to GNU as syntax, and it works as expected: I
get a 440 Hz square wave on digital pin 5. Here is the
translated program:

#include <avr/io.h>

; I'm too lazy to always type the full name of these macros
#define io(reg) _SFR_IO_ADDR(reg)
#define mem(reg) _SFR_MEM_ADDR(reg)

_a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

  ;wgm02..0 = 7 (fast pwm, top = ocr0a)
  ;cs02..0 = 4 (N=256)
  ;com0b1..0 = 2 (clear on compare match, set at bottom)
  ldi r16, 0b00100011
  sts mem(TCCR0A), r16
  ldi r16, 0b00001100
  sts mem(TCCR0B), r16
  ;ocr0a = _a to obtain 440Hz
  ldi r16, 141
  out io(OCR0A), r16
  ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
  ldi r16, 71
  out io(OCR0B), r16
  ;enable output at D5 aka oc0b aka Arduino pin 5
  sbi io(DDRD), 5
  loop:
  rjmp loop

As shown in my comment to your question, I suspect the problem is a
misunderstanding of the meaning of things like tccr0a and ocr0a.
In the translated version above, I admit I do not know what TCCR0A
and co. mean. And I need not to: I can treat these as opaque
identifiers, as the avr-libc recommends to always use them with the
macros _SFR_IO_ADDR() and _SFR_MEM_ADDR(), which provide the I/O
address and the data address of the register respectively.

I do not know how to use avra, so I cannot tell you how the get the I/O
or data address of a register. But there certainly must be a way. You
should always use the data address with sts and the I/O address with
out and sti.


Does ADC conversion to a voltage rely on the actual value of the +5 V pin?

The ADC inside the Arduino does not measure voltage, but rather a
voltage ratio. Namely the ratio from the voltage at the analog input
to the voltage at the Vref pin.

In the default configuration, the Vref pin is internally tied to the
+5 V line. You can select to use instead an internal reference as
Vref:

analogReference(INTERNAL);

This reference  is about 1.1 V, and is is quite immune to
fluctuations on the +5 V. The problem is that you cannot measure
voltages higher than the reference.

For your battery tester, if you want some sort of “absolute”
measurement, you could use the internal reference and a voltage divider
to ensure the measured voltage is below 1.1 V.

Edit: Another option which does not require a voltage divider is to
use Vcc as a reference to measure both the analog input and the
internal 1.1 V “bandgap“ reference. Measuring the 1.1 V
against Vcc is an indirect way to measure Vcc. This is not supported by
the Arduino core library, but you can do it by programming directly the
control registers of the ADC:

// Return the supply voltage in volts.
float read_vcc()
{
    const float V_BAND_GAP = 1.1;     // typical
    ADMUX  = _BV(REFS0)    // ref = Vcc
           | 14;           // channel 14 is the bandgap reference
    ADCSRA |= _BV(ADSC);   // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait until complete
    return V_BAND_GAP * 1024 / ADC;
}

Beware that the very first reading after boot may be bogus.


using UART bridge module to have serial communication through usb port of arduino nano

This is not possible - USB is not an ambidextrous protocol, rather there are distinct Host and Device roles, and while a few chips can switch-hit between them, the USB interface chips commonly used on Nano-style boards are strictly device only, and therefore cannot communicate with another USB device such as a USB-serial adapter.  There may well even be a duplicate here somewhere of a similar question having been asked before.

What you should probably do is just use the ATmega UART that interfaces to the USB chip, to talk to your external device directly (or through level translation and possibly inversion if it requires that).  The transmit side is no problem, however you will need to give some though to the receive side, as only one thing (the USB chip, or your external device) can drive that ATmega pin at a time.  Many of the official Arduino designs have a resistor there, which lets an external driver dominate over the on-board USB serial chip, but your board may or may not have that - if not, you may need to modify it.

And of course such a scheme requires that you disconnect the external device when uploading a new sketch via bootloader.

Another option would be instead of a traditional USB-serial converter, to use some sort of embedded USB host and have that convert to serial - the Kinetis KL25Z chip does this well, as does its close cousin on the Teensy-LC.  But at that point, you might as well just replace the Arduino Nano with a better chip having more pins, or even the ATmega328PB which has a second hardware UART.


Can I run 3 motion sensors with a voltage regulator?

Many internet sources like this one claim the HC-SR501 requires less than 50uA (or 0.00005 Amps).  Likely this is only in a quiet or quiescent state and current demand may increase initially when power is applied and when motion is detected.  Regardless, this is an insignificant fraction of a 2 Amp power supply.
Likely the Atmel 328p will require several times the total current of the 3 PIR sensors added together.  Still, the over all current of the described project (1 processor and 3 PIRs) is expected to be far less than half the capacity of a 2 Amp power supply.
It is suggested to keep the PIR to Arduino wires as short as possible to avoid noise.  It would be preferable they only be several inches (10s of centimeters).  And certainly not as long as several feet (a meter).


Burn bootloader to Arduino Uno using ARM-USB-OCD

Probably, but likely not easily

To program an AVR chip you likely want to use the AVR ISP protocol, which is not JTAG, but like JTAG is a synchronous serial protocol with a clock, a data line in each direction, and one additional control pin compared to the several mode/status pins of JTAG.

According to your link, the ARM-USB-OCD is based on an FT2232C USB interface chip.

avrdude documentation indicates that this is an interface it knows how to use, though it will likely take some study to figure out how.

The final question would be wiring - you'll need to figure out which JTAG-style signal names map to which FTDI functional pins, and how those should best be connected to AVR ISP pins in a way which avrdude can use.  Additionally, you'd have to make sure that any buffering between the FTDI chip and the pins is compatible with your needs, both in terms of data direction and voltage level.

Note that you can easily use any ATmega328-based Arduino as an ISP programmer for a same-voltage target - not really production worthy, but if you just need to move your project along today it's a handy option.


Connect a button to bluetooth board and comunicate with Android

For your project you can buy cheap Arduino Nano, or even Mini(programmer needed). For BT module buy HM10. It's cheap and it supports Bluetooth Low Energy.


Arduino Mega external interrupts fire randomly

Now, you write the following:

detachAllInterrupts();
delay(10);
...
... process any interrupts and/or button presses
...
delay(10);
attachAllInterrupts();

I understand that you put this stuff into the loop, such that the loop in effect looks like this:

void loop() {
    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();
}

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.

You should typically ENABLE the interrupts in the startup code, and then in the loop() you can have any Other processing you want, but not any processing referring to the interrupt processing.

The interrupt processing would take care of the button pressed etc. So - in the lane.lapdetected1() algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR lane.lapdetected1() algorithm?

What you would want to do, is to setup an interrupt in the setup(), which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
}

Thereby you would remove the detachAllInterrupts(), and all the way down to attachAllInterrupts() from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.


Too few arguments for multiple if statement conditions

The digitalWrite statement in the if statement needs a value to write. It looks like you meant digitalRead, since you're comparing the result to something and the other condition is a digitalRead.

 if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {

vs

 if ((digitalRead(blueLEDPin) == HIGH)  && (digitalRead(leverR) == HIGH)) {


Can I use WTV020 sound module as SD card reader?

It seems unlikely, for if you compare the schematic of the WTV020-SD (card reader part only) from the data sheet that you provided:

to the schematic of a bog standard SD card reader:

they are not the same. Instead of interfacing directly to the Arduino, as the standard SD card reader does, the WTV020-SD has additional logic, in the form of a WTV020SD-20S IC.

Therefore the code on the Arduino forums is highly unlikely to work.


What's the best way to control a USB-powered desk light

You have a couple options here. The main idea is that you're going to add a switch to the light's circuit and that switch will be controlled by the arduino. It's important that you keep the electronics for the light and the electronics for your arduino separate, 600mA will damage your arduino which no one wants. You can power the light and arduino from the same power supply, make sure it can handle the power draw though.

To actually switch the circuit you could use an NPN transistor as mentioned above, with the lamp's - terminal flowing into the C pin, an arduino GPIO pin connected to the B pin and the E pin grounded. When you set your arduino's pin HIGH the transistor will allow current to flow and light up the lamp.

Another option that actually physically separates the circuits is to use an opto-coupler. They're little IC's that serve this exact purpose. The have a light and a light sensitive transistor inside them, so when the light illuminates, the transistor allows current to flow. In your case, you would hook up an arduino pin to the + pin on the light side of the coupler and ground the - pin. Then connect your lamp in the same to the other side, +5v into the + pin on the transistor side and the lamp's positive terminal to the output pin. Again, when the arduino pin goes HIGH, the lamp will light up.


Using Arduino as contact to the world for linux box if app crashes

I will put our comments together in an answer.

You are overthinking the security issue. In my opinion, using RFID to reset the system is a bigger security thread, than using ssh the correct way. Normal RFID chips are susceptible to spoofing (copying an existing chip). Also the intruder could remove the RFID module to directly access the communication lines (depending on how much you will have accessible of the extra hardware). Also you can of course use the Serial interface of an Arduino to execute shell commands on your machine. You need a program on the machine to read the input and execute the commands (Majenko mentioned agetty for this). But is that really the best way? Using an Arduino here is a very hardware-ry way of solving a software issue. It is overly complex to do things this way and there are better options.

Instead you should really just use ssh with key-based authentication (disable password authentication). You can limit the ssh daemon to the local network (though, if you don't have configured corresponding port forwarding in your router, it isn't reachable from the internet either way), or - if you really want the additional security - to one specific device in your network. With a normal ssh key (I think 2048 bit is the standard), brute forcing is not a viable option for intruders. If you keep your private key save, there is very very little chance, that an intruder can get past that. You can also save the private key only on an USB stick, which you only use for resetting the machine. Also you can limit the commands, that the ssh user can execute, to only the resetting (like only allowing rebooting).

Depending on your actual security needs, you can choose, how far you want to go. I personally would just use key-based ssh limited to the local network. That should be plenty enough security and would also give you the possibility to access the machine, that is running in your home easier.

Or, if you really don't want to open ssh for the machine, you can write a simple watchdog program, that can run on the machine. Since the webapp is failing, you can write a simple python program (or any other language you like), which is regularly loading the webapp (how exactly depends largely on the webapp and the exact type of failure - may be a simple HTTP GET request) to check, if it is still alive. If the liveliness test fails for a defined number of times (let's say 3), it will reboot the machine.

This method does not require any access to the machine, but you will have to develop the liveliness test. Writing the program is then really simple.

All that said, it is not a good sign, that the app fails that often. You didn't write, what app that is, and what exactly fails. Maybe you are able to fix that issue directly. Or the developer of the app can, so maybe raise an issue on his platform (where the project is hosted).


How to use millis() in my code instead of delay()?

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


Is it possible to overload the digital pins for an Arduino?

As mentioned in the comments, you cannot power your robot from a 9V block battery. These are made for low power projects (like a smoke detector) and cannot provide enough current to drive even only the motors correctly. Using 2 of them does not really help much. You need to change to a different battery type. If you want to stay with alkalines, you could use six AA batteries or C cells, like jsotola suggested. But you might want to upgrade to a fitting LiPo/LiIon battery (in combination with a fitting battery charger module). That would give you enough power for all your needs, while being rechargable.

A different issue: It seems to be, that you provide all the components (sensors and motors) with power through the 5V pin of the Arduino. But especially with motors you can easily reach the current limitation of the voltage regulator on the Arduino. When drawing more current through it, than recommended, the regulator will go in emergency shutdown (with a genuine Arduino; with the cheap clones, the regulator will melt and be destroyed).

Instead you need to be sure, that the drawn current does not exceed the maximum current for the voltage regulator (depends also on the voltage provided). At least the motors should be provided with power parallel to the Arduino, so that the motor current will not flow through the Arduino. It is unclear, how you are controlling the motors. If you are using a motor shield, then look for the terminal for external power supply on it. Most motor shields have them. Depending on the batteries, you will use in future, and on motors and shield, you maybe an directly connect the battery voltage to the shield. Or you need to buy an extra (switching) voltage regulator, which brings the battery voltage down to 5V. In that case be sure, that the regulator can provide the needed current plus some overhead clearance.


48 MHz is a multiple of 16MHz. Why not just adjust the timing code to account?


This is the quick and dirty way, I would suggest re writing it to use arrays rather then having to declare all these variables and copy paste pinMode, read,writes if statments a bunch of times.

 int hallswitch1 = 1;  //Pin for Hall switch
 int hallswitch2 = 2;  //Pin for Hall switch
 int hallswitch3 = 4;  //Pin for Hall switch
 int hallswitch4 = 5;  //Pin for Hall switch

 int val1 = 0;       //Integer for reading Hall statu
 int val2 = 0;
 int val3 = 0;
 int val4 = 0;

 int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{

  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);

}

void loop() {

  val1 = digitalRead(hallswitch1);               //Read Hall pin status
  val2 = digitalRead(hallswitch2);               //Read Hall pin status
  val3 = digitalRead(hallswitch3);               //Read Hall pin status
  val4 = digitalRead(hallswitch4);               //Read Hall pin status

  if (val1 == HIGH) {digitalWrite(RELAY1, HIGH);}
  else {digitalWrite(RELAY1, LOW);}

  if (val2 == HIGH) {digitalWrite(RELAY2, HIGH);}
  else {digitalWrite(RELAY2, LOW);}

  if (val3 == HIGH) {digitalWrite(RELAY3, HIGH);}
  else {digitalWrite(RELAY3, LOW);}

  if (val4 == HIGH) {digitalWrite(RELAY4, HIGH);}
  else {digitalWrite(RELAY4, LOW);}

}


Where to store critical data in power outage situation on ESP8266

If you worry about the maximum number of write cycles, you could write the data to an SD card or some FRAM connected to the ESP8266, or you could send the data to a (web) server (if you have access to one) using WiFi. The server can then store the data.
If you really care about the data, you could do both. Having a backup is the only protection against catastrophic failure.


deprecated conversion from string constant to 'char*'

As is my wont, I'm going to provide a bit of background technical information into the whys and wherefores of this this error.

I'm going to inspect four different ways of initializing C strings and see what the differences between them are.  These are the four ways in question:

char *text = "This is some text";
char text[] = "This is some text";
const char *text = "This is some text";
const char text[] = "This is some text";

Now for this I am going to want to change the third letter "i" into an "o" to make it "Thos is some text".  That could, in all cases (you would think), be achieved by:

text[2] = 'o';

Now let's look at what each way of declaring the string does and how that text[2] = 'o'; statement would affect things.

First the most commonly seen way: char *text = "This is some text";.  What does this literally mean?  Well, in C, it literally means "Create a variable called text which is a read-write pointer to this string literal which is held in read-only (code) space.".  If you have the option -Wwrite-strings turned on then you get a warning as seen in the question above.

Basically that means "Warning: You have tried to make a variable that is read-write point to an area you can't write to".  If you try and then set the third character to "o" you would in fact be trying to write to a read-only area and things won't be nice.  On a traditional PC with Linux that results in:

  Segmentation Fault

Now the second one: char text[] = "This is some text";.  Literally, in C, that means "Create an array of type "char" and initialize it with the data "This is some text\0". The size of the array will be big enough to store the data".  So that actually allocates RAM and copies the value "This is some text\0" into it at runtime.  No warnings, no errors, perfectly valid.  And the right way to do it if you want to be able to edit the data.  Let's try running the command text[2] = 'o':

  Thos is some text

It worked, perfectly.  Good.

Now the third way: const char *text = "This is some text";.  Again the literal meaning: "Create a variable called "text" that is a read only pointer to this data in read only memory.".  Note that both the pointer and the data are now read-only.  No errors, no warnings. What happens if we try and run our test command?  Well, we can't.  The compiler is now intelligent and knows that we are trying to do something bad:

  error: assignment of read-only location ‘*(text + 2u)’

It won't even compile.  Trying to write to read-only memory is now protected because we have told the compiler that our pointer is to read-only memory.  Of course, it doesn't have to be pointing to read-only memory, but if you point it to read-write memory (RAM) that memory will still be protected from being written to by the compiler.

Finally the last form: const char text[] = "This is some text";.  Again, like before with [] it allocates an array in RAM and copies the data into it.  However, now this is a read-only array.  You can't write to it because the pointer to it is tagged as const.  Attempting to write to it results in:

  error: assignment of read-only location ‘*(text + 2u)’

So, a quick summary of where we are:

This form is completely invalid and should be avoided at all costs.  It opens the door to all sorts of bad things happening:

char *text = "This is some text";

This form is the right form if you are wanting to make the data editable:

char text[] = "This is some text";

This form is the right form if you want strings that won't be edited:

const char *text = "This is some text";

This form seems wasteful of RAM but it does have its uses.  Best forget it for now though.

const char text[] = "This is some text";


Building RS485 serial to USB adapter with digispark

There are some good books available to help. There is the Raspberry Pi cookbook and the Arduino cookbook. These will take you from the very beginning to the point where you can make your own designs and they will work.


Best way to add external power supply when main PSU is a solar charge controller?

Should I power the Arduino with the buck converter parallel to the same PSU (the 12V 20A Solar Charge Controller) I'm using for the pumps

Yes. However I wouldn't use a 9V buck regulator, but a 5V one and feed it to the 5V pin. That way you bypass the wasteful LDO on the Arduino, and when running from solar every bit of power saving you can muster helps.

and is it safe that way?

Yes, it's safe. As long as the buck regulator you are using is rated for the voltages in question.


It makes actually no sense to plug an USB-Controller via an Arduino to a PC. The direct way and using an autofire/macro /custom key programmer app is more efficient.

The Arduino UNO (with 32u4) can either replace an USB controller as demostrated in NicoHood HID library or
additionally act as an interface for controller with strange vendor specific plugs demostrated in UNOJOY and you can build your own Controller/interface out of nearly every old non usb controller by cutting the hardware specific plug (e.g. old Xbox) and attach to an UNO who acts as "interface" to the PC. Another example is a C64-Joystick to the PC
The other option for using an Arduino is interfacing with "old video game systems" . For some there are already more or less succesfull projects. When connecting the USB controller via an USB shield you have normally a high lag time due to the USB shield library, so the better approach is to cut the USB plug and directly interface with the Arduino.

Project with USB Host-shield:

C64 - with USB Joysticks

Project old Joystick to USB-PC:

NES controller to PC USB

Project Arduino as controller for NES/SNES:

UNO to NES/SNES

Info on the pinout/protocol cn be found in this page


Arduino processing serial comunication - losing data?

Ok, let's look at your Arduino program a bit at a time (for that is where the problem lies).

if (Serial.available()) { // If data is available to read,
    content = Serial.read();
}

If there is at least one character available in the buffer then read one character into the variable content.

if (content == 60) {

If the variable content is 60 (better to use '>' so you can see what it is), then ...

 for(int i=0; i<=7; i++) {
     str+=Serial.read();
 }

... read 8 characters from the serial buffer whether there are any characters in there or not.

That last bit is the crunch point.  You have an unknown number of characters in the buffer.  You had at least one, and that one you read into content.  You don't then check to see if there are the required 8 more characters available (or wait in each iteration of the loop for each character to actually arrive) before trying to read that character in.

If you take a moment to read the documentation on Serial Read you will see this:

  Returns

  the first byte of incoming serial data available (or -1 if no data is available) - int

The simplest fix is just to make your loop blocking so it waits for a character to arrive before reading it:

for(int i=0; i<=7; i++) {
     while (!Serial.available());  // Wait for a character to arrive
     str+=Serial.read();  // Read it
}


GPS Module Outputting Question Marks in Serial Window

No floating point for sprintf, it prints a '?'.

The functions sprintf, sscanf and the alike functions (snprintf and others) do not have floating point support for avr microcontrollers.

History

One of the first Arduino boards used the Atmega8 microcontroller with only 8k flash and 1k sram. It was important to be very memory efficient.
The gcc compiler did not automatically include the floating point support libraries for the sprintf functions, however it was easy to include them. Arduino decided not to include those extra libraries because they use extra memory.

Arduino has a preprocessor, compiler and linker that tries to only use code that is actually used. The sprintf does not know at compile time if floating point will be used, so it would have to include those extra floating point support libraries whether they were used or not.

Now it is 2018 and it is sadly still not included.

Workaround

The Serial.println functions can print floating point variables. They can however not print the output in scientific notation. It rounds the value that is printed to the nearest number.
The dtostrf() and dtostre() convert a float variable to text. The dtostre() is for scientific notation.
A variable of the float type can be cast to a integer.
The Arduino String object can handle a float.

Only float for avr microcontrollers, no double.

The avr microcontrollers are 8-bit microcontrollers. There is no floating point library for 64-bit double variables, only a library for 32-bit float variables.
That library is according to the IEEE standard and is extremely fast and optimized.