Serial communication between multiple devices (or Arduinos)

Almost any serial communication system can be "bent" to make a multi-master system - some easier than others.  The biggest problem you have is that of detecting and handling collisions.

However, if you can get away with a master->slave(s) system whereby one node on your bus makes requests to the slave nodes to get them to do something and respond with information then the whole system is far far simpler.

That is the normal way that I2C and SPI work, although I2C does have multi-master in its specification (though the Arduino API doesn't handle it AFAIK).

The industry standard way of making a UART able to communicate with multiple devices is through converting it to a standard bus system, such as EIA-422 or EIA-485 (AKA RS-422/RS-485). A half-duplex multi-drop EIA-485 is probably the simplest to arrange, and there are breakout boards for the Arduino that will convert UART to EIA-485.

It is possible (if you are clever) to make UARTs directly work as a multi-drop bus, but it requires a deeper understanding of UART control registers and electrical characteristics to emulate either an open-collector or tri-state TX pin on the slaves.

Of course, for all devices to operate on the same bus they must all conform to the specified operation of the bus. For instance, for EIA-485 all the slaves must have the ability to switch the transceiver into TX mode when needed, and react only to requests from the master and never send anything unsolicited. Just hooking random devices up to a bus with a transceiver is never going to work.

As far as USB goes - that is a single master (the PC) and multiple slaves (your keyboard, mouse, printer, scanner, webcam, Arduino, etc). Hubs are just a way of wiring them all together and routing the signals to the different peripherals at the right speeds.


That only works on an Arduino Yún (as described in this tutorial).


how to change variable when a button connected to pin 2 is pressed

Go here --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.

Those 3 are key.

Also, I wrote a buttonReader (debouncing) library here.

Sounds like you're a beginner, so check out Adafruit's tutorials here.

And lastly, I've compiled links to all my knowledge at the bottom of my article here.


nRF24L01+ packet loss caused by Arduino reading and communicating with sensors

You need to re-factor your program somewhat (I would imagine).  The nRF needs to be read at the same time as doing other things. That means interleaving it with your other operations.

There is a concept called a finite state machine which is the best way of writing a complex program like this. The idea is that nothing ever blocks, it just changes states. And all the time other things can be happening, such as reading the nRF24L01+ module.

I have a little tutorial on the Finite State Machine here:

https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/

If you use the Finite State Machine concept to run the reading of your sensors and the writing of data to the WiFi the nRF can then be polled constantly outside of the FSM constantly - maybe with an FSM of its own to deal with reception etc.

Things to remember:

Avoid delay(), certainly for anything longer than a couple of ms.
Avoid while(), for(), etc except for very short loops that finish quickly.
Any operation that takes more than a few ms to complete should be broken down into a number of sub-operations and coded as separate states of the FSM.


Serial string readout analyzed and logged onto an SD card

There are a number of ways that this can be accomplished.

If the string is always of a fixed length and the characters are always in the same place (this may require packing), then you could:

pull the required sections out, one character at a time, using the char array (i.e. string) index. However, in this case, this is rather long-winded and clumsy solution
Similar to above, use strncpy() to copy contiguous characters, see Given a starting and ending indices, how can I copy part of a string in C?
A more elegant method would be to use sprintf(), see How to copy a string into a char array in C++ without going over the buffer

Or you can use regular expressions (regexp) and patten matching. See How to read response from server using an Ethernet shield?
use sscanf, see Extract binary data from text string. Like Perl pack, not just regexp


The temperature sensor is likely included to keep the gyroscope and accelerometer better calibrated over the specified temperature range.  The temperature may not be the ambient temperature should the chip warm up.

The temperature sensor specifications are in section 6.3 on page 14 of the specification sheet indirectly pointed to in the question.

TEMPERATURE SENSOR
Range -40 to +85°C
Sensitivity Untrimmed 340 LSB/ºC
Temperature Offset 35ºC -521 LSB
Linearity Best fit straight line (-40°C to +85°C) ±1°C

So, when the chip is at 35C the chip temperature register is supposed to read about -521.  To convert that into C you need to make a calculation:

  chip_temperature = ((value_read + 521) + (35 * 340)) / 340

Simplified:

  chip_temperature = (value_read + 12421) / 340


The classic way of wiring up motors, including servos, is to provide them with separate power. The image below should clarify this:

The batteries (in this case) have the sole function of providing power to the servo motor. The "data" pin however goes to the Arduino.

The Arduino itself is powered by the USB cable in this example.

The important point is the blue wire - the shared ground wire. Both the Arduino and the servo (and batteries) must have a common ground.


The only metric you have is time. The only thing you can do is compare that time over iterations / task calls. The typical approach is to note the time at the start of a task "tick", and note it at the end. Then add the difference to the total for that task.
When you want to then look at usage percentages you can compare those totals to the total time the system has been running.
The total runtime is already done for you, in the form of millis(), so you don't need to worry about that.
Recording each task's total runtime in microseconds is simple enough, but of course will entail an overhead. That is unavoidable no matter what strategy you take. It's kind of quantum: the act of measuring changes the results.
If you treat your "idle" task the same as any other task (which is the normal way of doing things - the idle task is just a task that does nothing) then the sum of all the time counts for all the tasks = (within a certain granularity) the total amount of time your task scheduler has been running. The difference between that and the system runtime (millis()) is the proportion of the time your scheduler has been running compared to other things happening in loop().
Whether you compare to millis() or micros() for the system runtime is up to you. By storing micros() per task you're getting a reasonable resolution for each tasks's runtime (but with a limit to how long before it wraps - but you can handle that in software by carrying over to another lower resolution counter if you want), but you can then discard some of that resolution when doing your calculations if you don't need it at the time.
Estimating runtime in a co-operative multitasking system like this is never good, and often not bothered with because of that. It's always a guestimate with the results being skewed by the measuring, since the measuring is synchronous with the execution of the tasks.
In a proper context-switching multitasking system you would normally operate on the number of "ticks" of the system rather on time. That is, simply count 1 each time a task is switched in by the context switcher. Since each task has a fixed runtime controlled by the granularity of the scheduler it's then trivial to know that task X has been running for X/TOTAL_TICKS % of the time. Any calculations will be themselves done in a task - maybe the idle task, or a system accounting task.


unexpected change of ADC value with multiple voltage dividers (thermistors and pot)

#define meatTempPin A0
#define airTempPin A1

Your code says A0,A1 but the circuit and picture of the wires say A0,A2.

Since A1 doesn't appear to be connected, as you scan things, the ADC could be sampling and holding some voltage from the prior conversion of potPin.

Try this instead:

#define meatTempPin A0
#define airTempPin A2


Your problem is that you are treating both signal separately. Instead you need to think about the events of turning LEDs on and off and where they lie on a combined timeline:

     0    100   200   300   400   500   600   700   800   900  1000
     |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
     ^  ^                       ^  ^
  1 on  2 off                2 on  1 off
  1: ooooooooooooooooooooooooooooooo
  2: oooo                       oooooooooooooooooooooooooooooooooo

You see how I have looped the time around so that the turning off of the second signal, which would normally come at 1050ms, in fact comes at 50ms. By just working in a single 1000ms block of time as a loop things become much simpler.

You can do it now with just a simple set of delays, now you have it laid out in a single timeline like that:

void loop() {
    digitalWrite(led1, HIGH);
    delay(50);
    digitalWrite(led2, LOW);
    delay(400);
    digitalWrite(led2, HIGH);
    delay(50);
    digitalWrite(led1, LOW);
    delay(500);
}

All the delay() calls add up to 1000ms and it keeps looping around.

If you want to make it non-blocking you should set it up with a small finite state machine. There are 4 steady states which are the four spaces between the events on the timeline. There are 4 transitions, which are the events on the timeline.  So you:

Start in state 0 with both LEDs on (which is how they are at the start of the timeline).

0: When 50ms have passed turn off LED 2 and move to state 1.
1: When 400ms have passed turn on LED 2 and move to state 2.
2: When 50ms have passed turn off LED 1 and move to state 3.
3: When 500ms have passed turn on LED 1 and move to state 0.


Reading states of multiple toggle switches

The problem was two pronged---both the copy/paste error that @Gerben pointed out, as well as the incorrect if-else statements that @BrettAM pointed out. Below is the working code:

const int  switchOnePin = 2;    // digital in 2 (pin the switch one is attached to)
const int  switchTwoPin = 3;    // digital in 3 (pin the switch two is attached to)
const int  switchThreePin = 4;  // digital in 4 (pin the switch three is attached to)

int switchOneState = 0;         // current state of the switch
int lastSwitchOneState = 0;     // previous state of the switch

int switchTwoState = 0;
int lastSwitchTwoState = 0;

int switchThreeState = 0;
int lastSwitchThreeState = 0;

void setup() {
    //initialize serial communication at 9600 bits per second:
    Serial.begin(9600);

    int switchOneState = 0;         // current state of the switch
    int lastSwitchOneState = 0;     // previous state of the switch switch pins as an input
    pinMode(switchOnePin, INPUT);
    pinMode(switchTwoPin, INPUT);
    pinMode(switchThreePin, INPUT);
}

void loop() {
    // read the switch input pins:
    switchOneState   = digitalRead(switchOnePin);
    switchTwoState   = digitalRead(switchTwoPin);
    switchThreeState = digitalRead(switchThreePin);

    // compare the switchState to its previous state
    if (switchOneState != lastSwitchOneState) {
        // if the state has changed, increment the counter
        if (switchOneState == HIGH) {
        // if the current state is HIGH then the button
        // went from off to on:
            Serial.println("Switch one is on");
        } else {
            // if the current state is LOW then the button
            // went from on to off:
            Serial.println("Switch one is off");
        }
    }

    if (switchTwoState != lastSwitchTwoState) {
        if (switchTwoState == HIGH) {
            Serial.println("Switch two is on");
        } else {
            Serial.println("Switch two is off");
        }
    }

    if (switchThreeState != lastSwitchThreeState) {
        if (switchThreeState == HIGH) {
            Serial.println("Switch three is on");
        } else {
            Serial.println("Switch thre is off");
        }
    }

    // Delay a little bit to avoid bouncing
    delay(50);

    // save the current state as the last state,
    //for next time through the loop
    lastSwitchOneState   = switchOneState;
    lastSwitchTwoState   = switchTwoState;
    lastSwitchThreeState = switchThreeState;
}


Solution for if this occurs on a known working ESP-32-cam with PSRAM (i.e. example sketch with face recognition works ok).
If you're using anything other than PIX_FORMAT_JPEG, try reducing xclk_freq_hz.
In my case, it suddenly worked fine with PIX_FORMAT_RGB888, FRAMESIZE_VGA and xclk_freq_hz = 5000000 (4x lower).
( @Vraj P, this might not apply directly to what you found your problem was, but this post gets seen by many searching for this problem. Thanks!).


Is it possible to connect many arduino uno in one pc?

Yes, you can connect multiple Arduino UNO (USB) boards to a single PC. There's a simple way and a more advanced way to manage it.

The simple way is, having multiple boards plugged in, but using only one Arduino Software IDE to control one board at a time. (IDE = Integrated Development Environment. Some elements of the Arduino system use non-standard technical terms.) Use the Tools > Port menu to select which one of the attached boards to control. The selected board type and port appear in the lower right status bar.

A more advanced way to manage multiple boards, is to open multiple Arduino Software IDE instances -- each instance has its own independent Tools > Port setting. You could then edit, verify, and upload two different "sketches" (programs) to two different boards, without losing your place and without having to constantly change the Tools > Port setting. This would be convenient if you were developing a communications protocol between two or more boards.

This multiple-ports technique won't work unless you launch another instance of the Arduino Software IDE, without closing the first one. It isn't enough to use the File menu to open another window, because then you just get another window that shares the same Tools > Ports setting. Changing the ports setting on one window, changes the setting on all of the windows that belong to that instance. To support multiple boards at the same time, you have to actually launch the Arduino Software IDE again, without closing the first one, to create a second instance.

Usually you'd expect each window would represent a unique document, and they'd all be related to the application. But Arduino Software IDE has a hidden dependency between its windows. Whenever you restart the IDE, that opens a new and invisible instance of the IDE, where it remembers the board and port settings. If you use the File menu to open a new window, that new window is still part of the same IDE. So changing the Tools > Port setting on one window, changes that setting for all of the windows that belong to that instance of the IDE.

But if you restart the Arduino Software IDE (e.g. Windows Start Menu > Arduino-1.6.0), without closing the previously opened IDE, then you get a second instance. If you pay attention to the port setting visible on the lower right status bar of each window, you can distinguish which windows belong to which IDE instance.

Each time you launch the Arduino Software IDE, you start a new instance of the software, that can talk to one board. Each instance of the IDE can have an unlimited number of windows, but they all share the same Tools > Port setting. If you re-launch the Arduino Software IDE again without closing it first, then you get a second instance that can have a different Tools > Port setting, and thus control another board at the same time.

Verified on Windows 7, Arduino Software IDE 1.6.0, with two Arduino UNO revision R2 boards (firmware rev 0001), Arduino device driver 1.0.0.0.


Powering Arduino and L293D with the same Power Supply

I don't see any problem. You used the Vin for 9V, and shared grounds.
I suggest using a bypass capacitor (typically 0.1 uF) for the L293D VCC, but I don't have experience with using a L293D.
Also, you need to check if the battery can deliver enough current for both motors and the Arduino.


ESP8266 returns whatever is sent through Arduino serial

I noticed when testing my ESP8266 using the Arduino IDE serial console that ending with a CR repeated what was sent, a NL executed the command and combination of the two yielded a combination of the two behaviours. This could have just been the firmware on mine (it seemed to be non-standard), but it is possible that the behaviour is similar on yours. If you are using CR & NL, it would explain repetition. However, I can't explain commands not executing, or executing abnormally.


I keep getting an exit status 1 expected primary-expression before ')' token for my code

This int ctr = () should probably be int ctr = 0

The for loop syntax is incorrect, see: https://www.tutorialspoint.com/cplusplus/cpp_for_loop.htm

The first for loop needs a } at the end.


Converting code for ATTINY85 to ATMEGA2560. Pin change interupts

Each processor has different registers, things that control stuff like interrupts, input and output. I would not expect code written for one processor, especially if it directly accesses the registers, to work on another processor.

You would need to look at the datasheet for the Atmega2560 and see how to control its pin change interrupts.


How can I use both ultrasonic and IR sensor and ultrasonic sensor at ones with Arduino

Arduinos don't do multithreading. There are a number of attempts at implementing such things, but they're a waste of time and resources.
Instead you need to get into the habit of two things:

Write non-blocking code
Make use of the internal hardware peripherals when possible

The motors, using the hardware PWM, are very much "fire and forget" - set them going and you can forget about them until you want to change their speed or direction.
Ultrasonic sensors can be made both more accurate and more "in the background" by using the Input Capture peripheral of the Arduino.
IR sensors (I assume you mean proximity sensors) are usually either just like a button or a potentiometer - you just read them when you want to know what it's doing.
It's your task to learn how to fit all that together into a single program that reacts to the inputs in the way you want and control the motors in the right way.


Are my arrays stored in sram or in Flash?

It's stored in both the FLASH and SRAM because it's initialized array. To store in FLASH only you need use PROGMEM attribute.

const unsigned PROGMEM char g1[]= ...

You cannot access directly but using memcpy_P() function.


Can I force Arduino not to be powered by USB?

The best way of doing this, if you want your USB connection to still work, is to remove the P-channel MOSFET T1 from the board.

You can't just disconnect the power from the USB port since that power connection goes directly to UVCC on the ATMega16U2 chip. That is used to power the internal USB peripheral (it goes to a 3.3V regulator inside the chip) and without it the USB interface won't have power.

The USB power is connected to the main 5V rail through that transistor, so if you remove that transistor the 5V from the USB remains connected to the ATMega16U2, but is no longer connected to the rest of the circuit.


Want to add an LCD display screen for the output motor

From this instructable:

// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print(" **Text for line 1 of LCD**");
  lcd.setCursor(0, 1);
  lcd.print(" **Text for line 2 of LCD**");
  // THE REST OF YOUR SETUP
}

void loop() {
    if (digitalRead(13) == HIGH) {
        // I assume this is the motor going forward
        lcd.print("motor 1 run forward");
    }
}


How to set up one second interrupt/ISR for ds3231 RTC

This answer addresses the original question of why the interrupts didn't work. I happened to have a DS3231 lying around so I made up a test.

Interrupt vs pin number

First, this is wrong in your code:

attachInterrupt(rtcTimerIntPin, rtc_interrupt, RISING);

You need an interrupt number, not a pin number. This is correct:

  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);

I also made it a CHANGE interrupt so you get both the rising and falling pulse.

Pull-up resistor

Next, the 1 Hz output needs a pull-up resistor, so you should add that or make it INPUT_PULLUP like this:

  pinMode (rtcTimerIntPin, INPUT_PULLUP);

Testing

I used this library from Adafruit.

Adapting one of their examples, and putting in your interrupt code (with my modifications), it worked!

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

const byte rtcTimerIntPin = 2;

volatile byte flag = false;

void rtc_interrupt ()
{
  flag = true;
}  // end of rtc_interrupt

void setup () {

  Serial.begin(115200);

  while (!Serial); // for Leonardo/Micro/Zero

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  // enable the 1 Hz output
  rtc.writeSqwPinMode (DS3231_SquareWave1Hz);

  // set up to handle interrupt from 1 Hz pin
  pinMode (LED_BUILTIN, OUTPUT);
  pinMode (rtcTimerIntPin, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (rtcTimerIntPin), rtc_interrupt, CHANGE);
}

void loop () {
  if (flag) {
    digitalWrite(LED_BUILTIN, HIGH);    // flash the led
    delay(100);                         // wait a little bit
    digitalWrite(LED_BUILTIN, LOW);     // turn off led
    flag =  false;                      // clear the flag until timer sets it again
  }
}


Your code is somewhat confusing, probably because it has too many
variables. For doing what you describe, the program only needs to
remember two things:

is the relay in the ON state or in the OFF state?
when was the last time the relay changed state?

These can be represented as follows:

bool relay_is_on = false;
unsigned long last_relay_change = 0;

Then, I recommend you use descriptive names for your variables and
constants. Calling a constant threeSeconds is not useful. It has no
added value over just typing 3000. Having the constant named
RELAY_ON_TIME makes it a lot clearer what it is intended for. It is a
common convention to name the constants with all caps to make them stand
out relative to variables:

const uint8_t RELAY_PIN = ...;
const unsigned long RELAY_ON_TIME  =  3000;  //  3 s ON
const unsigned long RELAY_OFF_TIME = 10000;  // 10 s OFF

With this in place, periodically switching the relay on and off can be
achieved as follows:

void loop()
{
    unsigned long now = millis();
    if (relay_is_on && now - last_relay_change >= RELAY_ON_TIME) {
        // Turn off.
        digitalWrite(RELAY_PIN, LOW);
        relay_is_on = false;
        last_relay_change = now;
    }
    if (!relay_is_on && now - last_relay_change >= RELAY_OFF_TIME) {
        // Turn on.
        digitalWrite(RELAY_PIN, HIGH);
        relay_is_on = true;
        last_relay_change = now;
    }
}


Connecting an Arduino to a telephone line?

You can interface arduino to telephone line using MT8870D chip. This IC can decode DTMF tones. Below is a reference schematic from the datasheet.

Another popular design floating on the internet is below:

There are pre-build modules available from futurelec :

You can use Holtek HT9200 IC to encode DTMF that can be interfaced with Arduino. Below is the reference schematic from its datasheet.


Does SMS format depend on the sender's mobile?

If you're not trying to capture the mobile number or whatever SMS text was sent, but only react to specific SMS messages, then don't try to parse the whole message, but design the protocol between any arbitrary phone and your Arduino to be detectable independent of everything else, e.g.:

#L 5 on        ; set an LED state

#M 3 137       ; set a motor speed


I think you need arduino motor shield.

Click Here

Just click on above link, you find a good tutorial about arduino motor shield. I hope it might be helpful.


else if is ignored if not Serial.println anything before

Even though you read until \n, that just controls the ending of your buffered string.  It does not control it's start.  There may be some garbage before the command that you have not cut out.  In other words, I suggest you check if the string endsWith as opposed to == the command string.
As for what noise could be causing garbage or why activity on the tx side of the serial cleaned it up, i do not know.  Heck something might just be weird enough in the wiring that '2' is just the set of bits needed to aggravate it.


Arduino C, Led > binary alternative all lights

Code review (one possible solution can be found below)

Absolute numbers in the code, like 15 as the limit for the random numbers are generally considered harmful. It would be better to give all absolute numbers a constantsname and use these throughout. The OP code did not use the constants for the pins, for instance.
Writing similar pieces of code in a row makes maintenance hard. Therefore, group similar items in any kind of list, like an array, and iterate over them.
Functions should have expressive names clearly stating what is going on inside.
Functions should be short and concise, ideally having only a few lines.

Try something along these lines:

// setting the number of bits to analyze, corresponding pins and corresponding powers of two.
// the latter is here for instructional purposes although it is redundant.
const int numberOfBits = 4;
const int randLimit = 15;   // 2^(1+numberOfBits)-1 actually;
int ledPins[numberOfBits] = {13, 8, 12, 7};
int bitValue[numberOfBits] = {8, 4, 2, 1}; // the powers of two

void turnOffAllLeds ()
{
  Serial.println ("turning all off");
  for (int i = 0; i < numberOfBits; i++)
  {
    digitalWrite (ledPins[i], LOW);
  }
}

void selectivelyTurnOnLeds(int value)
{
  turnOffAllLeds ();

  // now for each bit, check if it is set in the value, if yes: turn on corresponding led
  for (int i = 0; i < numberOfBits; i++)
  {
    if ((value & bitValue[i]) > 0)
    {
      digitalWrite (ledPins[i], HIGH);
    }
  }
}

void setup()
{
  for (int i = 0; i < numberOfBits; i++)
  {
    pinMode (ledPins[i], OUTPUT);
  }
}

void loop()
{
  selectivelyTurnOnLeds (random (randLimit));
  delay (1000);
}

P.S. When posting a question, please also post what your code is supposed to do. If it were not for a lazy prechristmas workday, I would not have taken the time to reverse engineer your code.


Adafruit GPS module with SoftwareSerial affecting servo signals

The bad news is that you are using the absolute worst libraries (SoftwareSerial and Adafruit_GPS), and your program structure is based on the awful Adafruit_GPS example.

The good news is that there are much better alternatives: NeoSWSerial and NeoGPS.  Still, there's no doubt that you are near the limits of this processor, especially with Wire and timer-based Servos.  It can be an "interesting challenge" or a "beginner's nightmare."

Suggestions:

1) Consider using the HardwareSerial object, Serial, for the GPS interface.  Your excerpt does not show what Serial is currently used for, but if it's debug print statements... don't.  Instead, use a software serial port for debug statements (use a serial-to-USB adapter on those pins to connect it to your PC).  This would have a tremendous impact.

2) If you really really can't use Serial for the GPS (are you sure???), consider using an AltSoftSerial instance on pins 8 & 9, as this is much better than the dreaded SoftwareSerial.  Next best is NeoSWSerial on any pins, including 4&3 that you are using now.  There is absolutely no reason to shoot yourself in the foot with SoftwareSerial.

3) As other's have commented, use HW PWM... let the machine do the work for you.

4) Consider using the faster and smaller NeoGPS library.  And restructure your program to look like the NeoGPS example programs, because their sequencing is much more efficient.  The Adafruit_GPS example uses a timer interrupt... to read a character from the input buffer... that was stored by a SoftwareSerial interrupt... that was on for the entire character time of ~1ms.  What a phenomenal waste!

5) Use interrupt-driven GPS parsing.  All three Neo__Serial libraries (HW, IC and SW) allow NeoGPS to handle the GPS characters during the rx interrupt, avoiding character loss because the port was not read in time (input buffer overflow).  And because just a little work is performed on each character, there is no big chunk of processing when a sentence is complete.  This also uses half the interrupts and saves copying the characters multiple times, in and out of the serial input buffer... into the Adafruit double-buffered sentences, where it gets searched multiple times with strcmp and strchr.  Ugh.  No, I meant to say UGH!

6) NeoGPS will also free up hundreds of bytes of RAM, which you may be able to trade for some more speed, elsewhere.

It's definitely a tight squeeze.  Either reallocate your pins and use better libraries, or get a bigger hammer.      :-)


From the manual:
http://dmx.ohaus.com/WorkArea/showcontent.aspx?id=4294974226

  The balance will return “ES” for invalid commands.

Check to make sure you're using the correct serial parameters that the RX line is wired correctly.


Loops fail after ~5 minutes when making two API calls every 10 seconds using WiFi client

You keep calling new to allocate memory but you never free it.  This is a memory leak and eventually you run out.  Instead of constantly creating new arrays, why don't you make those global or static.  Or even just local arrays if you don't need them to be persistent.  On a microcontroller you really don't want to be using new unless absolutely necessary.


Unexpected value change of 2nd Potentiometer

As I was having chat with @Maxmilian Gerhardt he suggested to check the voltage of pot 2 so when I checked I was getting 0 volt So he Suggested me there may be a loose connection or something with the beadboard.

So This was a workaround :

Thnx for the help @Maxmilian Gerhardt


I have not actually interacted with the debian packages, but If I'm reading this right, this how they are organized:

arduino: The whole java IDE and avr code libraries

arduino-core: the libraries and code that comes with arduino to be compiled for avr

arduino-mk: a makefile for compiling arduino code without the IDE (but no code)

The normal arduino package has a command line interface, but the code for this is (currently) very closely tied to the java GUI code and cannot be used without the whole thing being installed. To make using the raw atmel avr tools easier, the makefile is available; However, the makefile does not include all of the cpp libraries that come packaged with the arduino installation that a normal arduino sketch would reference (Arduino.h, Servo, SPI, etc). The arduino-core package exists to bring in all this supporting code.

I imagine it is done with these three packages so if you already have arduino installed, the makefile will not bring a second copy of all the libraries with it.

The makefile is a configuration for the gnu make software. There is some information on the specific usage of the arduino makefile on its github page here


There are several things here:

Increase your delay, you don't want to be sending the data that often, even if you only increase it to 100-200ms, although I'd recommend making it in the order of 1-30 seconds.
You're reading in analog inputs which will be in the range of 0-1023 but your serial reads are in byte format (which will actually be reading the first three bytes (or the first three DIGITS of the first reading). More about this below.
You're reading in three arbitrary bytes, you're not identifying them at all, you have no idea what you're reading (other than by testing for a 1ms delay--which over XBee is not practical).

You have two options, transmit the data as ASCII (not a good idea IMHO), pre-pending some identifier such that:

1:259
2:0
3:1019

or even some other delimiter:

259:0:1019

But I would probably lean towards byte encoding:

byte0 :0xEA    // just some custom header for yourself
byte1H:0x01
byte1L:0x03
byte2H:0x00
byte2L:0x00
byte3H:0x03
byte3L:0xFB
byte4 :0xXX    // checksum

Or you could map the inputs down to a range of 0-255 for single byte transmission.

Next you'll need to work on receiving the data, how you do that is going to depend on how you encode the stream.

edit: I've removed the code sample that was here and replaced it with two working sketches below.

I have two XBees, running in AT mode, mine are Series 2, but programatically I THINK they are the same. If not, you'll have to tweak these, but I'm pretty sure you'll be right.

What we have are two apps, the first is the "SENDING" app, it takes three arbitrary values, they are: minutes (0-60) the micro has been running, seconds (0-60) the micro has been running, and 100 (it was random, and you can put that back if you want). Also, if you comment out the #define TESTAPP instead of using these values, it can pull three analog values from A0-A2 instead. (If you change it in the receiving app, you could have three LEDS on Pulse Width channels and vary the brightness).

/* * * * * * * */

XBEE SENDER (131)

#define TESTAPP        // Just serial data based on time

#define PACKETLENGTH   7
#define LED            13

/* * * * * * * */

void setup(){
    Serial.begin(9600);
    Serial.println("\nSender");
    randomSeed(analogRead(0));
    pinMode(LED,OUTPUT);
}

unsigned long m1 = 0;
unsigned long m2 = 0;

void loop(){
    m1 = millis()/1000;
    if(m2 != m1){
        m2 = m1;

#ifdef TESTAPP
        uint8_t  s = m1 % 60;           // how many seconds on millis()
        m1 /= 60;                       // now we're working with minutes
        uint8_t  m = m1 % 60;           // how manu minutes on millis()
        uint8_t  r = 100; //random(256);
        Serial.print("x.x");            // this is just pre-pended data for testing
        Serial.print('<');
        Serial.write(m);
        Serial.print('-');
        Serial.write(s);
        Serial.print('-');
        Serial.write(r);
        Serial.print(">  x-x");        // we want to ignore these chars
#else
        Serial.print('<');
        Serial.write(map(analogRead(A0),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A1),0,1023,0,255));
        Serial.print('-');
        Serial.write(map(analogRead(A2),0,1023,0,255));
        Serial.print('>');
#endif
        digitalWrite(LED,!digitalRead(LED));  // toggle the LED everytime we're here
    }
    // do other stuff here...
}

You'll notice garbage characters around the data we are transporting, this is to demonstrate cycling through all serial communications to arrive at the 7 particular characters we need. That's done in the next app, the receiver:

/* * * * * * * * */

XBEE RECEIVER (121)

#define TESTAPP  // if you attach 3 LEDS to 9, 10 and 11, the remove this line.

//#define DEBUG  // uncomment this line to see all the data stream coming in

#define PACKETLENGTH  7

/* * * * * * * * */

int LED[3]={9, 10, 11};

void setup(){
  Serial.begin(9600);
  Serial.println("\nReceiver");
}

byte  buffer[PACKETLENGTH]; // what holds our serial data
byte  idx         = 0;      // the index for the buffer character being written
byte  validBuffer = 0;      // flag to tell us if we're ready to go

void loop(){
  if(validBuffer){
      #ifdef TESTAPP
          // we're just going to print it out in a different format
          validBuffer=0;
          #ifdef DEBUG
              Serial.print('\n');
          #endif
          Serial.print("Data: (");
          if (buffer[1]<10) Serial.print("0");
          Serial.print(buffer[1]);
          Serial.print(":");
          if (buffer[3]<10) Serial.print("0");
          Serial.print(buffer[3]);
          Serial.print(") (");
          Serial.print(buffer[5]);
          Serial.println(")");
      #else
          // this is the more practical side of things
          // instead of serial.printing, change the brightness
          // on three attached LEDs via PWM Pins (9, 10, 11)
          analogWrite(LED[0],buffer[1]);
          analogWrite(LED[1],buffer[3]);
          analogWrite(LED[2],buffer[5]);
      #endif
      memset(buffer, 0, PACKETLENGTH);  // we've used the data, clear it out
      idx = 0;                          // and reset the index marker
  }
}

// This is where the real magic is done. We have a buffer of
// PACKETLENGTH that takes in all Serial data and waits until
// it finds PACKETLENGTH characters in the format we're after
// Probably not the best method, but it would be unlikely to
// stumble across this pattern, although not impossible :)
// use at your own risk

void serialEvent(){
    if(validBuffer) return; //we don't want to process new Serial
                            //until we've processed the buffer
    buffer[idx] = Serial.read();
        #ifdef DEBUG
        Serial.write(buffer[idx]);
        #endif

    if (++idx==PACKETLENGTH){
        // we have enough bytes for testing, this next part could be handled better
        if(  buffer[0]=='<' &&
             buffer[2]=='-' &&
             buffer[4]=='-' &&
             buffer[6]=='>' ) { // we have a valid data packet
               validBuffer=1;
        } else {    // we don't have valid data yet, but keep
                    // what we have, shift it all over one byte and
                    // we'll check again once the next byte is received
            memmove(buffer, buffer + 1, PACKETLENGTH-1);
        }
        idx--;
    }
}


See compiled assembly output (Visual Micro)

Turn on Verbose Compiling in the Arduino IDE and you will see all the intermediate file names (they are done in a temporary folder).

For example:

/home/nick/Development/arduino-1.6.7/arduino-builder -dump-prefs -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
/home/nick/Development/arduino-1.6.7/arduino-builder -compile -logger=machine -hardware "/home/nick/Development/arduino-1.6.7/hardware" -hardware "/home/nick/.arduino15/packages" -hardware "/home/nick/Arduino/hardware" -tools "/home/nick/Development/arduino-1.6.7/tools-builder" -tools "/home/nick/Development/arduino-1.6.7/hardware/tools/avr" -tools "/home/nick/.arduino15/packages" -built-in-libraries "/home/nick/Development/arduino-1.6.7/libraries" -libraries "/home/nick/Arduino/libraries" -fqbn=arduino:avr:uno -ide-version=10607 -build-path "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -warnings=default -prefs=build.warn_data_percentage=75 -verbose "/tmp/arduino_1cdca0d02fcf3112936d1438c170697d/sketch_mar03b.ino"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/home/nick/Arduino/libraries/PID_v1/PID_v1.cpp" -o "/dev/null"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10607 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/cores/arduino" "-I/home/nick/Development/arduino-1.6.7/hardware/arduino/avr/variants/standard" "-I/home/nick/Arduino/libraries/PID_v1" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp" -o "/dev/null"
...
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/main.cpp.o"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-ar" rcs  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/new.cpp.o"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-gcc"  -Os -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch/sketch_mar03b.ino.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/libraries/PID_v1/PID_v1.cpp.o" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/core/core.a" "-L/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp" -lm
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.eep"
"/home/nick/Development/arduino-1.6.7/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.elf" "/tmp/build1cdca0d02fcf3112936d1438c170697d.tmp/sketch_mar03b.ino.hex"
Using library PID_v1 in folder: /home/nick/Arduino/libraries/PID_v1 (legacy)

Sketch uses 6,484 bytes (20%) of program storage space. Maximum is 32,256 bytes.
Global variables use 285 bytes (13%) of dynamic memory, leaving 1,763 bytes for local variables. Maximum is 2,048 bytes.

Of interest are the last couple - the xxx.elf file and the xxx.hex file (where xxx is your sketch name).

The xxx.hex file is what is uploaded to your Arduino (well, it is decoded by Avrdude).

The xxx.elf file can be used to get assembly output, like this:

avr-objdump -Sz xxx.elf

That outputs to the screen. I usually output to a file:

avr-objdump -Sz xxx.elf > /tmp/avr_dump.txt

Example output:

void setup() {
      ec:   0f 93           push    r16
      ee:   1f 93           push    r17
  Setpoint = 100;
      f0:   80 e0           ldi r24, 0x00   ; 0
      f2:   90 e0           ldi r25, 0x00   ; 0
      f4:   a8 ec           ldi r26, 0xC8   ; 200
      f6:   b2 e4           ldi r27, 0x42   ; 66
      f8:   80 93 73 01     sts 0x0173, r24
      fc:   90 93 74 01     sts 0x0174, r25
     100:   a0 93 75 01     sts 0x0175, r26
     104:   b0 93 76 01     sts 0x0176, r27
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
     108:   61 e0           ldi r22, 0x01   ; 1
     10a:   70 e0           ldi r23, 0x00   ; 0
     10c:   82 e3           ldi r24, 0x32   ; 50
     10e:   91 e0           ldi r25, 0x01   ; 1
     110:   0e 94 04 04     call    0x808   ; 0x808 <_ZN3PID7SetModeEi>

In this particular  case Setpoint was a double so it took 8 instructions to load a literal into it.


avrdude: ser_open(): can't open device "\\.\COM4": Access denied

I think you used "Eclipse" and "Arduino" at the same time. so, I guess that a "com4 Port" conflict has occurred and the upload could not was done.

restart  your computer and try to open "Arduino" first and upload. not open "Eclipse" at the same time.


Confusion with storage of declared variables and volatile

That's just plain incorrect.

The volatile keyword tells the compiler that the value of that variable may change at any time, and that therefore it must re-read the value every time you use it in your code.

If you don't use volatile, the compiler may choose to make an optimisation.

Consider this code:

int b = 7;
a = b + b;

The compiler can see that 'b' is always 7 -- it is assigned the value 7 and nobody ever changes it.  The compiler may choose to optimise this to the equivalent of

a = 14;

But if you do this:

volatile int b = 7;
a = b + b;

then the compiler MUST read b twice from memory.

Why would you want to do that?  Perhaps you have an interrupt which might change the value of b.  Perhaps your interrupt changes the value of 'b' every time you press a button.  You need the code to really check the value of b every time it calculates a, and not rely on it always being 7.

Here is a fuller explanation.


Is it possible to use Wi-Fi as a wireless connection to my Arduino/Windows PC LAN without using the internet

I have a hydroponic setup working. Actually I'm working in a second version. My solution is this:

I'm using a nodeMCU, because it have WiFi and lots of memory. In the breadboard I also have a real time clock (RTC), a LDR to measure real light level, and a temp/humidity sensor (DH-11), plus a small OLED display. The green led represent the HID light for testing purposes. I still need to add more elements, but it's good enough to show you my setup.

The nodeMCU send information to a MQTT broker . I can watch that information using an MQTT client in my Android smartphone. With the same client I can send orders to the nodeMCU (like changing light schedule, etc.)

MQTT is a protocol designed for Internet of Thing. It small and simple. You need a broker (server) to receive and send messages. I'm using Mosquitto running on Linux, on a old laptop that is on all time.

This is the big picture (no Internet involved):

Mosquitto is free, and it's available for PC, Mac and Linux here.

You have free clients for Android, iPhone, Windows, Mac, and Chrome. I'm using MQTT Dash.

MQTT is lightweight, easy, multiplatform, multiclient, and the best part of it: minimal programming.


nRF24L01 - Measuring distance using time elapsed

Speed-of-light-delay measurements are not practical for the use-case you propose. As Majenko suggests in his comment, you'd need EXTREMELY accurate time measurement, as well as high speed radio-frequency signal processing. Any measurements you do through software will be far too inaccurate as a result of the software timing.
Apple's iBeacons (which are based on BLE) offer immediate, near, medium, and far distance readings that are based on signal strength. You should be able to achieve something similar with your own wristbands using BLE. The different distance thresholds would have some slop to them, but it should be possible to get decent results.


PWM water pump flow control - should I use capacitor for MOSFET?

I think you're talking about decoupling caps they are used to smoothen out the spikes and ups and downs in the power. But you're trying to control the flow level using pwm and if you add the Caps that would smoothen the pwm signal!


Can I use relays with 10A125V~ for my 220V~ applications, safely?

The part is obsolete now according to Mouser.  The simple answer is no, you cannot use a 120 volt part at 220 volts.  The higher voltage can breakdown the lower voltage rated parts.  It really has nothing to do with the "power" rating as there will be very little power actually dissipated in the relay.  The current handling of the contacts is one issue and that seemingly didn't change but the voltage rating change is basically saying that this part cannot work at 220volts.


Yes!

You can absolutely do the above said task with the shield that you provided information about.

All you have to do is to connect the Shield to the Arduino and upload the WiFiWebServer sketch from the Arduino's examples in the WiFi library!

Then you'll have to replace the SSID and Password with your WiFi's password.

Once uploaded, then you'll get your Arduino's (Server's) IP Address on the Serial monitorl.

Note the IP Address and open any browser on any device of your choice.

NOTE-
Your device must be connected to the same WiFi network to which your Arduino is connected to. If you wish to access the Arduino server from outside your LAN then you'll have to forward/open a port on your WiFi router and direct it to the IP Address of your Arduino. But I am assuming that you just want to access it from your LAN therefore the port forwarding can be ignored.

You'll see the default webpage in the Sketch which you can change/edit as per your own wish by using HTML.

Here's the link to the detailed explanation from arduino.cc itself.

Coming to the Second part of your question: "Also, once a device (say a phone) is connected, how would it go about requesting a web page, or other information?"

Well once the server is started on the Arduino all you do is type the IP of Arduino in the browser of the device and then the browser sends a HTTP request to the server.(This is the same way in which the browser sends requests to any other website or server like google/youtube/stackexchange . It is same for all ).


Why does my LCD screen display white rectangles?

As @Majenko already mentioned, you have to set the right contrast. Use potentiometer to find out what value suits you right.


Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock

If you have an appropriate crystal attached then you can do this in the Arduino IDE. Select your board and programmer in the IDE menu, connect the programmer to the board, and choose Burn Bootloader from the menu. This will both burn the prebuilt bootloader image and set the fuses in a single operation.

Note that you cannot use USB on the '32U4 if you are running off either a ceramic resonator or the internal oscillator, and so you should not attempt to use the Leonardo bootloader in either case.


Blue - Ground, connect to Arduino GND
Brown - Power, connect to external 12V source.
Red - 12 V output. Connect via a diode to arduino input pin. Enable pullup on arduino pin.

This way when the sensor output is low it will pull the arduino pin low. When the output is high the diode blocks the 12V from frying the arduino while the internal pullup ensures the input pin goes to a safe voltage for a high pin.

Don't put the diode the wrong way around or things will go bang.

simulate this circuit – Schematic created using CircuitLab


L293D motorshield with batteries doesn't power Arduino

The problem was that the 2 pins on which the jumper sits, the jumper or the board was broken (idk exactly). I might've caused that myself by turning on the batteries + powering it through usb at the same time.
I bought a new L293D board then made sure I didn't connect usb power to the arduino while the L293D was sitting on top of it. I uploaded the code, then disconnected the usb, put the L293D on top, powered it all and it works like a charm!


How to assign an interrupt to a button press with an ATtiny? (interrupt not fired with my code)

Look at the datasheet of the ATtiny45. In the section “Sleep Modes”,
there is a table that lists the wake-up sources available for each sleep
mode. For the mode “power-down”, INT0 is listed as a possible wake-up
source, but there is a small footnote:

  For INT0, only level interrupt.

This means that the CHANGE mode you are trying to use will not wake-up
the MCU out of power-down. You have to instead

attachInterrupt(0, wake, LOW);

  In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually
  I'd like to have interrupts for all these three pins.

You may then have to look into the “pin-change” interrupt. This is
something different from the INT0 you are using here, and is not
generally supported by the Arduino core. You will have to either get
some pin-change-interrupt library, or work with no library using the
information from the datasheet (not that hard). Pin-change interrupt is
also a wake-up source for power-down.

Edit: Answering extra questions from comments.

  How did you know that "only level interrupt" means only "LOW"?

The Arduino documentation states that the mode
parameter of attachInterrupt() can be either LOW, CHANGE, RISING
or FALLING. A few boards also support HIGH, but the ATtinies are not
among them. A “level” can be either LOW or HIGH, whereas CHANGE,
RISING and FALLING are “edges”.

This is corroborated by the ATtiny45 datasheet: “The INT0
interrupts can be triggered by a falling or rising edge or a low level.”

  Is pin-change interrupt PCINT?

Yes.

  why do you think it isn't supported by the Arduino core?

The attachInterrupt() API only really makes sense for INT0, INT1,
etc... not for PCINT. You can also look at the source code.

  Isn't it standard to interrupt when a pin changes states?

If you wish, you can configure INT0 to interrupt on a rising edge, a
falling edge, or any logical change. But this uses an edge-detection
logic which relies on the main clock, and thus does not work in
power-down mode.

For more details on INT0 vs. PCINT, their differences, and how to use
them, please refer to the datasheet, specifically to the “External
Interrupts” section I linked to above.

Addendum: Extra question:

  why it doesn't work [with ISR(PCINT1_vect) {...}]?

Gcc tells me “warning: ‘PCINT1_vect’ appears to be a misspelled
signal handler”. And indeed, there is no such interrupt vector on the
ATtiny45: there is only PCINT0_vect, and this interrupt is shared by
all the pins that can generate a pin change interrupt. If you want to
know which pin triggered the interrupt, you will have to figure that out
within the interrupt handler itself.

This is the single point that makes the PCINTs trickier to work with
than INT0 and co.: each PCINT interrupt is shared by a group of pins. On
the ATtiny45, there is only one such group, and PCINT0_vect is the
only interrupt handler. Larger AVRs have more groups (3 on the
Uno/ATmega328P), and PCINT1_vect makes sense on them.

Also beware of the somewhat confusing naming scheme. Avr-libc defines
some macros PCINTn, where n is a number. These macros expand to bit
numbers, and are meant to be used in code like this:

PCMSK = _BV(PCINT0)   // sense changes in pin PCINT0 = PB0...
      | _BV(PCINT1)   // and PCINT1 = PB1...
      | _BV(PCINT2);  // and PCINT2 = PB2

In these macros, the number n identifies an individual pin. Avr-libc
also defines the macros PCINTm_vect for defining interrupt handlers.
In these macros, the number m identifies a pin group.


I will use arduino to make tasks in my life automatic maybe to let rotate every morning a motor or to open the door.

That's the kind of thing it's designed for.

  So i will ask can i run arduino as solo so no pc needed,

Yes, you only need a PC to program it, once programmed it will run without the PC.

  Can I connect it to the internet

Yes, there are Ethernet and WiFi shields available for connecting it to a network.

  and can I setup PHP and Apache on it to control it over it; has it any protocols like SSH like an normal server ?

No.  The Arduino isn't powerful enough to run software like that.  You would normally connect it via the network / internet to a server to process data.  It would just receive simple instructions or send data to the server for processing.

  as example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino is running a function...

I assume by "a certification" you want to run SSL on the Arduino. That's not going to happen since it's way too underpowered for that.  As I mentioned earlier, the Arduino would connect to a server on the internet to receive its instructions, or you could interface to it directly within your local network (say from a smart phone) through a simple web server interface (very simplistic due to lack of memory - a few buttons and text, that sort of thing).


Send commands from cPanel website to client ESP8266

I don't believe you will have the capability to implement a Websocket interface on the GoDaddy cPanel web site.  I think you are limited to just serving up HTML content and associated files.  Websocket requires a server-side resource to talk to which you cannot implement.
I see nothing wrong with having a simple HTML page, that doesn't even need to really contain HTML that your ESP8266 can "GET" and examine and determine to turn your relay on or off.


avrdude : stk500_get sync attempt 10 of 10 not in sync : resp=0x20 how do i get pass this error for ardunio uno board

There are multiple reasons why you are getting this error.

Bootloader is either missing or corrupted. This is fairly unlikely.
Wire connected to pin 0 (RX)
Wrong COM port is chosen within the arduino IDE.
Drivers are not installed. You can update it within the Device Manager if you are using Windows.

Here is a link to an article explaining the causes and how to fix them, http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


There once was once something called an "Infinite USB Memory Drive" that acted as a thumb drive that read and wrote data to a networked share over wifi.
They aren't selling those anymore, but their approach might be what you need - network share to resolve the issue of multi- device connected to same drive.
In your shoes, I'd be looking at a Raspberry Pi Zero W (the one with wireless) instead of an arduino.  More computing options means more ways to solve your problems with the same hardware.


Powering multiple servos on external battery

If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use http://www.adafruit.com/product/815 which is very good.

Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.

I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.

After that you will understand a bit better what is going on and why this issue is happening on your configuration.

I cant find the power consummation of this servo so I Cant give much more information.


MySQL Connector/Arduino insert data from row into an array

Sorry for the inconvenience, problem solved!
The problem was simple as I was getting both two columns except one!

void query_analysis_gates() {
  row_values *row = NULL;
  column_names *columns = NULL;
  SQL_SETUP.cmd_query(QUERY_GATE_SQL);
  columns = SQL_SETUP.get_columns();
  counter = 0;
  do {
    row = SQL_SETUP.get_next_row();
    if (row != NULL) {
      gate_Array[counter] = atoi(row->values[0]);
      counter++;
    }
  } while (row != NULL);
}

I provide this if anyone needs help with another method but it does the same function.


Read RC receiver channels using Interrupt instead of PulseIn

Regarding the question, “Does PinChangeInt only work on digital pins?”, note that PCI's work on all the digital pins of an ATmega328, and on the first six analog pins.  (32-pin '328s have eight analog pins, A0-A7; 28-pin '328s only six, A0-A5.)

Regarding the problem symptom that “pulsewidth just seems to increase continuously”, that could happen if for some reason rising edges aren't processed.  To debug, add a couple more volative byte variables, say nrises and nfalls; increment each of them in the appropriate interrupt handler; and report their values from time to time.

Regarding your #include <PinChangeInt.h> statement, note that PinChangeInt.h is deprecated (as of 3 April 2015).  Consider using EnableInterrupt.h instead.

It's possible you'll resolve your problem while changing libraries.  If so, fine.  If not, or if that library's performance isn't adequate, consider changing over to handling the  pin change interrupts more directly.  The ISR in the following sketch shown below runs several times faster than code that uses PinChangeInt or EnableInterrupt library calls.

[Edit: This edit encloses the ISR in a sketch that compiles.  The code previously shown was missing two array length specifications.  This code was tested with a rotary encoder attached to A2, A3, with A0 and A1 grounded; an output sample (using an Arduino Nano) follows the code.]

/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

The code shown above uses Streaming.h, a contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, either install it via Streaming5.zip from arduiniana.org or manually translate the Serial << ... statement to Serial.print statements.

A sample of the sketch's output on serial monitor:

t=35773 0 0 14196 13456 4
t=35775 0 0 14196 13456 3
t=35778 0 0 14196 5748 4
t=35781 0 0 5244 5748 3
t=35783 0 0 5244 5748 4
t=35785 0 0 5244 5748 3
t=35786 0 0 5244 28 12
t=35788 0 0 3024 28 3
t=35789 0 0 3024 28 4
t=35792 0 0 3024 28 3
t=35796 0 0 3024 6396 4
t=35802 0 0 9316 6396 3
t=35809 0 0 9316 6396 4

In the output above, the two 0's are from A0, A1 being grounded and not changing.  The next two numbers are from the DT and CLK lines of a KY-040 rotary encoder, which toggle alternately to encode step-direction.  They should represent on-times in microseconds, and are always multiples of 4 because micros() reports multiples of 4.

The last number is the number of times the ISR's change-checking loop ran since loop()'s previous print.  An A2 change will show a count of 3 or more, and an A3 change 4 or more.  Cases where times are the same may represent contact bounces shorter than the ISR's service time; ie, several falling edges in a row might be detected, or several rising edges.  A storage scope or logic analyzer probably is necessary for finding out exactly what happens.


Reading data from potentiometer with MISO and MOSI on same pin

You need to do a little conversion:

Connect the SDI/SDO line to MISO on the Arduino.
Connect a 1kΩ resistor between MISO and MOSI on the Arduino.

Then you first send the command byte(s) to the slave. You will receive these back, but you can just ignore them.

Then you receive the data. You do this by sending 0xFF for each byte. The 1kΩ resistor means the slave can override the 0xFF from the MOSI. The MOSI -> MISO resistor effectively becomes a pullup resistor and is, to all intents and purposes, ignored (it's just in parallel to the pullup resistor internal to the slave).


PC Cannot Access HC-06 Bluetooth COM Port

If you have powered the BT module from 5v you may have fried it, I recall that the hc-06 module is 3.3v and 3.3v signal too.


I have a very slow internet connection and the Arduino IDE seems to depend a lot on it. When I launch it, I shut down internet and it opens in a breeze.


All those variables a, b, etc. are just the individual bits of a
13-bit number. When you loop through all combinations, you are actually
looping through all the possible numeric values of a 13-bit number.
This can be simplified as this (warning: not tested):

void setup() {
    pinMode(2, OUTPUT);
}

// the bitstream is: 0.101x xxxx.xxxx xxxx.0101
void pulsetrain(uint16_t code) {
    uint32_t bitstream = (((uint32_t) code) << 4) | 0x0a0005UL;
    for (uint8_t i = 0; i < 21; i++) {
        PIND = _BV(PD2);    // toggle pin
        if (bitstream & 0x100000)
            delayMicroseconds(566);
        else
            delayMicroseconds(283);
        bitstream <<= 1;
    }
    PORTD &= ~_BV(PD2); // last LOW
}

void loop() {
    for (uint16_t code = 0; code < 0x2000; code++) {
        pulsetrain(code);
    }
}


Buffer overflow error in ESP8266_SoftwareSerial library

There's some heavy String usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.

The library seems to create a connection by first clearing the SoftwareSerial buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.

The buffer is full message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the SoftwareSerial internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.

Instead, try loading a simple webpage like httpbin.org/ip. That is, at lines 952, 954:

char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

if (createTCP("www.httpbin.org", 80))


inttypes vs Arduino defined integral types

"Arduino": char, int, long; byte, word, unsigned long
  inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

A better classification would be:

C and C++: char, int, long, unsigned long
"Arduino": byte, word
inttypes: int8_t, int16_t, int32_t; uint8_t, uint16_t, uint32_t

I generally avoid the Arduino-specific types, as they are quite
non-standard, and do not usually exist outside the Arduino world. As for
the other types, just like Michel Keijzers suggests, I use the C types
when I do not care much about the exact size. int is guaranteed to be
at least 16 bits, but is likely to be 32 bits on a 32-bit architecture.
It is a good default type, as it is supposed to be efficiently handled
on any architecture. These types allow you to write portable code that
automatically selects the "right" integer width for whatever
architecture it is been compiled for.

If you care about the exact size, which can often be the case in a
memory-constrained environment, use the types from inttypes.h. And do
not worry about implicit conversions: as long as both types are wide
enough to hold the numbers you need to store, a type conversion, whether
implicit or explicit, always preserves the value.


arduino --verify / --upload not working (command line)

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

You should always install the official Arduino IDE downloaded from:
https://www.arduino.cc/en/Main/Software


You can't use an interrupt the way you are attempting to. Attaching an interrupt to a pin like that will cause the interrupt to trigger any time the digital pin's value changes. The DHT11 uses serial communication to send temp values to the Arduino. Serial communication uses lots and lots of on/off pulses on the signal line to send characters of data. Your interrupt will fire every time the DHT11 toggles the signal line.

You need to read the temp from the DHT11 in your loop, and then add an if statement that does what you want when the temp exceeds your threshold. (It looks like you just need to get rid of the attachInterrupt() call, and instead call IntCallback() every couple of seconds.


How to turn the digital pin to analog pin?

You can use an external A/D converter, there are a lot of varieties in a lot of price ranges for the Arduino. Check your favorite online source. That will require two of your existing analog pins for the I2C interface but you will gain back many more depending on your choice. If you choose to use SPI that will take 4 pins.


Checking for multiple values in IF separated by commata

Yes, the list of values 4, 6, 9, 11 does not mean what you think it does.

if ((minute == 31) &&  ((hour == 4) || (hour == 6) || (hour == 9) || (hour == 11))) {
    digitalWrite(8, HIGH);
}


MQTT broker and Arduino + Sensors NRF24L01

The normal topology is sensor nodes publishing topic-data on a MQTT broker. And the broker distributing updates to subscribing clients. The MQTT broker is responsible for several levels of QoS (Quality of Service) such as storing attribute/topic-values (persistence), checking that messages are delivered, etc. Typically the broker runs on a server with disk, multiple network connections, etc.

A possible solution is to send sensor messages to a bridge that translates and publishes the message on the MQTT broker. The sensors may use a simple cheap local wireless network (such as based on NRF24L01) and the bridge would publish over IP (Ethernet, WiFi, etc) to the MQTT broker.

Some sensors/actuators might need configuration/control (alarm thresholds, resolution, etc). In this case they need to subscribe to messages (topic updates) from the MQTT broker. Again the bridge needs to provide the subscription and message translation/routing back to the sensor.

Last, topics naming is a challenge as the bridge should be transparent in the naming structure but still configurable. The bridge configuration (e.g. network address/topic translation) could also be handled as a bridge topic.

Cheers!


Recommendation for a projector module or approach?

As written in the comments, the linked projector is a DLP  projector with 640x320 pixels. Of course, that is expensive. It is a complete pixel display, which can display anything (with the max resolution of 640x320). That is way more, than the projector watches.
The watches often use one of two possibilities:

A bright 7 segment LED display, which is projected to the wall via a lens. The seven segment display needs to be bright enough, depending on the intended brightness of the projection and how big the projected image should be.

An LCD display, which is illuminated from behind by a bright LED. That is then also projected to the wall with a lens. I would guess, that this is, what the linked watch is doing.

How to build that yourself? You can always salvage one of these watches. But when building it yourself, you should also follow one of the above possibilities. Which one depends on your requirements.
Using a standard 7 segment display will be the easiest. Though that might be not bright enough. You could look for especially bright 7 segment displays and test, if that is enough for you.
The second possibility would be more hacky. Most LCD displays, that you can buy, have a LED lit plane in the back as a backlight. You would need to remove that plane, so that the display gets transparent. Also you most likely would need to rotate the polarizing filter on the top of the LCD, because as standard a driven segment of the LCD gets more opaque, while you want it to get transparent. A new filter (up to a few cm) can be salvaged from the passive 3D glasses from a movie theater.
In both cases you install the display inside a tube together with a fitting lens. Look, what you can get from your location and then experiment with it.

can you link to parts

No, we are not really doing that here, because that is really dependent on your location, on your price- and other requirements. Also such part suggestions are usually very fast outdated. But you can look at the electronics shops, that you have at your location and search there for the general description of the parts (for example "7 segment display").


Why does an LED sometimes flash when increasing brightness?

According to the links you provide from the arduino.cc forum the question is more or less answered. If not that important, just avoid analogWrite(led,0) and make it analogWrite(led,1)

if you still want that analogWrite(led,0), I've tested your code with the advice and it seems to work OK when changing the register manually:

#include "wiring_private.h"

int led = 11;
int brightness = 0;

void setup()
{
  pinMode(led, OUTPUT);
}

void loop()
{
  if (brightness >= 256) //checks if brightness has passed 255, resets to 0
  {
    brightness = 0;
    sbi(TCCR2A, COM2A1);
    OCR2A = 0; // set pwm duty
  }

  analogWrite(led, brightness);
  if (brightness == 0)
  {
    delay(1000); //LED off for 1 second
  }

  brightness += 1; //increment brightness
  delay(20);
}

Edit: to explain what those "strange codes" are

I'm not very expert in this field to explain how exactly this works but basically sbi is function defined in a macro by Atmel (?), it stands for "set bit in" and is used to change registers of ATmega chips. So basically what I did was change register defined by the macro TCCR2A (why? because it is the register that controls PWM in pin 11) and pass the bitmask COM2A1 (this is a mode of compare defined in datasheet) and OCR2A is a register used to store the compare value that defines duty cycle. Imagine a counter that every time it receives a tick from a signal clock it compares the value of the counter with the value stored in OCR2A and it sets the pin high or low if that value as been passed or not (more or less like this, depending on the mode stored on TCCR2A).

But in fact I've not done some black magic. I just looked into the code of analogWrite() and that is the way they use to set a value of PWM in pin 11:

void analogWrite(uint8_t pin, int val)
{
    // We need to make sure the PWM output is enabled for those pins
    // that support it, as we turn it off when digitally reading or
    // writing with them.  Also, make sure the pin is in output mode
    // for consistenty with Wiring, which doesn't require a pinMode
    // call for the analog output pins.
    pinMode(pin, OUTPUT);
    if (val == 0)
    {
        digitalWrite(pin, LOW);
    }
    else if (val == 255)
    {
        digitalWrite(pin, HIGH);
    }
    else
    {
        switch(digitalPinToTimer(pin))
        {

...

          #if defined(TCCR2A) && defined(COM2A1)
            case TIMER2A:
                // connect pwm to pin on timer 2, channel A
                sbi(TCCR2A, COM2A1);
                OCR2A = val; // set pwm duty
                break;
          #endif
...

}

So basically I just used that info to set the register to zero, as suggested from the arduino.cc forum link that you have.

If you want to know more about PWM in Arduino, this site has a lot of info and explains a lot of the modes of registers also.


Theoretically that should be OK.

According to the datasheet the MPU6050 consumes no more than 3.9mA with all the internal options turned on. That is below the limit of 25mA sustained current from a single IO pin for the ATMega chips. Just be aware of the total limit of the ATMega's power pins of 200mA, but it would take a lot of modules to reach that limit.

Since the MPU6050 is a 3.3V device your modules most likely have a voltage regulator on them to allow powering from 5V. That should mitigate any voltage droop caused by the higher impedance of using an IO pin as a voltage source.


Time information from GPS receiver: how to tell whether it is fresh or stale?

Most of the GPS modules keep on sending the data in the NMEA format whether they have a GPS fix or not, however, you can parse the GPS data to find whether the data is the latest data received from the GPS or not. If you look at the definition of the NMEA data here, there are a few variables in the data that you can use to find whether the data is the latest data from the GPS or not.

You can use the "Fix Quality" in GPGGA as well as "Validity/Receiver warning" in GPRMC for your module. The tinyGPS indeed has both of these variables being parsed.

In the tinyGPS library, if _gps_data_good is true then the data coming from the GPS module is the latest data it received from the GPS satellites. The program uses either the fix or validity to determine this (Refer to the library here and here).

You should just keep checking this variable to find whether the current data is the latest from the GPS or is it being calculated internally.


What you are doing is called "bit-banging" (wikipedia link) but you have no guarantees about the timing of your bits.

In your writeTx routine you are changing tx_pin at some rate which depends on:

the clock speed of your MCU
the code that the C compiler generates

Moreover, the timing will be all screwed up if you happen to get an interrupt while sending the bits.

The same applies to your read routine.

The Arduino (really the Atmel MCU) has special hardware to perform both synchronous and asynchronous serial IO. The set up is rather complex because the hardware
is very versatile and capable of a lot of different functions.
In particular, it can deliver the bits at a specific baud rate for you so your code doesn't have to do it. It can also read in a serial stream and set a flag or invoke an interrupt when a complete word has been received.

This article can give you an idea of what the USART in an Atmel processor is capable of:

http://maxembedded.com/2013/09/the-usart-of-the-avr/


The mistake in question and in comments (except of Bigoldsofty's comment), is missing character for justifying. This character should be in format string before the required width. "% 5s" not "%5s"


After lots and lots and changing values for resistors and capacitors and checking connections, i came to find out that my micro-controller ground was not at the same level as the ADCs ( i had already connected its ground with my circuit board ground but there was some kind of problem ). When i soldered the controllers ground just near the ADCs ground, both the ADCs started working properly.


Arduino Ethernet and Uno R3 as a firewall

As an entry level board, I wouldn't suggest trying this on the R3. You can do it to an extent on the Yun which comes with both a network port and wifi.

Now that said, your internet speed will be severely hampered by the lack of resources on the yun. In which case, you might want to steer closer to the Intel Edison, which you can use with the arduino IDE. It is considerably more powerful.


Connecting two sensors to one analog pin

AO is not "Ay Zero", it's "Ay Oh", and stands for "Analog Output". It means it just sends a varying voltage. It really doesn't care where it's sent to, it just sends it.

It's up to you where you connect that output to. But suffice it to say it wants to be connected to an input that can read an analog signal. And the Arduino has 6 of them.

Which one you connect it to is entirely up to you - you just have to read from that analog input by using the right pin number in analogRead().


Powering the Arduino with a battery and reading the battery voltage

AFAIK, Arduinos are set up to use their operating voltage as the analogRead reference voltage by default.

So, what I think is happening is that you are trying to measure the battery voltage with the battery itself as a reference voltage.

This will, of course, always show "full scale".

You could use a voltage divider to bring the measured battery voltage down to about 1V (max) and use the internal reference of 1.1V for measuring.

Note that the 1.1V internal reference is stable, but not necessarily exactly 1.1V.


Using TX/RX serial pins to communicate over USB

There is no "built-in USB" on the Nano. There is only the FT232RL chip which talks USB. That chip is connected directly to the TX/RX pins inside the board.
You are already communicating over the TX/RX pins through the FT232RL to the USB.
Yes, you could use your own FT232RL (or FT232-like) board to communicate between USB and the TX/RX pins, but that will be exactly the same as using the one built in to the board - but without the convenience, and with the addition of more wires and expense.  So pointless, unless the current USB connection is damaged in some way.


How to burn bootloader/program an ATMega 328P with an external crystal 8 MHz oscilator?

myself as of 3 hours ago.

Get an arduino or similar, install the ArduinoISP sketch
Connect the two as described here.
Change the board to Arduino Pro or Pro Mini, Processor to 3.3V, 8Mhz, Programmer: Arduino as ISP
Hit burn bootloader button
Load up the sketch that you want on the device
Without changing anything, use "Upload using programmer"
Remove arduino, fix wiring changes required to use as programmer

Committed to Electronics Stackexchange  for posterity.  Or so I can find it when I forget next time...


Problems controlling servos using proximity sensor

I am new to servos as well, but I do have two coding thoughts. The servos I have used in the past have started in the halfway position. That would mean the "pos" variable would start off trying to go from the starting 90 position to the 0 value in 15ms. Not enough time before the next for loop. I could see that causing some weird spinning while the servos try to get to the intended position. So..

int pos = 90; // Start servo position.

And secondly, the "distancia" could just always be less than 100. I would try finding a max distance value to compare to vs a hard coded value.

void loop() {...
long duracion, distancia; // variables
boolean isMoveTrigger = false; // Movement trigger.

/* Calculo de la distancia efectiva */
distancia = (duracion/2) / 29.1;

// Store a maximum value.
if (distancia > maxDistance) {
    maxDistance = distancia;
}

// Wait to get a starting maximum distance value.
if (countDown > 0) {
    countDown--;
} else {
    if (distancia > 0) {
      int distancePercentage = (maxDistance * 100) / distancia; // A 0-100 percentage of the maximum value.
      // Then trigger the movement when less than this percentage.
      isMoveTrigger = distancePercentage < 50;
    }
}
if (isMoveTrigger) {
    for(pos = 0; pos < 180; pos += 1) ...


2.8" TFT Touchscreen Prohibits Access to Unused Pins

Several options:

Use wires to connect it rather than sticking it directly onto the Arduino.
Use a header extension to lift the display away from the other headers.
Use right-angle headers on the other pins.


How long should TinyMPU6050.h calibration run for?

I feel so sorry about the previous releases of TinyMPU6050. I've just released v0.5.0 that shall soon be available at the Arduino Library Manager index.

The calibration method indeed was messy, so I decided to keep it simple. I also removed dependencies of String objects and Serial stuff and it seems to work pretty fine now.

If you keep having issues with that, please let me know!

The official link to release 0.5.0 follows:
https://github.com/gabriel-milan/TinyMPU6050/releases/tag/0.5.0


Sonar and servo stop working when usb cable unplugged

Sonar modules are notorious for pulling so much instantaneous power during their brief pulses that they often reset the processor, causing the Arduino to start all over from the beginning.

Do you have any way of knowing whether your program is executing more-or-less normally, or if your program in the Arduino is getting reset?
If not, you need better debugging tools.

(tangential rant about debugging tools)

Many people debug by sprinkling their code with print(F()) statements that get sent to a LCD screen or a serial port.
Other people debug by sprinking their code with statements that turn on and off a series of LEDs of various colors, or at least a single LED with a (hopefully easy-to-decode) blink code.
Some kinds of problems are much easier to track down with an oscilloscope.

dealing with high-current pulses

My best guess is that the sonar is pulling very brief high-current pulses from the battery, which causes the battery voltage to droop low enough to reset the Arduino.
When the USB cable is plugged in, (I'm guessing that) the additional power supplied by the USB cable somehow keeps the Arduino from resetting.

Many sonar modules (very briefly) pull 1 A or 2 A, far more than a USB cable or a handful of AA batteries can supply.

There are many ways to solve that problem, but if I were you I would first see if that is really the problem in this case.
Possibly the quickest way to tell is:

Use at least 2 separate battery packs.
Hook all the grounds of all the battery packs and all the devices together.
hook the positive power of one battery pack to the Arduino and nothing else.
Hook the power lead of all the other devices to some other battery pack (ideally a different battery pack for each device).

Then run the test again.
This should give you a clue as to whether the problem is the Arduino seeing power-supply droop (which separate battery packs should "fix"), or something else.

If the problem really is power supply droop, there are a variety of ways to fix it:

(a) Many people recommend: use a large 1000 uF capacitor directly across the power pins of the sonar, and a 10 Ohm or 100 Ohm resistor between the battery positive and that capacitor. (a) (b) (c) (d) (e) (f)
(b) Use a large capacitor directly across the power pins of the Arduino, and a diode from the battery to that capacitor so that normally the diode allows the battery to charge the capacitor, but when the sonar or whatever briefly drags the battery voltage to a low level, the diode blocks the sonar from pulling energy "backwards" out of that capacitor, and the capacitor is large enough to run the Arduino during the sonar pulse.
(c) Get a dedicated "logic" battery array to power the Arduino and a few LEDs, etc., and a separate (often much larger) "dirty power" battery array to power the sonar, motors, etc.


myFile.read() returns one character. That character can be represented as a number (such as 65 for 'A') or a character, or whatever you want. Everything is just a number.
Letters are just our personal representation of certain numbers as humans. You could think of it as the numbers represented in base 256, where each value between 0 and 255 is assigned a unique symbol.
Serial.write() just passes that number verbatim to the computer which then maps it in the serial monitor to the corresponding letter in the ASCII table.
Thanks to the object-oriented and polymorphic nature of the Arduino API (see C++ Polymorphism) there is no difference between reading from a file and reading from serial. They all inherit the same Stream class that gives you the same functions regardless of what you're reading.
So you could, like Serial, read each byte from the file one at a time until you reach the line ending character(s) (\n for a Unix file, or \r\n for a Windows file) and append each to the end of a string (either a String object, which is frowned upon, though less so on more capable MCUs like the ESP8266 and ESP32, or a char array).
Alternatively you could use one of the helper functions of the Stream class, such as readStringUntil(), which reads an entire string up to (and discarding) the specified terminating character and returns a String.
However both those have problems when it comes to building up an array of all the results, especially if you don't know beforehand how many lines there are in the file - since in C++ arrays have a fixed size.
A better solution, if you really do want it all in RAM (see below), might be instead to, at first, forget the idea of lines and just read the entire file into memory. Once it is in memory you can read through the entire block of data counting the number of \n bytes (and add one if it doesn't end with \n). That will give you the number of lines in the file.
You can then allocate an array of pointers with the same number of entries as there are lines.
From there you can use strtok() on the data to split it into chunks on the \n bytes and assign each chunk to one of the pointers in your array.  That array then becomes a kind of index to the data.
But one has to ask... why do you want to store this data in RAM anyway? You have it in flash, and that is quite fast to access (not as fast as internal flash in a traditional MCU, but still many times faster than an SD card for example). If ease of navigating the data is your goal, maybe you should be thinking of better ways of storing your data. Depending on what that data is maybe a fixed size record based file structure using a struct to manipulate the data would be a better solution - then you can just seek to multiples of the record (or struct) size to almost instantly get to different entries in the file.
If it's textual data then maybe reading through the file and recording the file offsets of the start of each line in an array (note: two passes - one to count the lines for allocating the array and one for recording the offsets into the array) similar to the indexing of the data block described above would be a better solution. That way you're only storing 4 bytes per entry in your array rather than all the data. Seeking is instant (just seek to the offset stored in the array for the line you want) and you're not having to store all the data in RAM.


Counting the number of pulses in a second

As already explained in Michel Keijzers' answer, instead of counting how
many times you find the input HIGH, you should count the LOW →
HIGH transitions. This requires saving the previous input state and
counting a transition only when the input is HIGH while it was LOW
last time you saw it:

static int last_pin_state = LOW;
int pin_state = digitalRead(SPEED_PIN);
if (pin_state == HIGH && last_pin_state == LOW) {  // rising edge
    count++;
}
last_pin_state = pin_state;

For displaying the count every second, use the technique explained in
the Blink without delay Arduino tutorial:

static uint32_t last_time = 0;
if (millis() - last_time >= PERIOD) {
    Serial.println(count);
    count = 0;
    last_time += PERIOD;
}

Note that you have to reset the count every time you print it.

VE7JRO suggests using interrupts. Interrupts save you the pain of
writing the edge detection. On the other hand, they also make things
slightly more complicated, because you now have to worry about
atomicity, race conditions, volatile variables and such. There is no
need to use interrupts unless the pulses are so fast (or your loop()
is so slow) that you may miss a pulse. If your loop() gets bigger and
slower, and you risk missing pulses, then interrupts can really help.
But the proper way to use them is to count the pulses in the ISR. If you
use the ISR only to rise a flag, you loose the speed advantage of the
interrupts, which is the whole point of this approach.

The interrupt service routine would then be like this:

volatile unsigned int count;

void count_pulse()
{
    count++;
}

Then, the loop only has to print and reset the count:

void loop()
{
    // Periodically print and reset the count.
    static uint32_t last_time = 0;
    if (millis() - last_time >= PERIOD) {
        noInterrupts();
        unsigned int count_copy = count;
        count = 0;
        interrupts();
        Serial.println(count_copy);
        last_time += PERIOD;
    }
}

Note that the variable count is shared between the ISR and the main
loop. That's why it has to be declared volatile. Also, its access
within loop() has to be protected within a critical section delimited
by a noInterrupts()/interrupts() pair, otherwise you would have a
race condition. Also note that, in order to keep the critical section as
short as possible, the value of count is only copied within the
critical section, and the actual printing is deferred to after the
critical section is finished.


How to interface to LPG consumption meter

Start with earthing the red (!?) wire to the ground of the arduino.
Apply 5 volts via a 10k resistor to one of the black wires and also connect the black wire to the arduino as well.
Basically :

5V ----(10K resistor)---+---Black wire----( Gas Meter)-----ground
                        |
                        |
                        +--- arduino digital input

You should either get a high or a low signal. Try the other black wire, it might be inverted (as in high and then pulse low, vs low and then pulse high).

Failing that, pop the top off that cover and have a poke around. Might give you a clue as to what's what.