Is there a non-float alternative to pow()?

For the general case, @dat_ha 's answer is correct, but it is worth noting that you want a very special case... powers of two. Because computers use binary arithmetic, operations involving powers of two often have some shortcuts available.

Multiplying a number by a power of two can be accomplished by the left shift operation (<<), which literally shifts the digits of the binary representation of the number (i.e., bits) leftward.  In base two, shifting bits one place to the left is the same as multiplying by 2, just as in base 10 shifting digits one place to the left is the same as multiplying by 10. For a full explanation of the left shift operator in C++, see this answer on Stack Overflow.

It is important to note that left shifting can lose information; bits shifted off the end are lost. Because you need powers of 2 up to 10, you are safe when working with signed integers, which have a max value of 2^15-1 on Arduino Uno.

Given those caveats, here's a function to calculate powers of two within these constraints.  This is very fast code because the left shift operation is a very low level operation, and no multiplication is actually performed.

int pow2(int p){
    return 1 << p;
}


Burning servos like crazy, what am I doing wrong?

Some servos are actually not able to do full 0..180 rotation - or to rephrase it better, the standard 0.5ms and 1.5ms pulse will force them to a position which can not be reached. Therefore the motor keeps on rotating in a constant struggle.

change 0 to something like 20, and 180 to something like 150
check that the motor has stopped once reaching 20 or 150. I.e. it does not produce any sound, and if you touch the motor body it is not producing any vibration (so no constant stuggle)


How convert eight hex characters to uint32_t using strtol() function?

The function strtol() is not able to convert numbers that are larger than LONG_MAX and smaller than LONG_MIN as it uses signed numbers.

You should use the function strtoul() instead (for unsigned long integers).

Cheers!


Help with a function that accepts different parameter types

take a look at: http://www.cplusplus.com/doc/tutorial/functions2/

template <typename SomeType>
SomeType sum (SomeType a, SomeType b)
{
  return a+b;
}

This appears to be what you want.


How to implement the Arduino Extended Database library in a custom class?

It is difficult to answer this question because I'm not sure what you have managed to achieve.  Sorry if some of it seems a bit basic.

Look at Majenko's answer to the question.  If you want to use this EDB class then you need to define two functions:

  void configWriter( unsigned long address, byte data );
  byte configReader( unsigned long address );

You need to be able to access the single instance of these functions from anywhere in the code, so the need to have global scope.  When they are global you can assign them to pointers by using the function name and no brackets/parenthesis.  i.e.

aPtr = configWriter;

So the call to create the EDB instance would be:

 configDB = new EDB( configWriter, configReader );

Now you could create the EDB instance using a class member function.  To do this you have to make the function a static member, which means it has no access to the class's data. (in its simplest terms static means there is only one of the things it is referring to) i.e.

class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

Essentially its the same thing, but the code is compartmentalised better and you end up with neater code.

However, if you are only ever going to have one instance of the myEDB class then you can have a static member variable that hold the value of this.  You set this value in the class constructor.

class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
    myEDB() {pInstance = this;}
  private:
    static myEDB* pInstance = nullptr;
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

When configReader or configWriter is called it checks to see if the member pInstance has a non null value, if it doesn't then it creates a new instance.  The then use this pInstance to access the functions and variables for the instance of the class.  (This is the design pattern for a single instance class or singleton).

SO what should YOU do?

Start simply, define two global functions that do what you need as per the top of this answer.  If you get stuck, if you need more info feel free to ask or comment.


Arduino & ARM - Replacement for avr-libc?

I think newlib is the one you want.
howto


For numbers, certainly, const <type> is preferred.  This is chiefly because it imposes a type (which would only be optional for a #define), which can have a knock-on effect for mathematics.

That's not to say that you should always use const <type> instead of #define.  #define has its place.

One of the benefits of #define over const <type> is that it is a direct literal text replacement. The replacement is done before the compilation, so anything that is valid in your code can be put in a #define, whereas only things which evaluate to the correct type at runtime can be placed in a const <type>.

Take strings for example.  Yes, you can use:

const char *foo = "This is text";

And you can use that wherever a const char * is expected.  However, if you use:

#define FOO "This is text"

you can use it anywhere a string literal is expected.  That makes for useful things such as C's way of concatenating string literals at compile time:

Serial.println("I say: " FOO);

The two string literals "I say: " and FOO (which expands to "This is text") are concatenated into a singe string literal at compile time into:

Serial.println("I say: This is text");

You can't do that with const char *.

Another big difference with const <type> compared with #define is when expressions are evaluated.  Take for example:

const float sinpi = sinf(3.141592653);

That will calculate the sine of PI once at startup. However:

#define SINPI sinf(3.141592653);

will calculate the sine of PI every time it is used.

So in this instance const float not only gives you an imposed type of float for all calculations, it also reduces calculation overhead by only running the calculation once and saving the result.

So as you can see there are pros and cons to each.  But in general, for numbers:

const <type> is preferred for storing internal numerical data that doesn't change, and
#define is most often used for user-configurable data, since it doesn't impose the ; at the end of the line which often gets forgotten by (newer) users.


Regarding using I2C with Arduino for Silicon Micro-structure 5852 D 1.5 psi

The issues in your code:

When communicating with the sensor, the sensor expects a register address after the device address. Instead of providing it the register address, you sent the number of bytes you would like to receive. Good guess, but unfortunately the device was not designed that way.
You did not combine the least significant bits and most significant bits of the sensor output correctly. The LSB contains the 6 (not 8) least significant bits, while the MSB contains the 6 most significant bits. You first combined them like 00MMMMMM00LLLLLL (where bits marked L come from the LSB and bits marked M come from the MSB), and then masked off the upper two bits as in MMMMMM00LLLLLL. The proper way would have been to only left shift the MSB 6 bits, producing 0000MMMMMMLLLLLL, and then masking away the upper 4 bits leaving MMMMMMLLLLLL.
You should avoid 32 bit floating point math on 8-bit microcontrollers at all costs unless you have a huge amount of processor cycles to spare.

In order to read data from the sensor you must first select the register you want to read. To select a register you must first send the device address (95 in decimal, 5F in hexadecimal) with the write request bit set, and then the register address of the byte you want to read.
You can then read the contents of the selected register by first sending the device address, this time with the write request bit clear, and then receiving one byte of data immediately followed by a not acknowledge (NACK) to end the transmission.

The internal registers are organized as in the following table:

Here is my take on the code. It compiles fine, but obviously I cannot test if it actually works as I don't have the sensor. I removed the scaling routine, as it would be wise to first get it working to some level before implementing less essential features.

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

#define SENSOR_I2C_ADDR 95
#define SENSOR_REG_PRESSURE_LSB 128
#define SENSOR_REG_PRESSURE_MSB 129

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

void loop()
{
    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the least
    Wire.write(SENSOR_REG_PRESSURE_LSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, false);    //Request 1 byte of data, followed by a repeated start

    Wire.beginTransmission(SENSOR_I2C_ADDR);        //Send the address of the register where the most
    Wire.write(SENSOR_REG_PRESSURE_MSB);            //..significant bits of the pressure measurement are found
    Wire.endTransmission(false);                    //Send a repeated start
    Wire.requestFrom(SENSOR_I2C_ADDR, 1, true);     //Request 1 byte of data, followed by a stop, ending the transaction.

    uint16_t pressureRaw;

    //There should now be two bytes of data in the receive buffer.
    if(Wire.available() == 2)
    {
        uint8_t lsb = Wire.read();                  //The first byte contains the 6 least significant bits
        uint16_t msb = Wire.read();                 //The second byte contains the 6 most significant bits
        pressureRaw = (msb << 6 | lsb) & 0x0FFF;    //The most significant bits are aligned and combined with the
                                                    //..least significant bits. As the resulting value only has
                                                    //..12 bits of precision the upper 4 bits are masked to zero.

        Serial.print("Raw pressure value: ");
        Serial.println(pressureRaw);
    }
    else                                            //If more or less than 2 bytes have been received something isn't right.
    {
        while(Wire.available())                     //Clear the buffer
            Wire.read();
        Serial.println("I2C transaction error");
    }
    delay(1000);
}

For some unfathomable reason Silicon Microstructures decided to not include the I2C interface specification in the datasheet itself. The information is instead found in a separate application note.

EDIT:
Apparently Wire.flush() does absolutely nothing. Implementation from Wire.cpp:

void TwoWire::flush(void)
{
    // XXX: to be implemented.
}

And no, the implementation isn't in the base class either: virtual void flush() = 0;. To work around this, I replaced the flush call with a read() loop.


Trouble understanding connection diagram

Normally you would connect the ground (0V) side of resistor R2 to the ground of the Arduino and the other side of R2 (which is also connected to the emitter of Q1) to an input pin of the Arduino. When the LED is energized by pressing the button it sends light to the fototransistor. Because of this the phototransistor starts conducting current (I1) which causes a voltage drop I1xR2 over R2. When this voltage is high enough the input pin will show a "1" (or HIGH) when read out.  "High enough" means >= 0.7 x Vcc, where Vcc is the voltage of the powerline to the Arduino.

The website from which the picture in your question originates (here) has an extensive article about the working and implementation of optocouplers. It also shows examples of alternative circuits.


Can I send any kind of signal to my phone with Bluetooth?

You have an HC-06, which is a bluetooth Serial (UART) bridge. Thus the bluetooth device exposes the profile for a serial terminal. You can only transmit serial data. It doesn't work for HID input to the smatphone or audio. The Bluecontrol app seems to use serial. So that is not a problem.
To get the communication to work, you need to pair the HC-06 with your phone. The actual connection is then established by the app. It will send serial data to the HC-06, which will output it on its TX pin. Serial communication on its RX pin will be transmitted back to the app.
You need to test, for which baudrate the HC-06 is configured. For that write a test sketch, you use an extra serial interface (either another hardware interface or SoftwareSerial) for the HC-06 and send every byte, that you receive from it, to your PC, so that you can see, what the Arduino receives. Try different standard baudrates (like those, which are listed in the serial monitor), until you find the one, which gives you the correct output.
When that works, you can write your sketch to read the commands from the HC-06 serial interface and act accordingly. How exactly that works depends on the data, that the app is sending. Most likely is sends ASCII encoded text, each message terminated by a newline character \n. In that case you could read the data into a buffer byte by byte, when they arrive. When you read a newline character, you know, that you received a full message. Then you can process it and act accordingly.


Trying to understand compilation error message

You are trying to use a library, but it is either not installed, or is installed in the wrong location. A library, in this context, is code that supports a sensor or some other hardware or that accomplishes a task. We call them libraries because we can share and reuse them – like borrowing a book from a library.

It looks like you're trying to get the Adafruit TCS34725 color sensor going. The official source of the library is in the Adafruit's GitHub repository for the TCS34725 and there is a link at the bottom of the README for how to install a library. I'll bet that will get you back on track.


5V on HIGH Digital Pins, Only While Using USB Power

"Arduino Pro Mini hooked up to the 5V power supply via the RAW and GND pins, but the supply is a regulated 5v wall supply. "

That is the problem. RAW pin expects more like 6V to 6.5V for the regulator to output 5V.

If you are supplying 5V, connect to the 5V, or VCC and GND pins.

If you are connecting to USB via an  FTDI Basic or equivalent, and the 5V supply at the same time, then the computer may not like having the USB 5V line back driven from an external source (mine complains about a "power surge" and shuts down the USB port). Make up a breakout cable between the FTDI and the Promini and either disconnect the 5V line, or put a diode in series so the Promini can't supply 5V back thru the FTDI and into the USB port.  That way the FTDI chip is powered from USB, but the Promini is not, and all the hardware is happy.

Make sure to use series resistors with LEDs to avoid overcurrent from the Promini output pin, which will either damage the IO pin, possibly damaging the 328P, or damaging the LED from overheating from excess current.  (5.36V - 2.2V)/.02A = 156 ohm. A 180 ohm, 220, 270, 330, some value in that range will do. 1K will probably be fine, LEDs these days can be quite bright even at lower current; 20mA can be blindingly/annoyingly bright.


Arduino sketch- How to add Time Stamp for outgoing MQTT

Start with the ESP8266WiFi "NTPClient" example.  That will teach you how you can get the "Unix Epoch" time from the internet.

That value can be fed directly into TimeLib to keep track of the time for you (indeed, TimeLib includes an NTP example for Arduino Ethernet that should help you get started).  Do that periodically (daily, hourly, whatever), and you have your time.  TimeLib can then give you the date and time as individual components (hours, minutes, etc), which you can then construct together (I'd use snprintf) to include in your MQTT message:

int len = strlen(message) + 25;
char mqttMessage[len];
snprintf(mqttMessage, len, "[%04d/%02d/%02d %02d:%02d:%02d] %s",
    year(), month(), day(), hour(), minute(), second(), message);

mqttMessage => "[2018/08/11 20:36:24] foo"


How do interrupts work on the Arduino Uno and similar boards?

TL;DR :

When writing an Interrupt Service Routine (ISR):

Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be protected by "critical sections" (see below)
Don't try to turn interrupts off or on

What are interrupts?

Most processors have interrupts. Interrupts let you respond to "external" events while doing something else. For example, if you are cooking dinner you may put the potatoes on to cook for 20 minutes. Rather than staring at the clock for 20 minutes you might set a timer, and then go watch TV. When the timer rings you "interrupt" your TV viewing to do something with the potatoes.

Example of interrupts

const byte LED = 13;
const byte SWITCH = 2;

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  if (digitalRead (SWITCH) == HIGH)
    digitalWrite (LED, HIGH);
  else
    digitalWrite (LED, LOW);
}  // end of switchPressed

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  pinMode (SWITCH, INPUT_PULLUP);
  attachInterrupt (digitalPinToInterrupt (SWITCH), switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

This example shows how, even though the main loop is doing nothing, you can turn the LED on pin 13 on or off, if the switch on pin D2 is pressed.

To test this, just connect a wire (or switch) between D2 and Ground. The internal pullup (enabled in setup) forces the pin HIGH normally. When grounded, it becomes LOW. The change in the pin is detected by a CHANGE interrupt, which causes the Interrupt Service Routine (ISR) to be called.

In a more complicated example, the main loop might be doing something useful, like taking temperature readings, and allow the interrupt handler to detect a button being pushed.

Converting pin numbers to interrupt numbers

To simplify converting interrupt vector numbers to pin numbers you can call the function digitalPinToInterrupt(), passing a pin number. It returns the appropriate interrupt number, or NOT_AN_INTERRUPT (-1).

For example, on the Uno, pin D2 on the board is interrupt 0 (INT0_vect from the table below).

Thus these two lines have the same effect:

  attachInterrupt (0, switchPressed, CHANGE);    // that is, for pin D2
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);

However the second one is easier to read and more portable to different Arduino types.

Available interrupts

Below is a list of interrupts, in priority order, for the Atmega328:

 1  Reset
 2  External Interrupt Request 0  (pin D2)          (INT0_vect)
 3  External Interrupt Request 1  (pin D3)          (INT1_vect)
 4  Pin Change Interrupt Request 0 (pins D8 to D13) (PCINT0_vect)
 5  Pin Change Interrupt Request 1 (pins A0 to A5)  (PCINT1_vect)
 6  Pin Change Interrupt Request 2 (pins D0 to D7)  (PCINT2_vect)
 7  Watchdog Time-out Interrupt                     (WDT_vect)
 8  Timer/Counter2 Compare Match A                  (TIMER2_COMPA_vect)
 9  Timer/Counter2 Compare Match B                  (TIMER2_COMPB_vect)
10  Timer/Counter2 Overflow                         (TIMER2_OVF_vect)
11  Timer/Counter1 Capture Event                    (TIMER1_CAPT_vect)
12  Timer/Counter1 Compare Match A                  (TIMER1_COMPA_vect)
13  Timer/Counter1 Compare Match B                  (TIMER1_COMPB_vect)
14  Timer/Counter1 Overflow                         (TIMER1_OVF_vect)
15  Timer/Counter0 Compare Match A                  (TIMER0_COMPA_vect)
16  Timer/Counter0 Compare Match B                  (TIMER0_COMPB_vect)
17  Timer/Counter0 Overflow                         (TIMER0_OVF_vect)
18  SPI Serial Transfer Complete                    (SPI_STC_vect)
19  USART Rx Complete                               (USART_RX_vect)
20  USART, Data Register Empty                      (USART_UDRE_vect)
21  USART, Tx Complete                              (USART_TX_vect)
22  ADC Conversion Complete                         (ADC_vect)
23  EEPROM Ready                                    (EE_READY_vect)
24  Analog Comparator                               (ANALOG_COMP_vect)
25  2-wire Serial Interface  (I2C)                  (TWI_vect)
26  Store Program Memory Ready                      (SPM_READY_vect)

Internal names (which you can use to set up ISR callbacks) are in brackets.

Warning: If you misspell the interrupt vector name, even by just getting the capitalization wrong (an easy thing to do) the interrupt routine will not be called, and you will not get a compiler error.

Reasons to use interrupts

The main reasons you might use interrupts are:

To detect pin changes (eg. rotary encoders, button presses)
Watchdog timer (eg. if nothing happens after 8 seconds, interrupt me)
Timer interrupts - used for comparing/overflowing timers
SPI data transfers
I2C data transfers
USART data transfers
ADC conversions (analog to digital)
EEPROM ready for use
Flash memory ready

The "data transfers" can be used to let a program do something else while data is being sent or received on the serial port, SPI port, or I2C port.

Wake the processor

External interrupts, pin-change interrupts, and the watchdog timer interrupt, can also be used to wake the processor up. This can be very handy, as in sleep mode the processor can be configured to use a lot less power (eg. around 10 microamps). A rising, falling, or low-level interrupt can be used to wake up a gadget (eg. if you press a button on it), or a "watchdog timer" interrupt might wake it up periodically (eg. to check the time or temperature).

Pin-change interrupts could be used to wake the processor if a key is pressed on a keypad, or similar.

The processor can also be awoken by a timer interrupt (eg. a timer reaching a certain value, or overflowing) and certain other events, such as an incoming I2C message.

Enabling / disabling interrupts

The "reset" interrupt cannot be disabled. However the other interrupts can be temporarily disabled by clearing the global interrupt flag.

Enable interrupts

You can enable interrupts with the function call "interrupts" or "sei" like this:

interrupts ();  // or ...
sei ();         // set interrupts flag

Disable interrupts

If you need to disable interrupts you can "clear" the global interrupt flag like this:

noInterrupts ();  // or ...
cli ();           // clear interrupts flag

Either method has the same effect, using interrupts / noInterrupts is a bit easier to remember which way around they are.

The default in the Arduino is for interrupts to be enabled. Don't disable them for long periods or things like timers won't work properly.

Why disable interrupts?

There may be time-critical pieces of code that you don't want interrupted, for example by a timer interrupt.

Also if multi-byte fields are being updated by an ISR then you may need to disable interrupts so that you get the data "atomically". Otherwise one byte may be updated by the ISR while you are reading the other one.

For example:

noInterrupts ();
long myCounter = isrCounter;  // get value set by ISR
interrupts ();

Temporarily turning off interrupts ensures that isrCounter (a counter set inside an ISR) does not change while we are obtaining its value.

Warning: if you are not sure if interrupts are already on or not, then you need to save the current state and restore it afterwards. For example, the code from the millis() function does this:

unsigned long millis()
{
  unsigned long m;
  uint8_t oldSREG = SREG;    // <--------- save status register

  // disable interrupts while we read timer0_millis or we might get an
  // inconsistent value (e.g. in the middle of a write to timer0_millis)
  cli();
  m = timer0_millis;
  SREG = oldSREG;            // <---------- restore status register including interrupt flag

  return m;
}

Note the indicated lines save the current SREG (status register) which includes the interrupt flag. After we have obtained the timer value (which is 4 bytes long) we put the status register back how it was.

Tips

Function names

The functions cli / sei and the register SREG are specific to the AVR processors. If you are using other processors such as the ARM ones the functions may be slightly different.

Disabling globally vs disabling one interrupt

If you use cli() you disable all interrupts (including timer interrupts, serial interrupts, etc.).

However if you just want to disable a particular interrupt then you should clear the interrupt-enable flag for that particular interrupt source. For example, for external interrupts, call detachInterrupt().

What is interrupt priority?

Since there are 25 interrupts (other than reset) it is possible that more than one interrupt event might occur at once, or at least, occur before the previous one is processed. Also an interrupt event might occur while interrupts are disabled.

The priority order is the sequence in which the processor checks for interrupt events. The higher up the list, the higher the priority. So, for example, an External Interrupt Request 0 (pin D2) would be serviced before External Interrupt Request 1 (pin D3).

Can interrupts occur while interrupts are disabled?

Interrupts events (that is, noticing the event) can occur at any time, and most are remembered by setting an "interrupt event" flag inside the processor. If interrupts are disabled, then that interrupt will be handled when they are enabled again, in priority order.

How do you use interrupts?

You write an ISR (interrupt service routine). This is called when the interrupt occurs.
You tell the processor when you want the interrupt to fire.

Writing an ISR

Interrupt Service Routines are functions with no arguments. Some Arduino libraries are designed to call your own functions, so you just supply an ordinary function (as in the examples above), eg.

// Interrupt Service Routine (ISR)
void switchPressed ()
{
 flag = true;
}  // end of switchPressed

However if a library has not already provided a "hook" to an ISR you can make your own, like this:

volatile char buf [100];
volatile byte pos;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;
    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

In this case you use the "ISR" macro, and supply the name of the relevant interrupt vector (from the table earlier on). In this case the ISR is handling an SPI transfer completing. (Note, some old code uses SIGNAL instead of ISR, however SIGNAL is deprecated).

Connecting an ISR to an interrupt

For interrupts already handled by libraries, you just use the documented interface. For example:

void receiveEvent (int howMany)
 {
  while (Wire.available () > 0)
    {
    char c = Wire.receive ();
    // do something with the incoming byte
    }
}  // end of receiveEvent

void setup ()
  {
  Wire.onReceive(receiveEvent);
  }

In this case the I2C library is designed to handle incoming I2C bytes internally, and then call your supplied function at the end of the incoming data stream. In this case receiveEvent is not strictly an ISR (it has an argument) but it is called by an inbuilt ISR.

Another example is the "external pin" interrupt.

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
}  // end of switchPressed

void setup ()
{
  attachInterrupt (digitalPinToInterrupt (2), switchPressed, CHANGE);  // attach interrupt handler for D2
}  // end of setup

In this case the attachInterrupt function adds the function switchPressed to an internal table, and in addition configures the appropriate interrupt flags in the processor.

Configuring the processor to handle an interrupt

The next step, once you have an ISR, is to tell the processor that you want this particular condition to raise an interrupt.

As an example, for External Interrupt 0 (the D2 interrupt) you could do something like this:

EICRA &= ~3;  // clear existing flags
EICRA |= 2;   // set wanted flags (falling level interrupt)
EIMSK |= 1;   // enable it

More readable would be to use the defined names, like this:

EICRA &= ~(bit(ISC00) | bit (ISC01));  // clear existing flags
EICRA |= bit (ISC01);    // set wanted flags (falling level interrupt)
EIMSK |= bit (INT0);     // enable it

EICRA (External Interrupt Control Register A) would be set according to this table from the Atmega328 datasheet.
That defines the exact type of interrupt you want:

0: The low level of INT0 generates an interrupt request (LOW interrupt).
1: Any logical change on INT0 generates an interrupt request (CHANGE interrupt).
2: The falling edge of INT0 generates an interrupt request (FALLING interrupt).
3: The rising edge of INT0 generates an interrupt request (RISING interrupt).

EIMSK (External Interrupt Mask Register) actually enables the interrupt.

Fortunately you don't need to remember those numbers because attachInterrupt does that for you. However that is what is actually happening, and for other interrupts you may have to "manually" set interrupt flags.

Low-level ISRs vs. library ISRs

To simplify your life some common interrupt handlers are actually inside library code (for example INT0_vect and INT1_vect) and then a more user-friendly interface is provided (eg. attachInterrupt). What attachInterrupt actually does is save the address of your wanted interrupt handler into a variable, and then call that from INT0_vect / INT1_vect when needed. It also sets the appropriate register flags to call the handler when required.

Can ISRs be interrupted?

In short, no, not unless you want them to be.

When an ISR is entered, interrupts are disabled. Naturally they must have been enabled in the first place, otherwise the ISR would not be entered. However to avoid having an ISR itself be interrupted, the processor turns interrupts off.

When an ISR exits, then interrupts are enabled again. The compiler also generates code inside an ISR to save registers and status flags, so that whatever you were doing when the interrupt occurred will not be affected.

However you can turn interrupts on inside an ISR if you absolutely must, eg.

// Interrupt Service Routine (ISR)
void switchPressed ()
{
  // handle pin change here
  interrupts ();  // allow more interrupts

}  // end of switchPressed

Normally you would need a pretty good reason to do this, as another interrupt now could result in a recursive call to pinChange, with quite possibly undesirable results.

How long does it take to execute an ISR?

According to the datasheet, the minimal amount of time to service an interrupt is 4 clock cycles (to push the current program counter onto the stack) followed by the code now executing at the interrupt vector location. This normally contains a jump to where the interrupt routine really is, which is another 3 cycles. Examination of the code produced by the compiler shows that an ISR made with the "ISR" declaration can take around 2.625 µs to execute, plus whatever the code itself does. The exact amount depends on how many registers need to be saved and restored. The minimum amount would be 1.1875 µs.

The external interrupts (where you use attachInterrupt) do a bit more and take around 5.125 µs in total (running with a 16 MHz clock).

How long before the processor starts entering an ISR?

This varies somewhat. The figures quoted above are the ideal ones where the interrupt is immediately processed. A few factors may delay that:

If the processor is asleep, there are designated "wake-up" times, which could be quite a few milliseconds, while the clock is spooled back up to speed. This time would depend on fuse settings, and how deep the sleep is.
If an interrupt service routine is already executing, then further interrupts cannot be entered until it either finishes, or enables interrupts itself. This is why you should keep each interrupt service routine short, as every microsecond you spend in one, you are potentially delaying the execution of another one.
Some code turns interrupts off. For example, calling millis() briefly turns interrupts off. Therefore the time for an interrupt to be serviced would be extended by the length of time interrupts were turned off.
Interrupts can only be serviced at the end of an instruction, so if a particular instruction takes three clock cycles, and has just started, then the interrupt will be delayed at least a couple of clock cycles.
An event that turns interrupts back on (eg. returning from an interrupt service routine) is guaranteed to execute at least one more instruction. So even if an ISR ends, and your interrupt is pending, it still has to wait for one more instruction before it is serviced.
Since interrupts have a priority, a higher-priority interrupt might be serviced before the interrupt you are interested in.

Performance considerations

Interrupts can increase performance in many situations because you can get on with the "main work" of your program without having to constantly be testing to see if switches have been pressed. Having said that, the overhead of servicing an interrupt, as discussed above, would actually be more than doing a "tight loop" polling a single input port. You can barely respond to an event within, say, a microsecond. In that case you might disable interrupts (eg. timers) and just loop looking for the pin to change.

How are interrupts queued?

There are two sorts of interrupts:

Some set a flag and they are handled in priority order, even if the event that caused them has stopped. For example, a rising, falling, or changing level interrupt on pin D2.
Others are only tested if they are happening "right now". For example, a low-level interrupt on pin D2.

The ones that set a flag could be regarded as being queued, as the interrupt flag remains set until such time as the interrupt routine is entered, at which time the processor clears the flag. Of course, since there is only one flag, if the same interrupt condition occurs again before the first one is processed, it won't be serviced twice.

Something to be aware of is that these flags can be set before you attach the interrupt handler. For example, it is possible for a rising or falling level interrupt on pin D2 to be "flagged", and then as soon as you do an attachInterrupt the interrupt immediately fires, even if the event occurred an hour ago. To avoid this you can manually clear the flag. For example:

EIFR = bit (INTF0);  // clear flag for interrupt 0
EIFR = bit (INTF1);  // clear flag for interrupt 1

However the "low level" interrupts are continuously checked, so if you are not careful they will keep firing, even after the interrupt has been called. That is, the ISR will exit, and then the interrupt will immediately fire again. To avoid this, you should do a detachInterrupt immediately after you know that the interrupt fired.

Hints for writing ISRs

In brief, keep them short! While an ISR is executing other interrupts cannot be processed. So you could easily miss button presses, or incoming serial communications, if you try to do too much. In particular, you should not try to do debugging "prints" inside an ISR. The time taken to do those is likely to cause more problems than they solve.

A reasonable thing to do is set a single-byte flag, and then test that flag in the main loop function. Or, store an incoming byte from a serial port into a buffer. The inbuilt timer interrupts keep track of elapsed time by firing every time the internal timer overflows, and thus you can work out elapsed time by knowing how many times the timer overflowed.

Remember, inside an ISR interrupts are disabled. Thus hoping that the time returned by millis() function calls will change, will lead to disappointment. It is valid to obtain the time that way, just be aware that the timer is not incrementing. And if you spend too long in the ISR then the timer may miss an overflow event, leading to the time returned by millis() becoming incorrect.

A test shows that, on a 16 MHz Atmega328 processor, a call to micros() takes 3.5625 µs. A call to millis() takes 1.9375 µs. Recording (saving) the current timer value is a reasonable thing to do in an ISR. Finding the elapsed milliseconds is faster than the elapsed microseconds (the millisecond count is just retrieved from a variable). However the microsecond count is obtained by adding the current value of the Timer 0 timer (which will keep incrementing) to a saved "Timer 0 overflow count".

Warning: Since interrupts are disabled inside an ISR, and since the latest version of the Arduino IDE uses interrupts for Serial reading and writing, and also for incrementing the counter used by "millis" and "delay" you should not attempt to use those functions inside an ISR. To put it another way:

Don't attempt to delay, eg: delay (100);
You can get the time from a call to millis, however it won't increment, so don't attempt to delay by waiting for it to increase.
Don't do serial prints (eg. Serial.println ("ISR entered"); )
Don't try to do serial reading.

Pin change interrupts

There are two ways you can detect external events on pins. The first is the special "external interrupt" pins, D2 and D3. These general discrete interrupt events, one per pin. You can get to those by using attachInterrupt for each pin. You can specify a rising, falling, changing or low-level condition for the interrupt.

However there are also "pin change" interrupts for all pins (on the Atmega328, not necessarily all pins on other processors). These act on groups of pins (D0 to D7, D8 to D13, and A0 to A5). They are also lower priority than the external event interrupts. However they are a bit more fiddly to use than the external interrupts because they are grouped into batches. So if the interrupt fires you have to work out in your own code exactly which pin caused the interrupt.

Example code:

ISR (PCINT0_vect)
 {
 // handle pin change interrupt for D8 to D13 here
 }  // end of PCINT0_vect

ISR (PCINT1_vect)
 {
 // handle pin change interrupt for A0 to A5 here
 }  // end of PCINT1_vect

ISR (PCINT2_vect)
 {
 // handle pin change interrupt for D0 to D7 here
 }  // end of PCINT2_vect

void setup ()
  {
  // pin change interrupt (example for D9)
  PCMSK0 |= bit (PCINT1);  // want pin 9
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13
  }

To handle a pin change interrupt you need to:

Specify which pin in the group. This is the PCMSKn variable (where n is 0, 1 or 2 from the table below). You can have interrupts on more than one pin.
Enable the appropriate group of interrupts (0, 1 or 2)
Supply an interrupt handler as shown above

Table of pins -> pin change names / masks

D0    PCINT16 (PCMSK2 / PCIF2 / PCIE2)
D1    PCINT17 (PCMSK2 / PCIF2 / PCIE2)
D2    PCINT18 (PCMSK2 / PCIF2 / PCIE2)
D3    PCINT19 (PCMSK2 / PCIF2 / PCIE2)
D4    PCINT20 (PCMSK2 / PCIF2 / PCIE2)
D5    PCINT21 (PCMSK2 / PCIF2 / PCIE2)
D6    PCINT22 (PCMSK2 / PCIF2 / PCIE2)
D7    PCINT23 (PCMSK2 / PCIF2 / PCIE2)
D8    PCINT0  (PCMSK0 / PCIF0 / PCIE0)
D9    PCINT1  (PCMSK0 / PCIF0 / PCIE0)
D10   PCINT2  (PCMSK0 / PCIF0 / PCIE0)
D11   PCINT3  (PCMSK0 / PCIF0 / PCIE0)
D12   PCINT4  (PCMSK0 / PCIF0 / PCIE0)
D13   PCINT5  (PCMSK0 / PCIF0 / PCIE0)
A0    PCINT8  (PCMSK1 / PCIF1 / PCIE1)
A1    PCINT9  (PCMSK1 / PCIF1 / PCIE1)
A2    PCINT10 (PCMSK1 / PCIF1 / PCIE1)
A3    PCINT11 (PCMSK1 / PCIF1 / PCIE1)
A4    PCINT12 (PCMSK1 / PCIF1 / PCIE1)
A5    PCINT13 (PCMSK1 / PCIF1 / PCIE1)

Interrupt handler processing

The interrupt handler would need to work out which pin caused the interrupt if the mask specifies more than one (eg. if you wanted interrupts on D8/D9/D10). To do this you would need to store the previous state of that pin, and work out (by doing a digitalRead or similar) if this particular pin had changed.

You are probably using interrupts anyway ...

A "normal" Arduino environment already is using interrupts, even if you don't personally attempt to. The millis() and micros() function calls make use of the "timer overflow" feature. One of the internal timers (timer 0) is set up to interrupt roughly 1000 times a second, and increment an internal counter which effectively becomes the millis() counter. There is a bit more to it than that, as adjustment is made for the exact clock speed.

Also the hardware serial library uses interrupts to handle incoming and outgoing serial data. This is very useful as your program can be doing other things while the interrupts are firing, and filling up an internal buffer. Then when you check Serial.available() you can find out what, if anything, has been placed in that buffer.

Executing the next instruction after enabling interrupts

After a bit of discussion and research on the Arduino forum, we have clarified exactly what happens after you enable interrupts. There are three main ways I can think of that you can enable interrupts, which were previously not enabled:

  sei ();  // set interrupt enable flag
  SREG |= 0x80;  // set the high-order bit in the status register
  reti  ;   // assembler instruction "return from interrupt"

In all cases, the processor guarantees that the next instruction after interrupts are enabled (if they were previously disabled) will always be executed, even if an interrupt event is pending. (By "next" I mean the next one in program sequence, not necessarily the one physically following. For example, a RETI instruction jumps back to where the interrupt occurred, and then executes one more instruction).

This lets you write code like this:

sei ();
sleep_cpu ();

If not for this guarantee, the interrupt might occur before the processor slept, and then it might never be awoken.

Empty interrupts

If you merely want an interrupt to wake the processor, but not do anything in particular, you can use the EMPTY_INTERRUPT define, eg.

EMPTY_INTERRUPT (PCINT1_vect);

This simply generates a "reti" (return from interrupt) instruction. Since it doesn't try to save or restore registers this would be the fastest way to get an interrupt to wake it up.

Critical sections (atomic variable access)

There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).

Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

First ... when do you use "volatile" variables?

A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.

volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variables contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Turn interrupts off while accessing a volatile variable

For example, to compare count to some number, turn interrupts off during the compare in case one byte of count has been updated by the ISR and not the other byte.

volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  noInterrupts ();    // <------ critical section
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();      // <------ end critical section
  } // end of loop

Read the data sheet!

More information about interrupts, timers, etc. can be obtained from the data sheet for the processor.

http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

Further examples

Space considerations (post size limit) prevent my listing more example code. For more example code see my page about interrupts.


First of all, considering your comment: "I don't have time [...] to tackle arduino programming" - If you don't learn how to code, then you can't work with code (and that includes putting together libraries you find on the internet). And learning takes time, it's that simple.
I recommend you forget about those libraries and implement that easy task from scratch, so you actually learn something. The below code has the logic you ask for, try to understand what it does.
#define BUTTON_PIN   11
#define LED_PIN      13

bool button_was_pressed=false;

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

void loop() {
  if (digitalRead(BUTTON_PIN)) {
    if(!button_was_pressed) {
      for (int i=0;i<5;i++) {
        digitalWrite(LED_PIN,HIGH);
        delay(50);
        digitalWrite(LED_PIN,LOW);
        delay(50);
      }
    }
    button_was_pressed=true;
  }
  else {
    button_was_pressed=false;
  }
}

...pretty simple and it's only a few lines. You may want to debounce the button and use a non-blocking coding style, but that's a different chapter.
My advice is that you learn programming in a structured manner, e.g. by watching tutorials. A Q&A site is not the right place to do so, as we only answer questions.


Would this have any possible conductivity issues

Nope.

  or risk damaging the wires or board itself?

Nope.

  If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.

This is known as "potting". You can get special potting compounds, but hot glue is just as good.


Using Arduino Uno as USB to serial converter

You may also put Arduino in a reset state then Rx & Tx lines of serial converter will be free.


You're best off using strtoul():

messageType = message[0];
uint32_t data = strtoul(message + 1, NULL, 16);

The trick here is that message is just an array, so you can get the first letter with message[0]. Also, since C arrays are themselves just pointers to blocks of memory, message + 1 actually points to the location in memory of message[1], so you start processing the numbers from the second character in the string, thus omitting the first letter.

strtoul() takes a third parameter which is the base to decode from - 16 in this case for hexadecimal.

From there you can then use your bit shifting and masking to slice up your 32-bit value into your required sub values.


Beginner here, trying to start learning arduino, which starter kit should I buy?

You could do worse than a cheap 37-in-1 Sensor Kit from eBay and any Arduino board of your choice.

Also some Dupont Jumpers are essential.  Get a selection of M/M, M/F and F/F.


Convert uint8_t array to ascii character for serial transmission

You don't "convert" anything. A character is just a human representation of an 8-bit value.

Instead you just need to change what the compiler thinks the data represents (from a human perspective).  The simplest way of doing that is to either cast the uint8_t values to be char values, or to write each one individually as a raw value.

The latter way:

myBluetoothSerial.write(myData[0]);
myBluetoothSerial.write(myData[1]);
myBluetoothSerial.write(myData[2]);
myBluetoothSerial.write(myData[3]);
myBluetoothSerial.write(myData[4]);
myBluetoothSerial.write(myData[5]);

Or, with a loop:

for (int i = 0; i < 6; i++) {
    myBluetoothSerial.write(myData[i]);
}

or using a built-in variant of write that does the loop for you:

myBluetoothSerial.write(myData, 6);


Can I control a stepper motor with a sensor?

Yes, you can, they are completely independent, but that does not mean you can use e.g. an Arduino Uno to do the following:

Read the sensor
Based on the sensor values, control the L293D

In case you have doubt how to start, I suggest the following:

First, only use the HC-SR04 sensor (build the circuit, use an example program, check that it works)
Start over (remove the sensor), only use the L293D motor driver shield (with a motor), use an example program, check that it works)
Now combine both circuits and programs or if you feel confident enough, start making your entirely new program.


You'll need to program it trough the ISP port with an AVR programmer if you can't program it through a reset or double reset anymore. This can be done using another arduino. A tutorial is on the arduino.cc website.


TL;DR: Can't be done.
On a servo modified for continuous rotation, the signal you send sets direction and speed, not rotation angle. You can stop it, but you can't set an angle.
The sweep example will turn a continuous rotation servo in both directions, but I doubt it hits the angles you send it; it will just adjust speed and direction.
Without external hardware and feedback, like a limit switch, or a rotary encoder, there is no way of knowing what angle the servo is at, and no way to rotate to exactly 360° other than experimenting and "guessing" based on time and rotation speed.
You can then stop it by setting it to the PWM value for 90° or center position, which should set the rotation speed to 0.
On a servo, you can't have both continuous rotation with a set speed, and a set angle of rotation, without extra hardware.
Maybe a stepper motor would be a better choice for your application, or a "normal" servo with a gear that gives you the required rotation range.


Mechanical requirements for Arduino compatibility

Depends on what you define as "Arduino compatible".

My "Arduino Nano" is 'Compatible' but a whole other design.

Or well, it already separates here.
"Software compatible" working with the Arduino IDE and/or Libraries. In general, any board with ATMega 328P / USB or ICSP / Bootloader could be considered compatible.

But, however, for an "Arduino clone" being "Hardware compatible" you could also look at:

Pin placement (Thus being compatible with shields).
Using the same FTDI chip, thus being directly compatible with arduino
drivers (not sure)
Using "exactly" same electronic specifications.
Size and/or shape or even weight of the board.

Strictly, moving the ICSP header will make it 'incompatible' for some shields.
But, well, for most shields it won't be a problem. For casings that have an opening for the ICSP header it'll mostly just look funny.
By replacing the ICSP header it might touch components of other shields/casings and thus be not compatible with it.

(update)
The website and file below are from the arduino site and could thus be considered to be the 'standard' as it's set by arduino. You can however make your board how you want it and compatible with what you want. But changes will often make it incompatible with (some) shields/adapters.

The arduino website with specifications on the board:
http://www.arduino.cc/en/Main/ArduinoBoardUno

EAGLE files:
http://arduino.cc/en/uploads/Main/arduino_Uno_Rev3-02-TH.zip


Be careful with the 12V, the Arduino can not handle 12V at its pins.

The input can be the photoresistor with a resistor to 5V (not to 12V). Use a analog input to measure the amount of light.

The output can be with a resistor to the base of the transistor.
This is an example: PighiXXX transistor
Any unused digital output can be used.
Why do you need 12V for the led ? Is it a special led ?


SPI0 and SPI1 are used internally to access the ESP32’s attached flash memory. SPI2 and SPI3 are general purpose SPI controllers, sometimes referred to as HSPI and VSPI, respectively. They are open to users.
A quick google search shows:

So you can use IO5, IO18, IO19 and IO23.


The -AU and -PU suffixes on the part name indicate different packages. The former is used for the "32A" package (32-lead TQFP), and the latter is used for the "28P3" package (28-lead DIP). In plain English, the -AU is a surface-mount part, and the -PU is a breadboard-friendly chip.

As far as functionality, there is virtually no difference. The 32A package exposes pins for ADC6 and ADC7, which are not available on the 28P3 package, but they are otherwise identical. (Note that these pins are only used for the ADCs; they are not a member of any port, and thus cannot be used for digital I/O.)


Depending on how loud your audio signal is, you may be able to do it with just one capacitor and two resistors:

If your signal is quite quiet, though, you may need to amplify it using an op-amp. For instance:

That arrangement would double the volume of the audio. It also has the effect of inverting it, so you will need to invert your readings in software.

Also note that both of these methods will give you an AC waveform centred around 2.5V, so silence will be a reading of around 512, and it will go up and down from there. You can sample that audio waveform and do some basic (though quite slow on an Arduino) analysis of it, such as FFT to get the frequency content of the audio - great for visual effects...


How to reset an arduino while being able to know which button has been pressed?

Just found that I can change pins behavior. Inverting things a little bit, I can get my pins to work as LOW instead of as HIGH.

That way, I only need 1 button to trigger a reset and change pin status. Plus, grounding the reset is done temporarily because of the capacitor, which is what I need.

Here is the new schema

simulate this circuit – Schematic created using CircuitLab

New code

#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(BUILTIN_LED, OUTPUT);

  int buttonValueAtBoot = digitalRead(buttonPin);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("button was pressed");
    digitalWrite(BUILTIN_LED, HIGH);
  }

  // Avoid problem when the button is hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}


It's linking problem. More .o files included in linking declares identical global symbol eg. ISR(PCINT1_vect). Ideally write own makefile and compile via standard make. As hack you can loook in PinChangeInt.h conditional parts and make global definitions not to avoid *ISR()*s, e.g. #define __USE_PORT_JK


How to program an empty Mega2560 with an Arduino sketch?

If you buy an empty mega2560 IC. It won't contains any bootloader.
That means that you need an extra circuit, a programmer, to upload your HEX file into your MCU. "When to use the bootloader" questions link

But, if you buy your mega2560 from an Arduino provider, you should be able to order the MCU with the arduino booloader already programmed. Then a simple serial link from your PC to your MCU will suffice to program the MCU with your Arduino sketch using the Arduino environment. You could clone the serial part that you have on the Eagle files of the original Arduino to do this.

In summary:

Programming an empty chip requires a programmer
Programming a chip that has a booloader requires either a programmer, or a simple serial link.

You may also use another Arduino with the suited sketch as a programmer and use it for programming another empty MCU. There are examples of this on the web.


problem using GSM shield and GPS shield in one Arduino UNO R3

It appears the GSM library has its own conflicting copy of SoftwareSerial, and not necessarily a matching version unless you're lucky.

Not sure how well this would work but you can try removing the library reference to SoftwareSerial, and fiddle about to use the GSM library's SoftwareSerial.


Is it possible to program an Attiny85 with a USB-to-TTL converter?

Yes, it is possible.

Note that the FTDI chip (assuming that is what you have) can be accessed as either Virtual Com Port VCP or D2XX. Where VCP is the traditional method of using them as Serial Ports with avrdude calling "-c arduino -P COM3 -b115200". However the later D2XX method allows for the pins to be Bit Bang'ed.

One can see in this tutorial it is possible to call avrdude with a programmer of "-c ftdi". Assuming that the D2XX drivers are installed.

Where I see in the current releases 1.0.5r2 and 1.5.7's avrdude's config files that a programmer of type "avrftdi" is supported, as opposed to the article "ftdi"

However, that is not to say the IDE natively supports its. You will have to either call avdude manually. Or add the "avrftdi" to "\arduino-1.5.7\hardware\arduino\avr\programmers.txt" so that the IDE will be aware of it.

That all said I see "Tiny AVR Programmer" that are very in-expensive.


Your whole sending program is a complete mess, sorry to say:

First you create a SoftwareSerial port using the HardwareSerial pins. (Why on earth would you do that?)

Then you "begin" that SoftwareSerial port.

Finally you try and print Hello through the HardwareSerial port!

Either use SoftwareSerial OR use the hardware UART. You can't mix and match both. And since you are using the hardware UART pins, why even consider using SoftwareSerial?

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

void loop() {
    Serial.println("Hello");
}

OR, to use other pins than 0 and 1:

#include <SoftwareSerial.h>

const int bluetoothTx = 2;
const int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

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

void loop() {
    bluetooth.println("Hello");
}


There is no one single function for performing a calculation from a string like you are after in C.

Instead you will have to parse and split your string up into chunks and convert the two numbers into integers (maybe confirming that there is a + between them) and perform the calculation on those two individual integers.


What is happening in this basic push-button circuit?

what would the equation be to identify the amperage going into pin 2 when the button is pressed?

Once the button has been pressed for more than a few nanoseconds the current will be 0 (or as near as).

Immediately the button is pressed the formula is  I(t) = dQ(t) / dt since the input pin is a MOSFET gate and as such is seen (in simple terms) as a capacitor.

  What if I used the 3.3v on the arduino or a 9v battery instead?

The same.

  What is happening to the input pin when the button is not being pressed? (I assume it's a guarangeed LOW state due to any current being sapped by the GND, yes?)

It is pulled down to ground by the resistor.

  What would happen without the pull down resistor? A short when the button is pressed? What would happen without the ground being connected at all? Anything?

The input will be HIGH when the button is pressed, and floating (initially HIGH) when released.

  A tutorial for how to choose a pull down resistor I seen suggested a resistance value of 10 times the impedance of the pin. I'm not quite sure where to find this impedance value, but I have seen on an arduino tutorial "A 10K resistor is a good value for a pullup or pulldown resistor." Just not much of an explanation of why that value.

The main concern with a pullup or pulldown resistor is the current it demands from the power supply when the button is pressed. If it's too low then you will be wasting current. If it's too high then the input may take a while to turn off when you release the button.  10K is a "good" value since it is a good balance between those two factors.

The current from the supply is calculated as I=V/R, so 5/10000 = 0.5mA.  Low power systems may choose a higher value (100kΩ, say) to reduce the current.


Sum values, store them and print the last value

What you want to do is integrate the flow rate vs time curve. You have to keep track of the current flow rate. You also need to choose some unit of time measurement; this depends on how often you're sampling the flow rate. For instance, if you sample it every second, then you should convert your L/hr flow rate to L/s. This means a flow rate of 10L/hr is equivalent to 10L/3600s = 0.002778 L/s. So, if you get a reading of 10 L/hr for 10 seconds, 0.002778 L/s * 10 s = 0.02778 L of water flowed through your valve or whatever. An accumulating sum is what you need. You can try something like this:

#define INTERVAL 1000  // sampling interval in millisec
#define HR_TO_SEC 2.778E-4  // number of hours in a second

int curr_rate = 0;  // current flow rate in L/hr
unsigned long lastRead = 0;  // the last time the rate was sampled
float totalVolume = 0;

void loop(){
  if (millis() - lastRead >= INTERVAL){
    lastRead += INTERVAL;
    curr_rate = getFlowRate();   // or whatever function you call; should take << 1 sec
    totalVolume += curr_rate * HR_TO_SEC;  // update the volume
    Serial.println(totalVolume, 4);
  }
}

This rectangular method is reasonably accurate, depending on your application. If you want a better approximation, google "trapezoidal numerical integration" or "Simpson's method" if you want even better approximation.


Arduino - RF 433 Mhz transmitting string and but receiving ASCII values of those characters

Lokesh, to expand on what Majenko said when you transmit something over this sort of link you are transmitting either a 1 or a 0.  When 8 ones or zeros arrive you have a byte.  A byte has a value of between 0 and 255 and what this means is entirely up to the 'protocol' you are using.

In your case your sending program is sending a letter, lets say A.  Now the A that you are sending is held in memory as a byte with the value of 65, 65 is the ASCII [code] for A. So 65 is sent as 8 different transmissions to the other end of the link and is received, built back into a byte and your program receives a byte with the value of 65.  Your receiver program is using the same protocol as your transmitter program, so it 'knows' you don't meant the number 65, the colour green or an elephant riding a bicycle, you mean the character A.

To show that A you might need to cast the data you receive to a character i.e.

unsigned char rxData = 0;
Radio.ReceiveData (&rxData, 1);
Serial.println((char)rxData);


Absolute encoder vs Accelerometer for calculating angles

I'm hoping to get the X and Y coordinate accuracy within +/- 0.5mm. Is this accuracy feasible?

I'm only going to consider the A1 in your diagram since the accuracy of that will have the greatest impact in the final position. For the other angles any errors will have a smaller impact on the final position accuracy.

Take the most simple case, the arm is in a straight line almost completely in the X direction.

You want a Y reading of +/- 0.5 mm with an arm length of 1400 mm. That will require an angular accuracy of +/- 0.02 degrees.

Assuming you have a maximum travel of 90 degrees and you scale things such that your full ADC range is used linearly over that range then you require log(90/0.02)/log(2) = 12.1 bits resolution on your readings. So after allowing for the noise in all sensor outputs you're looking at a minimum of a 14 bit data required to give that level of resolution.

It's been suggested you use a pot connected to the internal 10 bit ADC.
Assuming you used your full ADC range over 90 degrees and the 10 bit ADC reading had no noise on it you would be looking at around 2 mm accuracy. In the real world I'd be impressed if such a system could reach 5 mm accuracy.

Assuming you are working vertically accelerators could work, they typically have at least 16 bit resolution on the output but are noisy, you'd need to average for a long time in a very stable environment to get the levels of accuracy needed. Probably a non-starter.

A very quick google didn't find any easily available encoders with the required accuracy. I'm sure they exist but they are probably going to be expensive. You could possibly use gearing to improve the sensitivity of a more standard part but that's adding mechanical complexity.

In other words the accuracy you're aiming for isn't easy to achieve. You may want to look at relaxing your requirements a little.


WebCam Face detection and tracking tutorial with Arduino Uno R3 and OpenCV 3.0 RC1 in Ubuntu 14.04

Forget Tserial.h lib. To solve your problem (for serial communication) I sugest you to use "read/write from/to a file" programming method. The serial ports may be written to just like you are writing in a file. In the facedetect.cpp (OpenCV's example), in the detectAndDraw() function (I'm using OpenCV 3.0) add: unsigned char MSB[1] = {0}; //
    unsigned char LSB[1] = {0}; //
    char serialPortFilename[]="/dev/ttyACM0";
    FILE *serPort = fopen(serialPortFilename, "w"); //

than add:

LSB[0]=r->x & 0xff;//
    MSB[0]=(r->x >>8) & 0xff;//

    fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

LSB[0]=r->y & 0xff;//
    MSB[0]=(r->y >>8) & 0xff;//

    fwrite((const void*)MSB,sizeof(unsigned char),sizeof(MSB),serPort);//
    fwrite((const void*)LSB,sizeof(unsigned char),sizeof(LSB),serPort);//

into the if (0.75 < aspect_ratio && aspect_ratio < 1.3) statement.

Finally don't forget to close the file

fclose(serPort);

Hope this will work for you!


Trouble making TMP102 work with any ADD0 other than ground

You see that little solder jumper block on the breakout board labelled "ADD0"?  You need to remove the solder from that.  It's currently connected in a pre-defined position and you trying to use the ADD0 pin is conflicting with that.


Arduino Ethernet Shield 2 stuck on EthernetServer::begin()

You must use these libraries:

#include <Ethernet.h>  -->  #include <Ethernet2.h>
#include <EthernetUdp.h>  -->  #include <EthernetUdp2.h>

More info at this link Arduino Ethernet Shield2


You'll need:

Emergency switch (it should be easy to cut the power off, even for small robots)
A chassis (you've found one already)
Motors (Obviously)
Motor control (Probably a dual H-bridge, think if you need reverse or not.)
Power (powering on (single use) batteries may not be your best option)
Controller (Arduino Uno, or something smaller or faster)
Sensors (Can be anything, depending on the requirements)

A way to communicate with the robot is also nice, often wireless (bluetooth/wifi/443mhz).

And also, it will be nice if the robot fits some kind of purpose, but this could be added later.
You could think of the robot having to pick up and carry something, extinguish a flame etc.

I advise to check out one of the many tutorials on building a robot, they often have a detailed parts list (sometimes even shopping links).


one Arduino with RS485 and Ethernet shields: does this work?

Should be no problem.

The ETH shield uses SPI to communicate with a W5500 chip. That chip does most of the network processing for you.

The 485 shield just connects to the UART TX and RX pins. It's just serial communications with a couple of control pins from there on out.

Neither use any pins that the other one uses.


Kinovea is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).


Can i run brushless ESC from any digital pin of arduino

It should work.

The Servo library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.


Seems like I cant control 4 stepper motor at once

The variable name BR is already used somewhere else.
Use a different variable name
AccelStepper FL(1,stepPin,dirPin);
AccelStepper FR(1,stepPin2,dirPin2);
AccelStepper BL(1,stepPin3,dirPin3);
AccelStepper BackRight(1,stepPin4,dirPin4);


What do the numbers behind lcd (0x27) mean?

Assuming You're using the same LCD library I'm using, there is a longer form of the constructor that takes pin assignments for the different pins on the I2C module, as Majenko says.

I'm at work, so I don't have access to my code, but your constructor looks a whole lot like the one I use for my module, which has non-standard pin assignment. (I got my LCD modules from oddWires, and they came without documentation. I had to do quite a bit of detective work to figure out how to make them work.)

EDIT

I use the Newliquidcrystal_1.3.5 library in my project, to interface the above-mentioned oddWires I2C LCD display. That library has various constructors, one of which takes all the parameters you list. Those extra numbers indicate the pins that connect to the I2C module.

My oddWires LCDs need exactly the settings you list in the constructor. Your milage may vary.

The long form is defined in the library header with

LiquidCrystal_I2C(
    uint8_t lcd_Addr,
    uint8_t En,
    uint8_t Rw,
    uint8_t Rs,

    uint8_t d4,
    uint8_t d5,
    uint8_t d6,
    uint8_t d7,
    uint8_t backlighPin,
    t_backlighPol pol
);

From the naming of the parameters you can deduce most of them:

En is an enable line
Rw is a read/write line?
Rs is ?
d4-47 are the data pins
backlightPin is the pin that turns backlight on and off
pol indicates the backlight polarity (POSITIVE probably means pull the line high to enable the backlight.


You seem to be suffering from three problems here:

A lack of understanding how the button's pins are configured
A lack of understanding of how breadboard works
A strange notion (that I have seen around a lot recently for some reason) that a button needs to be driven from an output.

For the button's pins you should know that the pins are paired on the long sides. That is, if you hold the button so it is in "landscape" orientation (wider than it is high) the two upper pins are joined together, and the two lower pins are joined together.

Breadboard consists of strips of connections which, in your diagram, would be running horizontal. Pins plugged into holes horizontally in line with each other on the same side of the board (the gap in the middle is a gap in the connections too) will be connected together.

Finally for the wiring of the button. Nowhere in the tutorial you link to does it ever mention connecting the button to two IO pins. The button should only be connected to one IO pin. It also connects to +5V and, through the resistor, to ground.  Wire it up exactly as it shows you in the tutorial and make it work like that before you try fiddling with it.


What you are asking for is not simple, especially since you have this
power function that can be hard to approximate.

First, you have to figure out the range and the required precision of
each of the floating point numbers you are manipulating. You wrote that
readSensorData() returns 7 decimals. If by that you mean that you
require a relative accuracy of 10−7, then I predict it will
be extremely hard to optimize this as a fixed point calculation. If
you can live with a much lower relative accuracy (say, around
10−3 or 10−4), then it may be worth trying
something.

I would start by writing the expression of height as

height = f(sensval/sensinitial-1)

where

f(x) = 44330 * (1 - pow(1+x, 0.190295))

I would expect sensval and sensinitial to be close to one another,
which would imply that x is small. At this point you should try to
estimate the likely range for x, because the feasibility of what
follows strongly depends on it. Next step is to approximate f() by a
polynomial. A simple Taylor
expansion gives:

f(x) ≈ -x*(8435.78-x*(3415.25-x*2060.2))

You may start by trying this, just to see if it looks kind of OK or
completely hopeless. You will notice that the above approximation is
great when |x| is tiny, but it very quickly degrades as |x|
increases. This is why you don't use Taylor expansions in real
approximations, I showed it to you only to give you an idea of the
feasibility of a polynomial approximation.

To do better than Taylor, you must specify the range of x, then you
can scale that range to [−1, 1] and expand on the basis of the
Chebyshev
polynomials. And
then you could fine-tune to get the optimal
polynomial, but
it's likely to be only marginally better than the Chebyshev expansion.

If all this works with a reasonable polynomial degree (say, no more than
5), then you can start converting to integer math. If it doesn't, you
may try a different type of approximation, like interpolating over
tabulated values. If the problem is the range of x being too large,
you may instead write the power function as

ab = 2b × log2a

and write polynomial approximations to the base-2 exponential and
logarithm (the polynomials only needs to cover one octave). If you try a
rational fraction approximation, beware that divisions are slow on the
AVR platform.

If all the above looks like too complex, or too much work, then just get
a faster CPU, or try to live with your program being slow.


Yeah, you can totally make that work with an Arduino Uno. You would have 14 digital pins, as well as 6 analog pins that can also be used as digital pins.


As others have said, this issue is created because the parseInt function reads in characters until it receives a non numeric character or until it reaches the timeout value, which is set at 1000 ms (1 second). There are a couple of ways to fix this, order most difficult to least:

Instead of just sending a number, send a number and then a letter at the end. So instead of sending "123", you would send "123x".  parseInt() will immediately return when it hits the x.  However, you'll still have the x in the stream so you'll need to manually read it and discard it.
Make the value that is sent a set number of digits - say 4 for example.  Since you know it will be four digits, use a for loop to read in four characters and build it into a number by multiplying.  If you read in digit1, digit2, digit3, digit4 then the number is 1000 * digit1 + 100 * digit2 + 10 * digit3 + digit4.
Make the timeout value for parseInt() smaller.  parseInt() inherits from the Stream class so you would use Serial.setTimeout(50) in the setup function to change it to a 50 ms timeout.


Very simple. It takes only 3 steps.

Blink an led stripe with no delay.
Blink two led stripes, using the code developed in step 1.
Enjoy your blinking let stripes.

edit: since you seem to be struggling, here is one (of countless) way(s) to do #1 above.

//blinky_ledx2.ino

//blink two led strips independently

//blinky rate
#define LED_DLY         100     //duration for led1, in ms
#define LED             12      //led to be blinked

int led = 13;

//run user routine, non-blocking
void NB_run(void (*func_ptr)(void)) {
    static uint32_t millis_next=0;                          //next match point

    if (millis() >= millis_next) {                          //time is up
        millis_next += LED_DLY;                             //advance match-up time
        func_ptr();                                         //execute user function
    }
}

//blinky example
void blinky1(void) {
    //blink LED
    digitalWrite(LED, !digitalRead(LED));
}

void setup() {
    // put your setup code here, to run once:
    pinMode(led, OUTPUT);
    pinMode(LED, OUTPUT);                                   //LED as output
}

void loop() {
    NB_run(blinky1);                                        //run blinky1 at set intervals for LED
    digitalWrite(led, !digitalRead(led));                   //blink led
}

the heart of this is NB_run() -> it executes func_ptr() once the set time has been reached. otherwise, it returns without doing anything, as shown in the example below.

D13 is blinked constantly in the main loop, while D12 is blinked based on LED_DLY, in a non-blocking fashion.

I purposely wrote NB_run() so that it needs additional "parameterization" to run multiple tasks - what you have here is the basis of a generic framework for a rudimentary pseudo multi-tasker. it is not difficult at all for you to extend the code to run 2 stripes.

good luck.

edit2: it was pointed out to me, quite correctly, that something like this can be done via rtos. true, but a typical rtos has lots of overhead and requires a more substantial hardware to support.

one exception is macro-based rtos, like protothread. in that particular implementation, you will see that there is little gain in terms of code complexity, but some stylistically.

here is an implementation of running two tasks concurrently via protothread, only code for one task is shown, however.

//thread 1
PT_THREAD(protothread1(struct pt *pt, uint32_t pr)) {
    static uint32_t time_next=0;        //time for the next blinking

    PT_BEGIN(pt);
    while (1) {
        PT_WAIT_UNTIL(pt, millis() > time_next);
        time_next += pr;                //advance time to the next match up point
        toggleLED(LED1);                //run user task - blink led1
    }
    PT_END(pt);
}

void loop() {
    protothread1(&pt1, LED1_DLY);       //running thread1
    protothread2(&pt2, LED2_DLY);       //running thread2

}

you can see that it retains largely the code structure presented earlier.

here is the outcome of that code, blinking D12/D13 at different rates.


Powering LED strips with two power banks and they randomly change different colors when i use the second power bank

These are USB power-banks? You need a way to tie the grounds together somehow. Try tying all the ground lines from your LED strips together and also connecting a wire from one of the LED strips to a ground line on your Arduino.

The USB connections should connect ground between the power bank and the device it's connected to, so by tying the grounds on the LED strips together, that should connect the grounds on the power banks as well.


There is a way to initialize an Arduino String with a given memory length: see reserve() method. It will generally greatly reduce or entirely eliminate memory fragmentation, if you can afford reserving a sufficient amount of memory in advance.

Just keep in mind that this is a "soft" boundary: once your string gets longer than the reserved amount, String will quietly resume reallocating memory with all those typical consequences.

It is not clear what you plan to do if the pre-reserved amount of memory proves to be insufficient. Fall back to "memory fragmentation"? Anything more elaborate than that will be pretty much as complex as performing manual management of a char[] array.

All the functionalities you requested are present for char[] arrays as well, might just require a few more lines of code. And it is not clear why one might "need" comparisons to be == specifically.

This might also be an XY problem. Why are you trying to concatenate all these requests in memory? What are you planning to do with them once you are done "concatenating"?


Connecting 5V arduino logic with 12V car logic

I found this that may be helpful to you.  this circuit allows for bidirectional communication between automotive K-line ECUs and an arduino.
 K-Line Interface circuit


Arduino SD count files and open last, How to?

Consider using the exist() method found in the SD.h library you already are including in your program.  Assuming you will create no more than 99 files and the last file created will have the highest 2 digit value as part of its name, test for the existence of the file log99.txt.  If not found, decrement the 2 digit number and test for the existence of file log98.txt.  Repeat this process until you find the newest file created.


Program arduino via USB while using a Bluetooth module (HC-06)

The link in question was correct... you do need to unplug it.

The Arduino's serial chip uses pins 0 and 1 to communicate with the ATmega 328 PU chip onboard, thus you have two independent devices connected to the same wires and both the Arduino main chip and the Bluetooth module are trying to communicate at the same time (rendering all data unreadable by the computer).


If I understood your question correctly, you're looking for something like this:

static const byte PIN_NUMBER[4] = { 0, 2, 5, 6 };
static const char *PIN_NAME[4] = { "A", "B", "C", "D" };

// and use them like this:

void Log(byte index)
{
  byte val = digitalRead(PIN_NUMBER[index]);
  Serial.print(PIN_NAME[index]);
  Serial.print('|');
  Serial.println(val);
}

void setup()
{
  for (byte i = 0; i < 4; ++i) pinMode(PIN_NUMBER[i], INPUT);
}

void loop()
{
  Serial.println("PIN|VALUE");
  for (byte i = 0; i < 4; ++i) Log(i);
  delay(1000);
}

Also, in the special case of "A", "B", "C", "D" as pin names, you don't really need the PIN_NAME array, instead of

Serial.print(PIN_NAME[index]);

you can use:

Serial.print('A' + index);


Is it advisable to use Serial.write in an ISR when loop() routinely uses Serial.read?

Reading and writing of serial data are separate functions. When you .write() you just append the data to the TX buffer. When you .read() you just take the next character from the RX buffer.
All actual sending and receiving, and filling/emptying of the buffers is done inside the ISRs for the UART module.
That said, you really shouldn't use Serial inside an ISR. This is because the sending and receiving is done by an ISR, and if you are in your ISR then the sending can never happen until you leave your ISR.  For the odd occasional byte it's not really a problem, but if the TX buffer fills up Serial.write() will block until the TX ISR has sent some data - which won't happen since your ISR is blocking the TX ISR.
So it's best to avoid any Serial operations inside an ISR. Instead you would normally set flags and values in an ISR then check for those flags in loop() to report anything.


Marlin g-codes applicable for a Melzi Sanguino board

As already written in the comments the software defines what G-Codes are taken by a (printer) boardBUT Even if the software has the same name (eg Marlin) it might behave different on different boards because of:

different release versions for different hardware
different release repositories being ahead or behind the master repo
hardware specific features a G-code triggers (most unlikely)

The clever way is to go from features I need to software supporting thosefeatures to boards supported AND useable for my hardware to controll (3d-printer/CNC-router/laser-cutter aso)
  -


keypad code is not working and produces wrong numbers

The first thing you need to do is just look at what the problem is.  Create a new sketch and paste this code into it.

#include <Keypad.h>

const byte ROWS = 4; // declare the rows of the keypad
const byte COLS = 3; // declare the columns of the keypad

// Define the Keymap
char keys[ROWS][COLS] =
{
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};

byte rowPins[ROWS] = {2,3,4,5}; // Connect keypad’s pins to these Arduino pins.
byte colPins[COLS] = {6,7,8};   // Connect keypad’s pins to these Arduino pins.

// Create the KeyPad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void keypadEvent(KeypadEvent eKey)
{
    // When the KeyPad will be pressed, the results will appear on the serial monitor.
    switch (keypad.getState())
    {
    case PRESSED:
        Serial.print("Enter: ");
        Serial.println(eKey);
        delay(10);
        break;
    }
}

void setup()
{
    Serial.begin(9600);
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop()
{
    keypad.getKey();
    delay(20);
}

You should recognise it, its a reformatted version of your code (pretty code is easier to debug), but with only the keypad bits in.

Now load that onto your hardware and write down what number is shown when you press 1 three times.  Do it three times just to make sure its the same number and you haven't got something totally obscure happening. Repeat for the other 11 buttons.

If 7 and 3 always give you 3 and 6 then you have got your row and column wires crossed.
If 7 always gives you 1 and 9 always gives you 3 then the wires for row 4 and 2 are crossed over. etc
If you can't work out the patter post your findings and I'm sure someone will solve the puzzle.

As for problem 2, don't even go there until you know what you are typing. :)

Hope that helps


Sorry to dredge up an old thread (well, really only replying to one that got robo-dredged :), but maybe this will help someone someday.

A /dev/cu.<something> is a unix port designation. "cu." meant a port used for modems, back in the mists of time but probably isn't relevant today. But what we do learn from it is that the OP is probably using a Mac, and for sure, not Windows.

"/dev/cu.usbmodem1421" is a typical device name for an Arduino as seen by a Mac on a particular one of its USB ports - the numeric part varies according to which Mac USB port the Arduino is connected to each time.

Arduinos & FTDI devices do not need additional drivers on Mac OS (that may not be true for other, non-FTDI USB-to-serial devices).

In this case, the OS already reports seeing (what looks like) an Arduino. The suggestion already put forward, checking the board-type and port selections in the IDE's 'Tools' menu, is the place to start.


I want turn the led off only when the input is low for a prolonged period of time and not when there are ups and downs in sound signal

It's very related to the debounce algorithm (used for debouncing switches/keys), but consider a button 'bounce' as a cry. The time is much longer (seconds, to even minutes).

See here the debounce explanation:

https://www.arduino.cc/en/tutorial/debounce

As soon as the baby starts crying, you want the LED to be turned on (almost) immediately, so use a short 'debounce' (or in this case: cry on) time for a rising edge (start crying), something in ms or a second maybe (I assume it is that time critical).
However, for detecting stopping crying, you probably want a much longer time, maybe even a minute (but I leave the exact timing requirement up to you).


Can't figure out how to distribute the power

The best option is to connect the 5V/2A output of the UBEC to the 5V pin on the Arduino. In my experience, 7.4V is not enough to feed into the input jack on an Arduino especially if it is from a battery, as the voltage will drop when current is being drawn by other loads. I have built an Arduino controlled robot using a 6V NiMH battery and brushed DC gearmotors (so no ESCs or UBEC) and used a $5 5V 1A step-up/step-down converter so that even if the battery voltage dropped below 5V, it could still power the board. However, since you have a UBEC that is not in use, use it. Note that if you put voltage into the 5V pin, disconnect it when you are connecting the arduino over USB or you might damage your board.

As for inductive charging, I don't know of any off-the-shelf solution designed for charging a 2S lithium ion battery. The best option for charging would probably be an easy way to open the ball to access the batteries.


How to stop OLED flicker when using SSD1306Ascii.h?

Your loop is repeatedly writing and clearing the display, nearly as fast as possible (minus the 1ms delay at the bottom), which is the reason for the flicker you're seeing. If instead, you only update the display when something changes, it will look much smoother. Even a clear-and-rewrite the entire display when something changes (assuming the changes are infrequent) will be a major improvement. Of course this assumes you'd eventually be writing dynamic data; your test program, of course, writes and re-writes static data.

Update:

  If I run the same code structure with Adafruit library there is no
  flicker, even with no delay in the loop.

Can you compare the two libraries to see what they do differently?

  The Adafruit library does not have this issue, but I've been told uses
  a lot of memory

There's a likely clue: Adafruit may be buffering the display contents in memory so it can find out which character positions changed and update only those. That would be a classic time/space trade-off.


Parse data from sensor without delimeters

actually I don't think it is all mixed up

as per geometrikal use the markers to parse the data stream

I believe your above sample data started mid-stream during the 0xF8 of the wave form.

F8,...
...,7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0,36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0,24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0,35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0,5E,60,61
F9,0
FA,0
FC,1A
FB,0
F8,62,62,62,63,0,...

I believe reading this as a finite length does not portray the data for easy interpetation. Given that 0xF8 is a variable length protocol.

Where the reparse of your data initially appears to be legitimate parse.

That said I do read the SPO2, Pulse as zero. Where it may be likely the sensor has not finished its reading and auto gain cycles.


Where is documentation on Arduino's Internal Interrupts?

The vector names are all defined within the header files for the main chip in the compiler.  The IDE doesn't need to know anything about that kind of thing - that's all up to the compiler.

Look for the files "lib/avr/include/avr/io*.h within the compiler in your chosen IDE.  In there are all the chips and all their definitions.

For instance, the ATMega328P definition (iom328p.h) has this list:

#define INT0_vect         _VECTOR(1)   /* External Interrupt Request 0 */
#define INT1_vect         _VECTOR(2)   /* External Interrupt Request 1 */
#define PCINT0_vect       _VECTOR(3)   /* Pin Change Interrupt Request 0 */
#define PCINT1_vect       _VECTOR(4)   /* Pin Change Interrupt Request 0 */
#define PCINT2_vect       _VECTOR(5)   /* Pin Change Interrupt Request 1 */
#define WDT_vect          _VECTOR(6)   /* Watchdog Time-out Interrupt */
#define TIMER2_COMPA_vect _VECTOR(7)   /* Timer/Counter2 Compare Match A */
#define TIMER2_COMPB_vect _VECTOR(8)   /* Timer/Counter2 Compare Match A */
#define TIMER2_OVF_vect   _VECTOR(9)   /* Timer/Counter2 Overflow */
#define TIMER1_CAPT_vect  _VECTOR(10)  /* Timer/Counter1 Capture Event */
#define TIMER1_COMPA_vect _VECTOR(11)  /* Timer/Counter1 Compare Match A */
#define TIMER1_COMPB_vect _VECTOR(12)  /* Timer/Counter1 Compare Match B */
#define TIMER1_OVF_vect   _VECTOR(13)  /* Timer/Counter1 Overflow */
#define TIMER0_COMPA_vect _VECTOR(14)  /* TimerCounter0 Compare Match A */
#define TIMER0_COMPB_vect _VECTOR(15)  /* TimerCounter0 Compare Match B */
#define TIMER0_OVF_vect   _VECTOR(16)  /* Timer/Couner0 Overflow */
#define SPI_STC_vect      _VECTOR(17)  /* SPI Serial Transfer Complete */
#define USART_RX_vect     _VECTOR(18)  /* USART Rx Complete */
#define USART_UDRE_vect   _VECTOR(19)  /* USART, Data Register Empty */
#define USART_TX_vect     _VECTOR(20)  /* USART Tx Complete */
#define ADC_vect          _VECTOR(21)  /* ADC Conversion Complete */
#define EE_READY_vect     _VECTOR(22)  /* EEPROM Ready */
#define ANALOG_COMP_vect  _VECTOR(23)  /* Analog Comparator */
#define TWI_vect          _VECTOR(24)  /* Two-wire Serial Interface */
#define SPM_READY_vect    _VECTOR(25)  /* Store Program Memory Read */

Further, _ISR() is just a macro.  It creates a suitable function prototype for your function, and if that happens to include a valid vector then it becomes an ISR.

#  define ISR(vector, ...)            \
    extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)

That is defined in "avr/interrupt.h" in the compiler's include files.  With your gibberish you'd end up with:

extern "C" void GibERisH (void) __attribute__ ((signal,__INTR_ATTRS));
void GibERisH (void) {
    // something here
}

With a real vector you'd get the more meaningful:

extern "C" void _VECTOR(7) (void) __attribute__ ((signal,__INTR_ATTRS));
void _VECTOR(7) (void) {
    // something here
}

Of course, _VECTOR() itself is a macro:

lib/avr/include/avr/sfr_defs.h:#define _VECTOR(N) __vector_ ## N

So that further expands out to:

extern "C" void __vector_7 (void) __attribute__ ((signal,__INTR_ATTRS));
void __vector_7 (void) {
    // something here
}

And magically, that new function name of __vector_7 is directly referenced from the standard vector handling code in the startup library crt of the AVR compiler.


How do I properly trigger the ATMega328 reset pin via software so that the bootloader runs and the firmware can be updated via RX/TX pins?

You wrote:

  void(* resetFunc) (void) = 0;

This seems to me like an approach worth trying, except that the function
address is wrong. At address zero of the flash you have the start of the
user's code. The bootloader, if you do use one, lives at the end of the
flash. The start address of the bootloader depends on its size, and is
configured by setting some fuses on the chip. If you are using the
popular optiboot (the bootloader of the Uno), you have to jump to
exactly 512 bytes before the end of the flash, i.e.:

void (*resetFunc)(void) = 0x7e00;

Oh, wait... the flash is organized as 16-bit words, so you may have to
use the wordwise address instead:

void (*resetFunc)(void) = 0x3f00;

But do note that, unlike a real hardware reset, this approach does not
reset the peripherals to their normal initial state. You may want to do
it before jumping to the bootloader.

Edit: I have disassembled a test program that does this kind of
call-by-pointer, then double checked the documentation of the icall
instruction. It appears that the function address you provide is
indeed interpreted as a word-wise address, so you should write half the
byte-wise address. If you write anything larger than the size of the
flash (0x4000 = 16 kilowords), the most significant bits get
lost, and the address gets reduced to the correct range modulo the flash
size.

That is, if 0x7800 worked for you, then presumably the correct address
is 0x3800, i.e. 2 kilowords (4 KB) before the end of the
flash. This is quite a large bootloader, and the largest size supported
by the ATmega328P. Are you sure it is righ? Aren't you sliding through
some uninitialized flash before hitting the bootloader? Here is a table
that gives the bootloader's start address as a function of the amount of
memory reserved for it:

reserved size  start address
    512 B         0x3f00
     1 KB         0x3e00
     2 KB         0x3c00
     4 KB         0x3800

Note that the Arduino Uno uses optiboot, which fits into the
smallest size that can be allocated to a bootloader (512 bytes).


Arduino Web Server: Receiving response from web form

Your form method is set to GET. In this case, when Submit is clicked, the client/browser sends request with values in URI:

GET /index.html?data=user_value&default_name_of_button=Submit HTTP/1.1
...more lines to follow...

These HTTP header lines will be available on your EthernetClient instance, retrieve them line-by-line using connected(), available(), read() methods. Then parse the line, find the user_value.

Please note that browser retrieves your page (to display it) using GET method too, in that case URI will be like:

GET /index.html HTTP/1.1
...more lines to follow...

It is recommended to use POST method to submit form values. Example content section (before content, server must send HTTP header - check Arduino Web Server example)

<form method="POST" action="foo.php">

First Name: <input type="text" name="first_name" />

Last Name: <input type="text" name="last_name" />

<input type="submit" name="action" value="Submit" />

</form>

In this case the values are returned in content section:

POST /foo.php HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://localhost/test.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 43

first_name=John&last_name=Doe&action=Submit

Tutorial on HTTP headers:

https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039


How to use Ultrasonic Sensor's trig pin, and why it is needed?

Yes, you do need it.

The purpose of the TRIG pin is to cause the module to send out a "Ping".  It's what makes the whole thing work.  As soon as the TRIG pin goes HIGH then LOW (for a period of not less than 10µs) the internal clocks start ticking.  8 cycles of 40KHz audio are sent out of the transmitter and it starts counting how long it takes for the echo to arrive.

If you don't use the TRIG pin the module won't be able to do anything at all.


Interrupt variable not getting called while executing another part

volatile byte _incomingFlag = 0;
 void onIncoming () {
             _incomingFlag = 1;
            Serial.println(F("You got an interrupt"));
            mySerial.println("ATH0");

        }

Regardless of what your purpose is there, you cannot successfully do serial prints inside an ISR. All bets are off if you do that.

In fact you are doing two prints - is one SoftwareSerial?

If you must have a debugging "flag" turn on an LED. Doing serial printing requires interrupts to be on, and they are off inside an ISR.

Note: You may get the display once, and therefore you think it works. As soon as the serial buffer fills up (probably 64 bytes) then it will just block indefinitely. Your message "You got an interrupt" is already 22 bytes if you count the trailing carriage-return/linefeed.

More detailed explanation

In your main loop, every time through it, you are printing either:

_incomingFlag: 1

or

0
not getting value

Therefore the serial buffer will be definitely full (or almost full). It can't empty the buffer if you are cramming this stuff into it every time through loop.

So now you have an incoming call. You set _incomingFlag to 1, then try to do this:

    Serial.println(F("You got an interrupt"));

That blocks, because if can't fit all that into the output buffer, and the program then hangs, because the buffer is not emptied inside an ISR.