Switching a Solenoid Using Arduino's 5V Output?

Note: this answer demonstrates using the 2N3904 NPN transistor for all of the calculations, since that's what's in the schematic in the question. However, after writing the answer, I noticed the words at the end of the question state it is a D882P (also an NPN type) transistor. So, just follow my methodology here but use the appropriate values for your NPN transistor type, which you can obtain from the datasheet. A quick Google search for "d882p datasheet" reveals this as a potential datasheet.
2N3904 is an NPN transistor (datasheet), as opposed to a PNP transistor, so it must be connected directly to GND and switch the low side of the circuit only, so wire it like this instead:

simulate this circuit – Schematic created using CircuitLab
Notice I've added a diode, D1, to dissipate inductance-induced voltage spikes created when electromagnetic fields (a form of energy storage) collapse in the inductor each time you turn the switch OFF. This diode, due to its function (not type), is called a "flyback", "snubber", or "clamp" diode. Again, it protects the transistor and other components from inductance-induced voltage spikes from the relay coil/inductor. When a voltage spike occurs, it will simply travel around that loop through the diode, relay, and resistor R2 again and again and again until it has all been dissipated as heat in those components and there is no more voltage spike remaining.
I've also added a resistor R2 to limit current through the relay coil. You'll have to size this appropriately to get the correct current through your relay coil, based on the relay's datasheet. If your relay's datasheet says to hook up the relay to 12V directly, you can remove this resistor.
And you'll definitely need a base resistor (R1 in my circuit) or else you'll burn up your Arduino pin.
First, let's collect some necessary values from the Datasheet. These will be used in the calculations below:

VBE(sat) = 0.65 to 0.95V.

This is the diodic voltage drop from Base to Emitter when the transistor is "saturated", or fully ON.

hFE_min = 30

Notice in the screenshots below that I have crossed out all of the 2N3903 transistor hFE entries so they don't distract us from the 2N3904 entries, which is the transistor type I'm using for this example. I then chose the lowest hFE entry for this transistor, which is 30.
This is the "guaranteed" minimum, or worst-case, DC current gain. The formula is simply: I_max_permitted_from_Collector_to_Emitter = gain * I_Base_to_Emitter. So, if your gain is 30, for example, and you drive a base current of 5mA from Base to Emitter, then the "guaranteed" maximum possible current allowed from the Collector to the Emitter will be 30 gain * 5mA = 150mA. Again, this is not what you will get into the Collector, this is what you could get before the transistor itself starts limiting the current into the Collector rather than your load limiting the current through the Collector.

Ic_max_continuous = 200mA

This is the max continuous current you can get from Collector to Emitter without overheating the transistor (assuming, I think, you have adequate cooling through conduction and possibly even convection and radiation via heat sinks--I need to brush up on the thermal and power equations myself). The datasheet may specify if a heat sink is required to achieve this current, but regardless, you should keep your continuous current down to about half this value or less if possible, as the device may reach crazy high temperatures of like 150 C or something with this current and no convective cooling or heat sink. For short bursts, hitting this current is just fine.

Here are some screenshots of where to find these values in the datasheet:

Notice in this next image I've crossed out all of the 2N3903 hFE lines so they don't distract us from the 2N3904 entries, which are for the transistor we care about in this example. Choose the lowest hFE value as the gain you will use in your estimates in order to have a "conservative" estimate, virtually guaranteed to fully turn on your transistor in all cases (ie: for all Collector current values you might like to switch on and off).

Now, let's calculate a Base resistor value for an NPN BJT transistor, assuming your goal is to fully turn on (saturate the Base-Emitter channel of) the transistor:
VBE(sat) has a diodic voltage drop of 0.65 to 0.95V, so your resistor would have to burn off 5 - 0.95 = 4.05V to 5 - 0.65 = 4.35V. Let's just use the lower 4.05V value so we will size for higher currents and faster turn-on speeds.
Your minimum hFE (gain) value for the 2N3904 transistor (not the 2N3903) is 30. Maximum continuous Collector current, Ic is 200mA, so let's increase that by a factor of 2 to 4 and size for 200mA * 3 = 600mA to 1) more fully saturate the Base to Emitter channel and get closer to full turn on under all cases, 2) get faster turn-on, and 3) overcome the fact that decreased gain occurs at higher Collector currents. In Figure 15. DC Current Gain, from the datasheet, for instance, shown below, it shows that the normalized gain decreases from ~0.28 at 100mA Collector current to ~0.13 at 200mA Collector current, which means that the gain of 30 found in the datasheet at 100mA Collector current indicates the gain at 200mA Collector current will actually be approximately 30 gain/(0.28/0.13) = 13.9 gain. Simply multiplying the Collector current we are sizing for by a factor of 2 to 4 (3 in our case) accounts for this fact, so we will use 600mA instead of 200mA in our maximum Collector current calculations below.

So, 600mA / 30 gain = 20mA Base to Emitter to get rock solid turn-on performance. Arduino can do up to 40mA per pin so this is Ok. Note that I recommend 30mA max per Arduino pin (for the ATmega328 microcontroller), and there is also a combined output limit for the ATmega328 microcontroller of 200mA for all pins combined, which you should keep in mind. I describe this on my website in my article "Arduino Power, Current, and Voltage Limitations" here.
V = IR, so R = V/I, so resistor, R that we need = 4.05V/0.020A = 202.5 Ohms. This is the minimum recommended base resistor size. Don't go too much smaller than 200 Ohms, if you go smaller than that at all. A 100 Ohm resistor, for instance, would allow a maximum base current of I = V/R = (I intentionally use the higher voltage value here) 4.35V/100 Ohms = 43.5mA, which could damage your pin.
Don't go larger than 600 Ohms or else you risk not turning on the transistor fully by not saturating the Base to Emitter channel. A 600 Ohm resistor would give you a guaranteed max Base to Emitter current of I = V/R = (I intentionally use the smaller voltage value here) 4.05V/600 Ohms = 6.75mA, which with a gain of 30 would give you a max Collector current (based on your relay coil resistance now) of 6.75mA * 30 gain = 202.5 mA. However, as indicated from Figure 15 shown above, a more realistic gain at 200mA Collector current might be only 13.9, which means your maximum allowed Collector current with a 600 Ohm resistor would be 6.75mA * 13.9 gain = 93.8mA. But, at this current your gain would actually be > 30, not 13.9, which leads back to the 200mA Collector current number. You can see this is a juggling game of numbers since the gain is NOT constant NOR linear, but rather is a function of Collector current, as shown by Figure 15 above. So, perhaps your actual maximum allowed Collector current with a resistor of 600 Ohms would be more like 130mA or something. The point is: any larger of a base resistor than 600 Ohms and you most likely won't be able to achieve the transistor's rated maximum continuous Collector current even if you wanted to. So, there's a reasonable R value range!: 200 Ohms to 600 Ohms, perhaps even leaning more towards the 200 Ohms side if you expect to have high momentary Collector currents anywhere near your maximum continuous Collector current rating of 200mA.

Additional notes on high-side vs low-side driving with NPN BJT or N-Channel MOSFET transistors, for clarity:
An NPN transistor can switch high-side voltages too--you just have to drive the necessary Base to Emitter current is all (and don't exceed any maximum ratings)! That's it! So...if you try to drive the high side, think about it: you turn it on with 5V so your voltage from Collector to GND can't exceed ~5V now because as current starts to flow through the collector, voltage would come up on the Emitter side until your base current no longer flows. Your system would be fighting itself. Even if you gave it 12V before the Collector you'd never see more than ~5V at the Emitter, assuming your Base drive voltage was 5V. If you can design around it, go for it, but generally the "easy" or "normal" way to do things is to use NPN to switch low-side voltages and PNP to switch high-side voltages.
The same goes for N-channel and P-channel MOSFETS. Use N-channel to switch low-side voltages and P-channel to switch high-side voltages, UNLESS you are doing some fancy driving (again), of N-channel to switch high-side voltages, as N-channel MOSFETs are more efficient and can switch higher currents than their equivalent P-channel pairs, due to some electron hardware mumbo jumbo stuff.
Keywords: transistor sizing; BJT transistor circuit calculations, equations, and datasheet; arduino and electrical engineering: transistor (BJT) sizing, equations, datasheet, and calculations example


You are not creating an array of references, you are creating the array from the objects; they are being copied. You can see that this by moving the line (and adding an equals)

Train trains[trainCount] = {train1, train2};

to the bottom of your setup method. However, that is beside the point, as you are not fully using the power of arrays. You needn't create separate objects everywhere, simply create an array of objects right off the bat with new[] and use them. Like this:

#include <stdlib.h>

class Train {
    public:
        int numOfCars;
        void init();
        void move();
};

void Train::init() {}
void Train::move() {}

const int trainCount = 2;
Train* trains = new Train[trainCount];

void setup() {
    // initialize trains
    for (int i = 0; i < trainCount; ++i) {
        trains[i].numOfCars = 5;
        trains[i].init();
    }
    Serial.begin(9600);
}

void loop() {
    for(int n = 0; n < trainCount; n++) {
        Serial.println(trains[n].numOfCars); //always prints 0
        trains[n].move();
    }
}


int PPM_INPUT_PIN = TinyPpmReader.width_us(3);

will save the result into variable PPM_INPUT_PIN, while

val0 = analogRead(PPM_INPUT_PIN);

will save an analog reading results from PPM_INPUT_PIN channel into variable val0. This is (one of) your problem.
To map the PPM value, you can do:

#include <TinyServo.h>
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>

int val0,                     // integer to store value
    mappedval0;               // integer to store mapped value;

const byte SERVOS = 1;                   // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
const byte servoPin[SERVOS] = { 0 }; // what pins are your servos on?
                                       // you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

#define PANSERVO 0
#define PPM_INPUT_PIN  2    <--------- //define pin for ppm input

const int PPM_max_value = xxxxx; //put the max value of PPM reading result
const int PPM_min_value = yyyyy; //put the min value of PPM reading result

void setup()
{
  setupServos();
}

void loop()
{
  val0 = TinyPpmReader.width_us(4);   //get PPM reading result from index 4
  mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
    // scale it to use it with the servo (value between 0 and 180)

  moveServo(PANSERVO, mappedval0);
  delay(5);                           // waits for the servo to get there
}


How to start a block of code after a certain time?

The following bare-minimum code will switch pin 13 to high after 20 seconds:

void setup() {
  // assuming pin 13 has a LED connected (as on most Arduino boards)
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW); // would also work without this line
}

void loop() {
  unsigned long time = millis();
  if (time >= 20000) {
    digitalWrite(13, HIGH);   // set the LED on
  }
}

Try if this works for you, i.e. if a LED connected to that pin will light up 20 seconds after reboot.

If not you will need to find the problem: Is your ATmega running at the correct speed? Is your code executed at all? Are the peripherals working?


If you use this library, then use

sevseg.begin(P_TRANSISTORS, numDigits, digitPins, segmentPins);


The freeRam() method you are suggesting calculates the "space" between the heap and the stack, thus it returns the free SRAM.

There is no way to calculate free remaining EEPROM (if that is what you are asking), since it just contains some arbitrary data at arbitrary locations. Get the EEPROM capacity from the device data sheet and make sure to write within its boundaries.


SoftWire Library Programming Questions for I2C with Digital Pins

You can change the tof10120 to any i2c address between 1 and 254. you need to write the serial string 's7-xxx#' where xxx is the decimal address required (in string form). I wrote a simple python program for the raspberry pi to change my sensor addresses via the Rx Tx.


Use a Unicode surrogate pair character in Arduino IDE

There is a nifty new feature in C++11 called string literal, this example shows how to use it with any single line or multi line or utf8 text. You just define starting and ending sequence, in following case --- (starting sequence becomes R"---( and ending sequence )---") and make sure that this sequence does not appear in encapsulated text. This is great for integrating websites into arduino projects:

static const char _index_html[] PROGMEM = R"---(
<html>
<head>
<link rel="icon" type="image/png" href="/favicon.png"/>
</head>
<body>
...
</body>
</html>
)---";


trying to connect to WiFi on ESP32 using credentials from SD card

I use the NVS partition to store NON VOLATILE information.
I use this library: NVS library
You can save like string and restore after reset/off.
Example:
#include <Arduino.h>
#include "ArduinoNvs.h"

void setup() {
    NVS.begin();
    Serial.begin(115200);
    // write to flash
    String set_SSID = "WIFI_name";
    NVS.setString("nvs_wifi_name", set_SSID ); //upload 1 time. after comment this line and upload again **
    // read from flash
    String get_SSID = NVS.getString("nvs_wifi_name");
    Serial.printf("Wifi name stored %s\n", get_SSID);
}

void loop() {}


Why is my Adafruit motor shield not spinning my motors?

A couple of things I see...

1.) Your motor leads may be shorting out of the housing of the motor. make sure they are not.

2.) You may have the motor on the wrong port for the given code:

On line 7 of the code it reads: AF_DCMotor motor(4);

So try switching physically your motor to port 4.

3.) Also, this board has an I2C address and I dont see that addressed anywhere in the code. You can check to see what the I2C address is with this code. It will also show you that the motor control board is indeed responding.

// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknow error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}


How can I make a rotary encoder change between neopixel programs?

I was wondering if there is a way to change the program immediately
  after turning the rotary encoder, instead of having to wait for the
  program to complete.

There is, but it's not completely trivial. The reason it is not trivial
is each animation is implemented as a function that takes a while to
execute. For doing what you ask, each of these animations should be
modified, with a way to exit early if needed.

One approach would be to manage the rotary encoder using an interrupt. I
let you investigate how to do that: you probably can find examples on
the Web. Once the encoder reading is interrupt-based, you would need to
do the following changes in your program:

At global scope, add

volatile bool stop_now = false;

This will be a sort of “flag” intended to inform the currently running
animation that it should return ASAP.

Then, inside the interrupt handler, add

stop_now = true;

In loop(), just after if (change != 0) {, add

stop_now = false;

In each animation, replace delay(wait) with:

uint32_t start_time = millis();
while (millis() - start_time < wait) {
    if (stop_now)
        return;
}


What you want can be achieved with your MCUs timers and their associated interrupts. Timers are basically counters that run inside your hardware and they run decoupled from your code. Since one usually knows how fast these timers tick (e.g. how long it takes to count from one to two and so on) you can specify events that happen when a certain amount of timer ticks passed.

I suggest you have a look at SimpleTimer and Timer1 (the second page is only for ATmega168/328)

Both pages include some code samples where they specify some method that will be called every x milliseconds.


Controlling Dynamixel MX24T, MX64T servo wirelessly using Arduino Mega?

I know, Although it is not ZigBee, ROBOTIS Arduino Shield(https://emanual.robotis.com/docs/en/parts/interface/dynamixel_shield/) can use BLE module (BT-410). My recommendation is Arduino compatible OpenCM 9.04(https://emanual.robotis.com/docs/en/parts/controller/opencm904/).
Arobotix-M(https://www.trossenrobotics.com/p/arbotix-robot-controller.aspx), you can use ZigBee.


Need help with a program for a button to change the display on an OLED display

You have pinMode(buttonPin, INPUT_PULLUP); so I assume, you connected the button between pin and ground. With pull-up the pin will read HIGH if it is not grounded. If the button is pushed, grounding the button pulls it LOW. So you should test if the button is pressed with comparing to LOW.

We have this misleading idea in our heads that active is HIGH and not active is LOW. But you can see it this way:

button pushed down (low) is LOW
button not pushed is up (high) reading HIGH


I have used 40 pin cables for this purpose, specifically, IDE cables (beware: on high speed, "80 conductor" cables, but still with 40 pin connectors, some pins are permanently connected, to indicate to to the controller that this is a high speed cable!). The connectors are cheap, the cables are free if you ask around (probably less so now). In my case, I connected two extra-large 7-segment displays, and it worked great. More pins than you rarely hurts. In my case, it was especially useful since I needed some pins at the top, and some pins at the bottom of the display; my ide cable had three connectors (motherboard & two drives); I used the top row on one ide connector to the top of of my displays, and the bottom row of pins on the other connector to the bottom of the displays.


Templated class: How to create instance and work with it?

I think I found the solution:

According to: https://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor

--> Put all implementation in .h file. That's it. No more compler complains, code runs fine.

I think I have to dig deeper into c/c++ development ...


Write char array containing new line to SD card

File.print() stops printing at a NULL character (ASCII 0) not a new line.  You can stick as many new lines as you like in a string and it will print.  Try this example

void loop ()
{
  Serial.print ("Hello\nMultiline\nPrint\n");
  Serial.print ("Hello\0Multiline\0Print\n");
}

File.write() writes binary data to a file, it will write BUFLEN bytes, even if you don't give it that many bytes.

Looking at the output from you hex editor your string ends with ... 2020 2035 310a which would be 3 spaces (20), 51 (35 and 31) and a new line (0A).  There is also a null (00) after that, but I can't tell how many because you have 0s to pad the output (or fill the file).

If you look further back in the output (3rd col, 3rd row) you can see another newline (0a33) so that proves its not new lines that is stopping your output.

Without your code we can't say whats wrong, but I agree with Mark that its not what you think it is.

To write data to a CSV file I would write each row of data into a struct and then hold those structs within a list.  Then have a function that iterated through the list and printed each record to the file.  That way you wouldn't need a buffer.  If it didn't have to be a CSV then you could just call

myFile.write (currentRecord. sizeof(StructRecord));


While installing the Arduino software,
there are several window pop ups which occur to install the  drivers needed for the operating system to communicate with the device.
Click install to all of them.


Extremely cheap "Arduino" for single tasks?

Digispark comes to mind, or any of the ATTiny breakout boards at Tindie. Or, make your own PCBs, I just now finished soldering a few ATMega328p circuits to boards I designed. Microcontroller is $1.50, PCBs range from $2 to $8 each, time is "free."

Also consider "compatible with" designs; while you're not directly supporting the ecosystem, if you've already paid full price once and your conscience is clear, eBay has plenty.


The ESP provides a reset reason API, which lets you differentiate between a crash and a normal reset:

extern "C" {
  #include "user_interface.h"
}

const char * const RST_REASONS[] =
{
  "REASON_DEFAULT_RST",
  "REASON_WDT_RST",
  "REASON_EXCEPTION_RST",
  "REASON_SOFT_WDT_RST",
  "REASON_SOFT_RESTART",
  "REASON_DEEP_SLEEP_AWAKE",
  "REASON_EXT_SYS_RST"
};

// .. in setup():

const rst_info * resetInfo = system_get_rst_info(); //populate reset info
String diag = String(RST_REASONS[resetInfo->reason]); // turn enum index to string

if(diag == "REASON_SOFT_WDT_RST") digitalWrite(TX, HIGH);// check string, take action


MKR GSM 1400 Works only when connected to computer

If your sketch on an Arduino with native USB doesn't run if not connected to USB, always first check if you didn't forget the while (!Serial) {} in setup().


I'd suggest building a Faraday cage around the inductive coil. It's probably inducing enough current in all the wires around it to trigger logic level voltages in your signal wires, in the board, etc.

It sounds like the goal is for the coil to fling a magnet away, so you might have to settle for a "Faraday bowl" (an open-topped Faraday cage). Some magnetic field would leak out the top of the bowl, but if you place the control board below the bottom and several feet away it might be enough.

You might need to shield everything separately: Faraday cage around the Arduino. "Faraday Bowl" around the coil. Coax cables for everything, where the power to the coil is in a coax cable that's grounded separately, etc.


How to correctly read a string from Arduino serial port?

This is a common (and my favorite) approach:

Choose an “end of message” character. CR or LF can be good choices,
especially if you want to test your program with a terminal emulator.
On the Arduino, buffer all the received bytes until you see the end of
message.
When you see the end of message, handle the buffer to a function that
will parse and process it.

I would avoid parseInt() for anything but the simplest tests, because
it is both blocking and sensitive to the timing of the input.

For an example, you can take a look at this
Simple Arduino command line
interpreter
(look at loop()). It's non blocking, so you can add background
processing to perform while waiting for input characters.


How do people generally get data onto the Arduino, I found a lot of conflicting information online.

There are various ways depending on what the data is and how you access it.

  Does this thing have Wifi or Bluetooth??

Not unless you add WiFi or Bluetooth to it, no.

  I have a raspberry pi spare, can I just use that, sending data from pins?

Yes, there are ways.

How you go about getting data on to an Arduino depends very much on how the data is accessed.  It is possible to add a WiFi interface to an Arduino, either through an official WiFi shield or through adding something like an ESP8266 on a breakout board (ESP-01 is popular) although interacting with the ESP8266 can be tricky.

You can do the same with Bluetooth or any number of other wireless protocols.

The simplest method of getting data to the Arduino, though, is through the USB serial port. Since you have a Raspberry Pi available the most logical option would be to plug the Arduino directly into the Pi's USB port. The Pi can then communicate through /dev/ttyACM0 (or /dev/ttyUSB0 for some clones) and the Arduino receive the data through the Serial object. Exactly how you arrange all that is entirely up to you.


How do I attach 4 input pots to arduino?

It doesn't really matter as long as the the voltage across your pots doesn't exceed the ARef or IORef voltage, which is usually equal to Vcc (3.3V or 5V) for the Arduino boards. It's best to use the 5V from your board. The ADC inputs are relatively high impedance so very little current flows through. Don't use very large value pots or you might not get the correct values from your analog inputs.


To enable debugging, you need to

uncomment ENABLE_CC3K_PRINTER in Adafruit_CC3000.h
If you want to pass in some debug stream other than the default Serial, you should pass a pointer to the object (which should inherit from Print, such as SD or Client) as the last argument to the constructor in your sketch:

Adafruit_CC3000(uint8_t csPin, uint8_t irqPin, uint8_t vbatPin, uint8_t spispeed = SPI_CLOCK_DIVIDER, Print* cc3kPrinter = CC3K_DEFAULT_PRINTER);

In utility/debug.h, change the value of DEBUG_MODE to 1 (or any non-zero value)

I don't know what caused your issue but you shouldn't put this in your code:

#define _CC3000_DEBUG  1

Because most of utility/debug.h is wrapped in the usual:

#ifndef _CC3000_DEBUG
.
.
.
#endif

Your #define, depending on where it's placed, could cause most of the file to be skipped by the compiler and result in compilation errors. To be on the safe side, get rid of it and simply include utility/debug.h as needed.


Is it possible to detach an interrupt for a certain ammount of time

The standard way to do this is just as you described (but with the non-blocking coding style like in the BlinkWithoutDelay example): Detach in the ISR and setting a flag and a timestamp. Then in the main code check the flag and the time since the timestamp was took. In code that looks somewhat like this (Note, that I left out some arguments of the attaching/detachting functions):
volatile byte flag = 0;
volatile unsigned long timestamp = 0;
#define REACTIVATE_INTERVAL  1000

void ISR_function(){
    detachInterrupt(...);
    flag = 1;
    timestamp = millis();
}

void setup(){
    attachInterrupt(..., ISR_function, ...);
}

void loop(){
    if(flag && millis() - timestamp > REACTIVATE_INTERVAL){
        flag = 0;
        attachInterrupt(..., ISR_function, ...);
    }
    // Rest of your main code from here on
}

For this to work correct, you must of course use a non-blocking coding style in your main code, meaning no delay()s (except for really small ones) and no blocking while loops. If you have those in your main code, you should rewrite it to be non-blocking. Not only for this feature, but for any further extension of your project. A non-blocking coding style is an important principle to embrace, especially microcontrollers.

Without a non-blocking coding style, you would need to use a timer interrupt, to reattach the pin interrupt. While that is totally possible, it does not make much sense to configure extra peripherals of the Arduino just for this.


How to write a sketch when adding more devices to an I2C data line?

Yes you can connect multiple devices on one I2C bus. Every device on the bus needs to have its own address. Some libraries have the default address included. Some do allow to change it. Others don't. For example the SE95 temperature sensor (page 10) does allow for setting a few bits of the address allowing more than one sensor on a bus.

You can use the Wire library from Arduino to request data from I2C. When you want to pull data from a sensor, you have to send a command depending on the specs than request data from the address.

Example: for the SE95 address 0x4F (you can repeat this for any address you have a sensor on your bus) the SE95 ranges from 0x49 to 0x4F depending on the pin settings:

//Please note that the example is not complete because Wire has to be loaded and initialized
byte address = 0x4F;
byte read1;
byte read2;
Wire.beginTransmission(address);
Wire.write(0x00);
Wire.requestFrom(int(address), 2);
if(Wire.available()) {
  read1 = Wire.read();
  read2 = Wire.read();
}

So depending on the libraries, this would be quite easy.


LEDs are not powered by a particular voltage level, but by the voltage difference between anode and cathode. That's why you need to drive cathode pins (7, 4, and 2) LOW to switch the LEDs ON and HIGH to switch them off. A truth table could help:

╔═══════╦═════════╦══════════════════════════╦═══════════╗
║ anode ║ cathode ║ voltage anode to cathode ║ led state ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ LOW     ║ 0V                       ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ HIGH    ║ - 3.3V                   ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ LOW     ║ + 3.3V                   ║ ON        ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ HIGH    ║ 0V                       ║ OFF       ║
╚═══════╩═════════╩══════════════════════════╩═══════════╝

Your schematic looks safe to me, but be aware that if you decide to illuminate L1, L2 and L3 to the same color simultaneously (e.g drive red line HIGH and pins 7, 4, and 2 LOW), your LEDs will not have uniform brightness. Only one of the cathode pins should be LOW at a time, otherwise you will end up in the situation described here.


There seem to be 3 pins involved here: a potentiometer pin (0), an analog pin (val) and a servo pin (2). What is the purpose of each of these pins, and is this 3-pin wiring common across all/most servos?

No, there is only 2 pins.  The value of the potentiometer attached to pin 0 is read and stored in the variable val.  That is then used to set the angle of the servo motor on pin 2.

  Is there anything "wrong" with defining myservo.attach(2); up above the setup function, and leave the setup function an empty no-op function?

Yes.  It'll never get called.  setup() is the first function to be called and its purpose is to perform any initialization routines, such as attaching the servo code to the pin the servo is connected to.  So you have to call that either from setup() or from a function which setup() itself calls.

  Where does the map(...) function come from? If it was defined inside SoftwareServo I would have expected its usage to be something like SoftwareServo::map(...), etc.

map() is part of the standard Arduino API.  http://www.arduino.cc/en/Reference/Map

  Why do we need the delay after calling myservo.write(val);? What would happen if this delay wasn't in there?

You don't need the delay() call, but you don't want to set the value of the servo too rapidly.  You really want to allow at least one PWM cycle between each call to ensure the values have been set properly.

  According to that link, calling SoftwareServo::refresh() once every 50ms is necessary in order to: "keep your servos updating." But what does this mean, really? Updating to what?!?

SoftwareServo is just what it says - a piece of software.  You have to run that software for it to work, and the refresh() function is that bit that you run.  If you don't call that then the PWM signal for the servo will never get generated and nothing will happen.

Oh, and yes those little servos should be fine.


Navigating menus using buttons on Arduino

I'm not sure about built-in buttons, however on my projects I always add a debounce feature to any buttons.  Adjust this to your uses. If there's any issues let me know and I'll test it properly as I'm not at my programming workstation to fully test at the moment.

For example:

// Updated to include if statements and copy/pasted version of successfully
// compiled version.

// Had to use LiquidCrystal library as I don't have the AdaFruit Display libraries.
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//

int menu = 0, subMenu = 99, debounce = 200;
unsigned long pMillis = 0, cMillis;

void setup(){
  lcd.begin(16,2);
};

void loop(){
  cMillis = millis(); // sets cMillis to current millis()
  //uint8_t buttons = lcd.readButtons();
  lcd.setCursor(0,0);
  if(cMillis >= (pMillis + debounce)){
    if (menu == 0) {
      lcd.print("Select menu option");
      /*if (buttons & BUTTON_SELECT) {
       *  lcd.clear();
       *  menu = 99;
       *  subMenu = 1;
       *  };
       */
    };
    if (subMenu == 1) {
      lcd.print("in sub menu 1");
      /*if (buttons & BUTTON_SELECT) {
       *  lcd.clear();
       *  lcd.setCursor(0,1);
       *  lcd.print("shouldnt happen");
       *  };
       */
    };
  pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  };
  // I always put something similar to this at the end
  // to make sure that when millis() cycles back to 0
  // pMillis is reset to less than cMillis.
  if(cMillis < pMillis){
    pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  };
};

Edit/Update:  This compiles fine using the standard LiquidCrystal library, I am unable to test the AdaFruit display as I don't have one.  If this still doesn't work, I'll upload it to the Arduino when I get back and see what's up.

New test:

// Your libraries here

int menu = 0,
    subMenu = 99,
    debounce = 200;

unsigned long pMillis = 0,
          cMillis;

void setup(){
  lcd.begin(16,2);
}

void loop(){
  cMillis = millis(); // sets cMillis to current millis()
  //uint8_t buttons = lcd.readButtons();

  if(buttons & BUTTON_SELECT){ // I used "if(digitalRead(buttonPin) == HIGH){ ... }"
    if(cMillis >= (pMillis + debounce)){
      //I'd normally put counter/menu logic in here for the different buttons, for example:
      //"subMenu += 1;
      // if(subMenu >= totalSubMenus) { subMenu = 0; };"
      subMenu = 1;
      pMillis = cMillis;
    }
  }

  if(menu == 0){
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Select Menu Option");
    menu = 99;
  }
  if(subMenu == 1){
    lcd.clear();
    lcd.setCursor(0,1);
    lcd.print("In Sub Menu 1");
  }

  if(cMillis < pMillis){
    pMillis = cMillis; // sets pMillis to cMillis for the next iteration of the loop()
  }
}


The VIN (and the USB) goes into a 3.3V switching regulator. This has a minimum input voltage of 4.5V.

You isolate the output of that regulator from the rest of the circuit by cutting that one link (which is easy to re-solder). You are then free to feed 3.3V from your own power source directly into the board.

Yes, if you provide more than 3.3V you are liable to damage the board (note that a Li-Poly can be around 4.2V when fully charged).

You need to take your battery power and feed it through a nice efficient switching voltage regulator that has a low enough "dropout" voltage to allow good use from the battery. Note that many devices "rated" at 3.3V will also work much lower. For example:

Nina-B3 series module will run at down to 1.7V.
The APDS-9960 will operate down to 2.4V.
The HTS221 will run at down to 1.7V.
MP34DT06J can go as low as 1.6V.
LSM9DS1 can run from 1.9V.
LPS22 is 1.7V minimum

So it could be good to reduce your power to 2.5V instead of 3.3V to give more life from the battery. You should check each of the components in the both the device schematic and the rest of your circuit (by reading the datasheets) to find the highest "minimum" voltage they will work on.


Need to set a FAILSAFE in an if else loop

This is one of those cases when thinking in terms of a finite state
machine makes the programming quite straightforward. Here I would
use three states:

In the OFF state, the switch is LOW and the solenoid is off
in the ON state, the switch is HIGH and the solenoid is on
in the DELAYING state, the switch is LOW, but the program is
keeping the switch HIGH for three seconds.

The possible transitions are:

OFF → ON when the switch goes HIGH
ON → DELAYING when the switch goes LOW
DELAYING → OFF after three second in this state
DELAYING → ON when the switch goes HIGH.

The last transition is meant to ensure that LOW states of the switch
that last less than three seconds do not turn the solenoid off.

And here is a tentative implementation. Keep your constants and your
setup(), and replace your loop() with this:

const uint32_t DELAY_TIME = 3000;  // time to deay the -> off transition

void loop() {
    static enum {OFF, ON, DELAYING} state;
    static uint32_t start_delay;
    int floatswitch = digitalRead(FLOAT_PIN);

    switch (state) {
        case OFF:
            if (floatswitch == HIGH) {
                Serial.println("Switch closed");
                digitalWrite(SOLENOID_PIN, HIGH); // Turn the SOLENOID on
                state = ON;
            }
            break;
        case ON:
            if (floatswitch == LOW) {
                start_delay = millis();
                state = DELAYING;
            }
            break;
        case DELAYING:
            if (floatswitch == HIGH) {
                state = ON;
            }
            else if (millis() - start_delay >= DELAY_TIME) {
                digitalWrite(SOLENOID_PIN, LOW); // Turn the SOLENOID off
                state = OFF;
            }
            break;
    }
}


Why did my program stop working when I eject the serial cable like it did an auto reset?

Try increasing the voltage of the power supply. Maybe there might be a problem with the current. The Arduino has a 5V regulator on-board, try using a 9V battery. MAKE SURE THAT YOU CONNECT TO THE DC BARREL CONNECTOR.

Good luck!


Arduino program does not start when plugged in

I would recommend you to follow the following instructions step by step to verify your Arduino Mega.

Reboot your computer
Connect the Arduino using the USB cable to PC and check the Arduino itself if there is any jumper wires connected/grounded. If there are then remove them all.
Upload a blank sketch first. Go to File -> New
Verify the Arduino has accepted the blank sketch and resetted.
Upload the Blink sketch from the File -> Examples -> 0.1Basics -> Blink
Verify if the Pin 13/onboard LED is blinking. If yes then go to uploading your sketch, if no then there is a hardware/bootloader problem with your Arduino. Watch this video on how to burn bootloader here. https://www.youtube.com/watch?v=X5achE10rCI


It is very difficult to accurately control timings with delay(),
because you have to account for the time needed to execute the rest of
the code, including interrupts. You can easily have better accuracy by
using millis() like this:

static unsigned long last_step_time;
unsigned long now = millis();
if (now - last_step_time >= step_delay) {
    do_one_step();
    last_step_time += step_delay;
}

This is almost what you have commented out in your own code, except that
millis() should be called only once per iteration, hence the now
variable.

This may still have less than perfect accuracy due to your clock source.
If your Arduino is clocked from a quartz you should be able to get
decent timing accuracy. If it is clocked from a ceramic oscillator you
are out of luck. In any case, you can always improve the accuracy by
calibrating your clock: you measure its drift and correct for it in
software. Then you have only to worry about thermal fluctuations of the
clock frequency, which should not be an issue with a quarts.

For best accuracy, you can use either an RTC or a watch crystal
connected directly to your ATmega chip. This last solution is only
possible if you go for a bare microcontroller, without the Arduino
board. See this answer
for more details about this option, as well as the way to correct
for the drift in software.


There is no way to detect position on the bus because all devices are connected in parallel. This is why a serial or "chain" wire, added to the newer devices, is required.

(To complicate matters, what is the "order of devices" - or even the meaning of "order" in a center-fed bus, or a circular, star, or other branched network? Order is just something we perceive when looking at an end-fed linear network. Electrons don't care. Think of a capacitor (unfortunately, the bus behaves like one but that's another story) with two plates, several centimeters square, and a dozen 1-wire devices connected from plate to plate. Now what is their order? Ow, my brain hurts! Let's go back to linear buses.)

The discovery order is a function of the set of binary device IDs on the bus. There are two ways I know of to come to know the physical ordering, both empirical (i.e., by observation):

Connect the set of devices one at a time, to a temporary bus such as a breadboard. With an Arduino, read the their IDs and tag them (human readable). With knowledge of the discovery alogrithm, or by running actual discovery on an Arduino with all devices connected, write down the IDs in the order they are discovered which is invariant for a given set of device IDs. Assemble your wired bus with the devices in this order.
(The reverse of 1 and quicker to build, and is what you've already shown in your question: Wire the bus. With a simple Arduino program, repeatedly sample all devices on the bus and report print their indices and temperatures (the indices will be in discovery order). One at a time, warm each device with your hand and notice which device index is affected. Write down the physical position (first, second, ...) and the index. This is the mapping table between position and index. Include it in your control algorithm.


Controlling 10+x 5m led strips with 10+ individual analog floor switches

I think that the best solution for you, unless you want a simple on/off control (if you want it just go with Majenko's solution) is to use port expanders.

Maybe this can be slightly overkill, but you can think of using a MAX7313.

This IC is I2C controlled and has 16 I/O; you can configure each as input or output, and with automatic PWM generation too. This means that the uC just has to send it the value of light you want to output and it automatically keeps the LED strips at the correct duty cycle.

This way you can connect a sensor to P0, P2, P4, ... and configure them as input, then a pull-up resistor and a MOSFET to P1, P3, P5, ... and configure them as output with PWM. From the arduino, you will just have to connect two pins (SDA, SCL) and, of course, GND, then you will have the ability to control eight sensor/led pairs to one sensor. You want to extend it? Just solder another IC and assign it another address (pins AD0..2 serve for this purpose). You can set 64 different addresses, thus being able to drive 512 sensor/led pairs.

Want more? Use RGB led strips. Connect P0 to sensor, P1 to R, P2 to G, P3 to B, and with each IC you'll be able to drive four sensor/led pairs. You'll be able to drive only 256 sensor/led pairs, but they will be rainbow colored...

This solution has only one drawback: I could not find any pre-made board with the MAX7313 on ebay. So you'll have to design your own PCB and solder it. If you are not able to do this, alternatives exist.

Adafruit has a PCA9685 16-channels port expander board (and a lot of other manufacturers made this). This has also integrated PWM and a lot of addresses possible, but the PCA has only outputs (so no inputs). You will be able to arrange them in a matrix (so with the 18 pins remainig you will be able to control 81 switches).

Another alternative is the MCP23017; this has inputs and outputs, but no automatic PWM; this means that if you want turn them on and iff ok, but if you want a variable light you will have to "manually" pull the pin high or low (very heavy on the I2C network).

Other solutions using SPI may have better performances (SPI is faster than I2C), and a lot of other ICs with SPI, I2C or other serial connections exist. You just have to find out the most suitable for you


The SDA line of of ADS1115 will use 3.3 V if you power it with 3.3 V, but then the maximum analog input voltage would be 3.6 V (VDD + 0.3 V).

The ACS712 has the middle value at 2,5 V so to read it you need the 5 V range and must power the ADS1115 from 5 V. Then the SDA line of esp8266 will be connected to 5 V logic level, but the esp8266 pins can handle 5 V TTL communication currents.

The SCL line is driven from master (esp8266) at 3.3 V and the ADS1115 is good with it.


Bluetooth HC-05 module returns encoded data

I also got the same problem, and after a few researches, I found that it was related with a bug inside the library SoftwareSerial. Here is how to fix it :

Download the two files of the new version of the library on github
Rename them into mySoftwareSerial.cpp and mySoftwareSerial.h and put them in the working folder
Replace in the working file and in the file mySoftwareSerial.h the line #include <SoftwareSerial.h> into

#include "mySoftwareSerial.h"
Compile and send it to the arduino. It should work ! (Tested in AT mode at a baud rate of 38400, and in classical mode (+AT mode) with a baud rate of 57600 on a arduino nano)

You can find the file I used at the and of the post.

By the way, I also mention another problem I got which is not related but could help : in some models of HC-05 you have a pin EN instead of KEY. Here, instead of connecting the VCC to the KEY pin, you need to press the button on the top of the HC-05 board before starting the HC-05 module : this button will connect VCC to the pin 34 for you. But note that if you don't keep this button down, you will be able to do only a subset of the commands (for example, AT+NAME? won't work, while AT+NAME=... and AT will). You can find lot's of additional information here.

The files I used

This file is the "project file" used to forward the classical serial connection (Ctrl+Shift+M on arduino software) to the bluetooth device. Type AT commands here.

#include "mySoftwareSerial.h"
SoftwareSerial BTserial(7, 8); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
//

char c = ' ';

void setup()
{
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    Serial.println("Remember to select Both NL & CR in the serial monitor");

    // HC-05 default serial speed for AT mode is 38400
    BTserial.begin(38400);
}

void loop()
{

    // Keep reading from HC-05 and send to Arduino Serial Monitor
    if (BTserial.available())
    {
        c = BTserial.read();
        Serial.write(c);
    }

    // Keep reading from Arduino Serial Monitor and send to HC-05
    if (Serial.available())
    {
        c =  Serial.read();
        BTserial.write(c);
    }

}

The file mySoftwareSerial.h, taken from the github page :

/*
SoftwareSerial.h (formerly NewSoftSerial.h) -
Multi-instance software serial library for Arduino/Wiring
-- Interrupt-driven receive and other improvements by ladyada
   (http://ladyada.net)
-- Tuning, circular buffer, derivation from class Print/Stream,
   multi-instance support, porting to 8MHz processors,
   various optimizations, PROGMEM delay tables, inverse logic and
   direct port writing by Mikal Hart (http://www.arduiniana.org)
-- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
-- 20MHz processor support by Garrett Mace (http://www.macetech.com)
-- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
The latest version of this library can always be found at
http://arduiniana.org.
*/

#ifndef SoftwareSerial_h
#define SoftwareSerial_h

#include <inttypes.h>
#include <Stream.h>

/******************************************************************************
* Definitions
******************************************************************************/

#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#endif

#ifndef GCC_VERSION
#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif

class SoftwareSerial : public Stream
{
private:
  // per object data
  uint8_t _receivePin;
  uint8_t _receiveBitMask;
  volatile uint8_t *_receivePortRegister;
  uint8_t _transmitBitMask;
  volatile uint8_t *_transmitPortRegister;
  volatile uint8_t *_pcint_maskreg;
  uint8_t _pcint_maskvalue;

  // Expressed as 4-cycle delays (must never be 0!)
  uint16_t _rx_delay_centering;
  uint16_t _rx_delay_intrabit;
  uint16_t _rx_delay_stopbit;
  uint16_t _tx_delay;

  uint16_t _buffer_overflow:1;
  uint16_t _inverse_logic:1;

  // static data
  static uint8_t _receive_buffer[_SS_MAX_RX_BUFF];
  static volatile uint8_t _receive_buffer_tail;
  static volatile uint8_t _receive_buffer_head;
  static SoftwareSerial *active_object;

  // private methods
  inline void recv() __attribute__((__always_inline__));
  uint8_t rx_pin_read();
  void setTX(uint8_t transmitPin);
  void setRX(uint8_t receivePin);
  inline void setRxIntMsk(bool enable) __attribute__((__always_inline__));

  // Return num - sub, or 1 if the result would be < 1
  static uint16_t subtract_cap(uint16_t num, uint16_t sub);

  // private static method for timing
  static inline void tunedDelay(uint16_t delay);

public:
  // public methods
  SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);
  ~SoftwareSerial();
  void begin(long speed);
  bool listen();
  void end();
  bool isListening() { return this == active_object; }
  bool stopListening();
  bool overflow() { bool ret = _buffer_overflow; if (ret) _buffer_overflow = false; return ret; }
  int peek();

  virtual size_t write(uint8_t byte);
  virtual int read();
  virtual int available();
  virtual void flush();
  operator bool() { return true; }

  using Print::write;

  // public only for easy access by interrupt handlers
  static inline void handle_interrupt() __attribute__((__always_inline__));
};

// Arduino 0012 workaround
#undef int
#undef char
#undef long
#undef byte
#undef float
#undef abs
#undef round

#endif

The file mySoftwareSerial.cpp, also taken from the github page:

/*
SoftwareSerial.cpp (formerly NewSoftSerial.cpp) -
Multi-instance software serial library for Arduino/Wiring
-- Interrupt-driven receive and other improvements by ladyada
   (http://ladyada.net)
-- Tuning, circular buffer, derivation from class Print/Stream,
   multi-instance support, porting to 8MHz processors,
   various optimizations, PROGMEM delay tables, inverse logic and
   direct port writing by Mikal Hart (http://www.arduiniana.org)
-- Pin change interrupt macros by Paul Stoffregen (http://www.pjrc.com)
-- 20MHz processor support by Garrett Mace (http://www.macetech.com)
-- ATmega1280/2560 support by Brett Hagman (http://www.roguerobotics.com/)
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
The latest version of this library can always be found at
http://arduiniana.org.
*/

// When set, _DEBUG co-opts pins 11 and 13 for debugging with an
// oscilloscope or logic analyzer.  Beware: it also slightly modifies
// the bit times, so don't rely on it too much at high baud rates
#define _DEBUG 0
#define _DEBUG_PIN1 11
#define _DEBUG_PIN2 13
//
// Includes
//
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <Arduino.h>
#include "mySoftwareSerial.h"
#include <util/delay_basic.h>

//
// Statics
//
SoftwareSerial *SoftwareSerial::active_object = 0;
uint8_t SoftwareSerial::_receive_buffer[_SS_MAX_RX_BUFF];
volatile uint8_t SoftwareSerial::_receive_buffer_tail = 0;
volatile uint8_t SoftwareSerial::_receive_buffer_head = 0;

//
// Debugging
//
// This function generates a brief pulse
// for debugging or measuring on an oscilloscope.
#if _DEBUG
inline void DebugPulse(uint8_t pin, uint8_t count)
{
  volatile uint8_t *pport = portOutputRegister(digitalPinToPort(pin));

  uint8_t val = *pport;
  while (count--)
  {
    *pport = val | digitalPinToBitMask(pin);
    *pport = val;
  }
}
#else
inline void DebugPulse(uint8_t, uint8_t) {}
#endif

//
// Private methods
//

/* static */
inline void SoftwareSerial::tunedDelay(uint16_t delay) {
  _delay_loop_2(delay);
}

// This function sets the current object as the "listening"
// one and returns true if it replaces another
bool SoftwareSerial::listen()
{
  if (!_rx_delay_stopbit)
    return false;

  if (active_object != this)
  {
    if (active_object)
      active_object->stopListening();

    _buffer_overflow = false;
    _receive_buffer_head = _receive_buffer_tail = 0;
    active_object = this;

    setRxIntMsk(true);
    return true;
  }

  return false;
}

// Stop listening. Returns true if we were actually listening.
bool SoftwareSerial::stopListening()
{
  if (active_object == this)
  {
    setRxIntMsk(false);
    active_object = NULL;
    return true;
  }
  return false;
}

//
// The receive routine called by the interrupt handler
//
void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Disable further interrupts during reception, this prevents
    // triggering another interrupt directly after we return, which can
    // cause problems at higher baudrates.
    setRxIntMsk(false);

    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=8; i > 0; --i)
    {
      tunedDelay(_rx_delay_intrabit);
      d >>= 1;
      DebugPulse(_DEBUG_PIN2, 1);
      if (rx_pin_read())
        d |= 0x80;
    }

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    uint8_t next = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    if (next != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = next;
    }
    else
    {
      DebugPulse(_DEBUG_PIN1, 1);
      _buffer_overflow = true;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN1, 1);

    // Re-enable interrupts when we're sure to be inside the stop bit
    setRxIntMsk(true);

  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

uint8_t SoftwareSerial::rx_pin_read()
{
  return *_receivePortRegister & _receiveBitMask;
}

//
// Interrupt handling
//

/* static */
inline void SoftwareSerial::handle_interrupt()
{
  if (active_object)
  {
    active_object->recv();
  }
}

#if defined(PCINT0_vect)
ISR(PCINT0_vect)
{
  SoftwareSerial::handle_interrupt();
}
#endif

#if defined(PCINT1_vect)
ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect));
#endif

#if defined(PCINT2_vect)
ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect));
#endif

#if defined(PCINT3_vect)
ISR(PCINT3_vect, ISR_ALIASOF(PCINT0_vect));
#endif

//
// Constructor
//
SoftwareSerial::SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic /* = false */) :
  _rx_delay_centering(0),
  _rx_delay_intrabit(0),
  _rx_delay_stopbit(0),
  _tx_delay(0),
  _buffer_overflow(false),
  _inverse_logic(inverse_logic)
{
  setTX(transmitPin);
  setRX(receivePin);
}

//
// Destructor
//
SoftwareSerial::~SoftwareSerial()
{
  end();
}

void SoftwareSerial::setTX(uint8_t tx)
{
  // First write, then set output. If we do this the other way around,
  // the pin would be output low for a short while before switching to
  // output high. Now, it is input with pullup for a short while, which
  // is fine. With inverse logic, either order is fine.
  digitalWrite(tx, _inverse_logic ? LOW : HIGH);
  pinMode(tx, OUTPUT);
  _transmitBitMask = digitalPinToBitMask(tx);
  uint8_t port = digitalPinToPort(tx);
  _transmitPortRegister = portOutputRegister(port);
}

void SoftwareSerial::setRX(uint8_t rx)
{
  pinMode(rx, INPUT);
  if (!_inverse_logic)
    digitalWrite(rx, HIGH);  // pullup for normal logic!
  _receivePin = rx;
  _receiveBitMask = digitalPinToBitMask(rx);
  uint8_t port = digitalPinToPort(rx);
  _receivePortRegister = portInputRegister(port);
}

uint16_t SoftwareSerial::subtract_cap(uint16_t num, uint16_t sub) {
  if (num > sub)
    return num - sub;
  else
    return 1;
}

//
// Public methods
//

void SoftwareSerial::begin(long speed)
{
  _rx_delay_centering = _rx_delay_intrabit = _rx_delay_stopbit = _tx_delay = 0;

  // Precalculate the various delays, in number of 4-cycle delays
  uint16_t bit_delay = (F_CPU / speed) / 4;

  // 12 (gcc 4.8.2) or 13 (gcc 4.3.2) cycles from start bit to first bit,
  // 15 (gcc 4.8.2) or 16 (gcc 4.3.2) cycles between bits,
  // 12 (gcc 4.8.2) or 14 (gcc 4.3.2) cycles from last bit to stop bit
  // These are all close enough to just use 15 cycles, since the inter-bit
  // timings are the most critical (deviations stack 8 times)
  _tx_delay = subtract_cap(bit_delay, 15 / 4);

  // Only setup rx when we have a valid PCINT for this pin
  if (digitalPinToPCICR(_receivePin)) {
    #if GCC_VERSION > 40800
    // Timings counted from gcc 4.8.2 output. This works up to 115200 on
    // 16Mhz and 57600 on 8Mhz.
    //
    // When the start bit occurs, there are 3 or 4 cycles before the
    // interrupt flag is set, 4 cycles before the PC is set to the right
    // interrupt vector address and the old PC is pushed on the stack,
    // and then 75 cycles of instructions (including the RJMP in the
    // ISR vector table) until the first delay. After the delay, there
    // are 17 more cycles until the pin value is read (excluding the
    // delay in the loop).
    // We want to have a total delay of 1.5 bit time. Inside the loop,
    // we already wait for 1 bit time - 23 cycles, so here we wait for
    // 0.5 bit time - (71 + 18 - 22) cycles.
    _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 75 + 17 - 23) / 4);

    // There are 23 cycles in each loop iteration (excluding the delay)
    _rx_delay_intrabit = subtract_cap(bit_delay, 23 / 4);

    // There are 37 cycles from the last bit read to the start of
    // stopbit delay and 11 cycles from the delay until the interrupt
    // mask is enabled again (which _must_ happen during the stopbit).
    // This delay aims at 3/4 of a bit time, meaning the end of the
    // delay will be at 1/4th of the stopbit. This allows some extra
    // time for ISR cleanup, which makes 115200 baud at 16Mhz work more
    // reliably
    _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (37 + 11) / 4);
    #else // Timings counted from gcc 4.3.2 output
    // Note that this code is a _lot_ slower, mostly due to bad register
    // allocation choices of gcc. This works up to 57600 on 16Mhz and
    // 38400 on 8Mhz.
    _rx_delay_centering = subtract_cap(bit_delay / 2, (4 + 4 + 97 + 29 - 11) / 4);
    _rx_delay_intrabit = subtract_cap(bit_delay, 11 / 4);
    _rx_delay_stopbit = subtract_cap(bit_delay * 3 / 4, (44 + 17) / 4);
    #endif

    // Enable the PCINT for the entire port here, but never disable it
    // (others might also need it, so we disable the interrupt by using
    // the per-pin PCMSK register).
    *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));
    // Precalculate the pcint mask register and value, so setRxIntMask
    // can be used inside the ISR without costing too much time.
    _pcint_maskreg = digitalPinToPCMSK(_receivePin);
    _pcint_maskvalue = _BV(digitalPinToPCMSKbit(_receivePin));

    tunedDelay(_tx_delay); // if we were low this establishes the end
  }

#if _DEBUG
  pinMode(_DEBUG_PIN1, OUTPUT);
  pinMode(_DEBUG_PIN2, OUTPUT);
#endif

  listen();
}

void SoftwareSerial::setRxIntMsk(bool enable)
{
    if (enable)
      *_pcint_maskreg |= _pcint_maskvalue;
    else
      *_pcint_maskreg &= ~_pcint_maskvalue;
}

void SoftwareSerial::end()
{
  stopListening();
}

// Read data from buffer
int SoftwareSerial::read()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

int SoftwareSerial::available()
{
  if (!isListening())
    return 0;

  return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF;
}

size_t SoftwareSerial::write(uint8_t b)
{
  if (_tx_delay == 0) {
    setWriteError();
    return 0;
  }

  // By declaring these as local variables, the compiler will put them
  // in registers _before_ disabling interrupts and entering the
  // critical timing sections below, which makes it a lot easier to
  // verify the cycle timings
  volatile uint8_t *reg = _transmitPortRegister;
  uint8_t reg_mask = _transmitBitMask;
  uint8_t inv_mask = ~_transmitBitMask;
  uint8_t oldSREG = SREG;
  bool inv = _inverse_logic;
  uint16_t delay = _tx_delay;

  if (inv)
    b = ~b;

  cli();  // turn off interrupts for a clean txmit

  // Write the start bit
  if (inv)
    *reg |= reg_mask;
  else
    *reg &= inv_mask;

  tunedDelay(delay);

  // Write each of the 8 bits
  for (uint8_t i = 8; i > 0; --i)
  {
    if (b & 1) // choose bit
      *reg |= reg_mask; // send 1
    else
      *reg &= inv_mask; // send 0

    tunedDelay(delay);
    b >>= 1;
  }

  // restore pin to natural state
  if (inv)
    *reg &= inv_mask;
  else
    *reg |= reg_mask;

  SREG = oldSREG; // turn interrupts back on
  tunedDelay(_tx_delay);

  return 1;
}

void SoftwareSerial::flush()
{
  // There is no tx buffering, simply return
}

int SoftwareSerial::peek()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  return _receive_buffer[_receive_buffer_head];
}


What is the difference between a 3 pin and 4 pin ultrasonic range sensor?

It's simple enough... instead of:

pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);

You would have

pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);

(of course you have to define echoPin to be whatever pin you choose to connect ECHO to).

And to save processing time you can have all your pinMode() calls in setup since there is no need to change mode on the fly any more.


Formula to calculate energy required to power an Arduino board

In the datasheet you can read how much every mode uses (normal mode, sleep mode etc). However, it also depends on which peripherals inside the CPU are active and all electronics around it. So make sure you read the datasheet of the entire development board, and not from the CPU itself.

The mathematical formula is reasonably simple: the total power is the sum of each component's Amperage * component's Voltage. But practicially this is hard to calculate.

The easiest way (but not mathematically) is probably just to measure the amperage in the development board, and the voltage and multipley them together.


How to receive and process a long string sent over serial?

I had to read until delimiter :D

String receive() {
        String content = "";
        content = Serial.readStringUntil('\r');
        return content;
    }

Now it is fine. I will also change String to large char array.


How to connect an Arduino to WIFI using an ESP8266

Sending the following commands to the ESP should get you started:

AT+RST                         # Reset
AT+CWMODE=1                    # Set to station-mode as a client
ATE0                           # turn off command echo
AT+CWLAP                       # optional: list access points
AT+CWJAP_DEF="SSID","PASSWORD" # Always connect to this SSID

(I made-up the comment syntax; don't try to send those.) The full
ESP8266 AT Instruction Set has the complete set of commands and a functional description of each one.

Update:

  ... do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to
  TX of Arduino, Ground of Arduino to RESET ?

Rx & Tx must be cross-connected with the corresponding Arduino pins and the ESP's reset pulled high (3.3v).


How to split a string received via a GSM module (message)

Simplest solution is to use sscanf().

  int password;
  char operation;
  int time;
  char* buf = "{14:C:123}";
  int n = sscanf(buf, "{%d:%c:%d}", &password, &operation, &time);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("password="));
  Serial.println(password);
  Serial.print(F("operation="));
  Serial.println(operation);
  Serial.print(F("time="));
  Serial.println(time);


PCF8563 does not remember time when restarting Arduino Uno?

[SOLVED]

The solution is simply to put a jumper between BAT and VCC positions in the module itself. Many thanks to Edgar Bonet


Arduino, Receiving Instant Time When Event Occurs

It's not very clear what you expect to see.

You are currently using millis() which returns the number of milliseconds since the program started running.  This can run for 50 days without wrapping.  It has no relevance to the real time unless you recorded the time the program started.  You could write something to add millis to the start time if you wanted (look at http://playground.arduino.cc/Code/time)

Alternatively you could use a real time clock (DS1307 or DS3221) which a usually just a few pence/cents.  These ICs keep the current real time and return it when queried.  If you are trying to log data from sensor (or cars) then this will give you the real time the data was received by the Arduino, and it will make a lot more sense.

Your current code will display

45678

An RTC could let you display

Wednesday 22nd February 2017 13:05:42.32


How to produce a .o file from code using Arduino IDE (primarily for LGPL3 compliance)

To extract the .o produced during compilation in the Arduino IDE, do the following:

Go to the Arduino->Preferences menu item. This will open a preferences window.
In the preferences window find the line that says "Show verbose output during" and make sure that compilation is checked. (you can leave upload on or off as you prefer).
Click "OK" to close the preferences window.
Compile (or compile and upload) your Sketch.

You will get lots of extra output. In the white text, you will either see messages about files being compiled or about "using previously compiled file". In either case, there will be a path provided which will indicate where your Sketch was compiled. On my Mac environment this is /var/folders/<long random string>/T/arduino_build_<number>/sketch/<sketch_name>.ino.cpp.o

The line where your sketch is compiled is very long, but the path is also visible in most of the library lines and you can just work down into .../sketch/... instead of .../library/... instead of scrolling so far to the right on the exactly correct line.

To find the exact line where your sketch is compiled, look for the line directly below a line which simply says "Compiling sketch..."

I know this is rather basic (now that I know how to do it), but it took quite a bit of digging to find it and I figured others might want an answer that's searchable.


See topic #16812, “Load sketch code from SD Card”, in forum.arduino.cc, which explains how to replace the ordinary Arduino bootloader with one that can load programs from an SD card.

Also see Bootdrive loads Arduino sketches from SD card at dangerousprototypes.com, which gives different code to do the same thing.  It also mentions BootDrive for Arduino from baldwisdom.com.

Note, the program code that these loaders install into flash is already compiled, as opposed to being original C source code.  If you want to load source-level code into the Arduino, look for an interpreter / interpretive language to run on the Arduino.


How Can I convert my arduino code to C/C++ embedded code

Arduinos use a standard C++ compiler. The supposed "Arduino Language" doesn't exist; it is C++. Except that the Arduino IDE will permit you some shortcuts that the compiler doesn't. The two biggies are:

The IDE will notice that your are trying to use libraries (ones it recognizes, anyway) and insert the necessary #include <SOMELIBRARY.H>, if you didn't do it.
The IDE will notice when you make forward reference to a function not yet defined nor declared, and provide the necessary forward declaration.

But if you manage these for yourself, as you would have to in any other C++ environment, your code structure will be portable.

The remaining source of incompatibility is hardware dependence. Writing embedded systems software is almost always hardware dependent. It has to be dependent on the external hardware, and quite likely is dependent on specifics of the MCU. The latter dependencies can usually be written around. Function calls or direct references to the processor's I/O registers, for example, which, on another processor, will map differently, maybe even to memory addresses instead of to registers at all.

Another processor will very likely have an entirely different set of pins with different characteristics and capabilities from the original one. Libraries to drive external hardware will likely have been designed for a given processor or processor-family and may not map gracefully to another.

If processor independence is a design-goal of the project, then you'd probably define a hypothetical set of features that you'd expect all processors to share, and hand code for anything outside of that basic set. If you wanted to take advantage of certain features if they were available on a given processors, then, in addition to the hand-coded features you wish to have, you'd also provide conditionally compiled, optimized-for-the-processor code that you could enable when you compile for that processor, and disable for all others.


ard-reset-arduino resetting Leonardo/Micro via USB works on OSX, fails on Ubuntu

I'm somewhat embarrassed as to the source of the problem.  It wasn't an OSX vs Ubuntu issue.

Rather, on the Ubuntu system, there was an another application that was holding the USB port open, so attempts to reset the Leonardo were failing.

Rather than delete this post out of shame, I'm leaving it here in case someone else stumbles across the same problem.


You're on the right track here. In the datasheet for the ATmega1280 I find this box:

What you want to look at is DC Current Vcc and GND Pins  ....  200.0 mA

This is the total limit of all the current going through the chip (because everything must come through Vcc), and it is the absolute maximum. Don't go near it. You need to boost this with some transistors.


Is it safe to connect VCC to a data pin on Attiny chips?

As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.
It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).


Which motor (type) to use for an arduino controlled magnetic stirrer?

I'd personally recommend a continuous rotation servo or a brushed DC motor. Personally, for this kind of load, I think it would be easier and cheaper to go with the brushed DC motor. You have to remember a continuous rotation servo is a DC motor with some circuitry so you can send pulses to it to control the speed (although it's not directly proportional to the signal you send).

A servo is the only other option besides a brushless motor; both require a little more circuitry than the brushed motor/continuous servo. The additionally cost more. This blog post covers the differences between brushed and brushless motors.

For driving a continuous, you hook it up to power [depends on your servo voltage], ground, and another Arduino pin and use the servo library to send a signal as a degree (90 = no speed, 180 = full speed forward, 0 = full speed backward).

A brushed you would need a h-bridge that allows you to either send voltage, send no voltage, or send reverse voltage (for backward). This chip (~$5) does that for two motors and allows PWM for different speeds. It also includes a brake function, although that doesn't seem necessary for you. It can handle up to a "2.4 A continuous (4 A peak)." I talk about this in this answer of mine.

Quick note, if you want to control the exact RPM of the device and not just manually adjust it to a good rate, you'll need some sort of a rotary encoder or similar. A reed switch (sends current depending on magnetic fields) would work perfectly for this purpose, just mount it below the magnets and figure out the degrees rotated by the motor for each "pulse."


Using Modbus-RTU with Arduino and temperature controller

The setTransmitBuffer calls are for writeMultipleRegisters, which you removed from the example.

The first parameter of the readHoldingRegisters is the address of the register. The second parameter is the count of registers to read.

Your sketch doesn't show the retrieved data. You have no indication of success or fail.


Can I work with larger numbers than an unsigned long long in Arduino?

There are many ways to use numbers bigger than an unsigned long on Arduino. The right one depends on the application.

Floats and Doubles
floats and doubles types on Arduino can hold exact integers up  2^53. That is a very large number. They are built into the Arduino compiler.

uint64_t
The uint64_t type can hold exact integers up to 2^64. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.

BigNumber (or bc)
The BigNumber type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...

https://github.com/nickgammon/BigNumber

Again, this type is not supprted by the Arduino built-in library functions so  you will need to either down-convert or find BigNumber compatible functions for things like printing and serializing.


You need to add an LED and series resistor between a currently unused Arduino pin and ground.
In your setup() function, set that pin's i/o mode to OUTPUT.
Where the code turns the tone on, it should also make the LED pin HIGH.
Where the code turns the tone off, it should also make the LED pin LOW.


Serial not displaying sketch for MPU6050

Ground the AD0 pin. I thought the address should be set to 0x68 without this, but from what I've seen it fluctuates between 0x68 and 0x69. If you want the address to be 0x69 short the AD0 pin to 5V. I guess this would be useful if you need to use 2 MPU6050s with different I2C addresses without doing something in software. Haven't looked into that yet

Still, the I2C scanner for arduino may be useful for detecting the address/debugging: http://playground.arduino.cc/Main/I2cScanner


Does the MKR WIFI 1010 support the arduino mouse and keyboard controller?

Yes, the Arduino SAMD boards are supported by the Arduino Keyboard and Mouse library.

Nano 33 IoT is a smaler alternative to MKR 1010.

But the MKR1010 or the Nano33 IoT with original NINA firmware doesn't yet support classic Bluetooth like the HC-05 module. The ArduinoBLE library and the NINA firmware support only BLE which is different.

But there is a simple way to replace the NINA firmware with the ESP32 Arduino basic Bluetooth sketch SerialToSerialBT and then use it from the SAMD. This way the NINA module will be degraded to something like a HC-05.


How do I convert Arduino to an ATmega328P-based project?

A compiled sketch will run just fine on a bare ATmega328p, if all the necessary surrounding components are there, and if you have a way to program it.
This could be as simple as putting the chip on the Uno and programming it there. Don't do that too often; the socket isn't intended for that. You could get a 28-pin ZIF socket, though.
There are a few things to consider:

The bare chip needs external components like a crystal, etc. to function; you can check the Uno's schematic to see what you want to copy to your PCB/breadboard;
You may want to include a way to program the ATmega328p in-circuit using an ISP or a USB-to-serial chip;
The pin numbers will be different, a minor annoyance;
Possibly things I forgot.

There is a how-to on the Arduino site, and also a description of how to build a "whole" Arduino on a breadboard.


Switch two or more digital outputs of ESP8266 at the same time

See the datasheet: esp8266-technical_reference_en

Paragraph 2.2.2 shows how to use the output registers.

With the registers GPIO_OUT, GPIO_OUT_W1TS and GPIO_OUT_W1TC you can set or clear multiple GPIOs.


What you are experiencing is a common pitfall.
You are probably expecting floating point calculations, but what you are writing are only integer ones.

Try with:  y * 180. / 1023.   (notice the dots).

This will work only with constants.

To make it work with anything, use a cast:  y * 180 / (float) 1023

Happy hacking.


Connecting a FireBeetle ESP32 to Arduino

The flash button is virtual and controlled by the RTS signal from the computer through the USB port (why are you trying to connect through an Arduino?). It should automatically enter bootloader mode when you go to program it. There should be nothing you need to do.

However, if you do want to manually enter bootloader mode, just connect IO0 (note: not D0) to GND and press the reset button.


It seems this error is specific to the Rust ARM library I am using; quoting from https://github.com/klangner/sam3x/issues/9:

  It looks that at bound rate=9600 the timer sends data with the speed of ~888. And then computer can't understand the output.

Based on this, I started playing around with the baud rate I pass to the library when initializing it, and using 11000 instead of 9600 empirically seems to work (i.e. I am seeing a steady stream of 0x5A on my PC receiving at 9600).


First of all, you should decide for a datastructure for you table. There are many options with various advantages and disadvantages. I am choosing a statically allocated table here, with a fixed width for each entry in the table and a fixed number of columns. One may also use pointers to strings which are allocated on the heap or elsewhere, but I find this to be the simplest.

Anyways, the basic problem doesn't change: We want to write a integer value in some string buffer. I am using the C library function snprintf() here. This function is like printf(), just that it writes its output to a given buffer of a maximum size. Thus, we can use simple format strings here and some workarounds for non-working format strings (floating points..)

Here is the code.

#include <Arduino.h>

/* A table is a 2 dimensional array of char buffers.
   The core element is a char buffer of fixed size.
   The number of columns must be fixed at compile time.
   Rows can by dynamically added in the structure without having to
   declare the number of elements.
   You can declare the number of rows at compile time, but do not need to fill them.
   Thus you can dynamically add rows to the table.
 */

#define MAX_ENTRY_SIZE 20
#define NUM_COLUMNS 3
#define COLUMN_PRINT_WIDTH MAX_ENTRY_SIZE

char myTable[][NUM_COLUMNS][MAX_ENTRY_SIZE] = {
        {"Column 1", "Column 2" ,"Column 3"}, //Row 1
        {"Variable a", "Variable b", "Variable int"}, //Row 2
        {"Variable double", "Variable double" ,"Variable double"}, //Row 1
};

char* get_table_entry(int row, int column) {
    char* entry = myTable[row][column];
    return entry;
}

void write_int_to_table(int value, int row, int column) {
    //Get a pointer to where the entry is
    char* entry = get_table_entry(row, column);
    //write a new string inside it
    snprintf(entry, MAX_ENTRY_SIZE, "%d", value);
}

void write_double_to_table(double value, int row, int column) {
    //Same as above, different format string..
    char* entry = get_table_entry(row, column);
    //Formatting floats on an Arduino Uno is tricky. %f formatters don't work (cut out due to size.)
    //use String API instead
    String stringFloat(value);
    const char* cString = stringFloat.c_str();
    strncpy(entry, cString, MAX_ENTRY_SIZE);
}

void print_table() {
    //Get number of Rows
    int numRows = sizeof(myTable) / (MAX_ENTRY_SIZE * NUM_COLUMNS);
    for(int row = 0; row < numRows; row++) {
        //Print all columns of this row
        for(int column = 0; column < NUM_COLUMNS; column++) {
            char* entry = get_table_entry(row, column);
            Serial.print(entry);
            //fill with spaces to the right
            for(unsigned int i=0; i< COLUMN_PRINT_WIDTH - strlen(entry); i++) Serial.print(" ");
        }
        Serial.println();

        //Table header seperator
        if(row == 0)
            Serial.println("============================================");
    }
}

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

void loop() {
    int a = random(0, 100);
    double b = random(0, 100);

    Serial.print("Will write new values for a = ");
    Serial.print(a);
    Serial.print(" and b = ");
    Serial.println(b);

    //write these in the second row (first row after header), first and second column.
    write_int_to_table(a, 1, 0);
    write_double_to_table(b, 1, 1);

    //Print table again
    print_table();
    Serial.println();
    Serial.println();

    delay(5000);
}

Two rounds give the output:

Column 1            Column 2            Column 3
============================================
Variable a          Variable b          Variable int
Variable double     Variable double     Variable double

Will write new values for a = 7 and b = 49.00
Column 1            Column 2            Column 3
============================================
7                   49.00               Variable int
Variable double     Variable double     Variable double


Its not just a question of the stackability of the shields and the clash of pins you also need to consider what the shields do.

Stacking the GSM shield under the LCD is going to restrict is tx/rx power unless you have an external aerial.

The LCD will require a large amount of memory and processing power, a 3.5" inch display is really going to push an Uno to the edge, you aren't going to get much time for servicing the GSM and camera.

The camera is also going to require a large amount of RAM and processing time to handle still images.  If you are processing video then I really doubt you will be able use the other shields.

You don't say if you are experienced in Embedded development.  Its different to Linux or Windows dev where resources are almost limitless.  If you don't have experience then you might find the transition quite hard.

Your question was are they compatible, I don't have the evidence but I would say no because of the resources they consume.  Sorry I can't see this project going anywhere fast. :(


Data packet format when USB initialized as COM port

Once the USB connection is initialized as a COM port, it no longer utilizes traditional USB packets (only internally). It acts as a regular COM port. This layer of abstraction is created by 8u2 chip on Arduino side and by the driver on the PC side.

If you need to use the USB without the COM port abstraction, you have to probably configure the 8u2 chip to behave this way. I think it should be possible to configure to act as some HID device for example. You would also need to take care about the PC side and you might have to write your own driver.

For a guide on hacking and configuring the 8u2 chip on Mega, see following link:

http://arduino.cc/en/Hacking/DFUProgramming8U2


Arduino Serial Response is Slow when in While Loop

Serial.read() reads one character from the Serial stream, or returns -1 if there are no characters to read.

When you send a 1 from the Serial Monitor, the Arduino board first receives an Ascii 1, and then receives a line-end character (eg, an LF from Linux) or characters (eg, a CR and LF from MSWindows).

Since none of 1, CR, or LF are equal to an Ascii 0, the numkey value computed at the fourth line of case 1 is not 0, so the exit condition isn't met.  Thus the fade loop continues running, until it sees a 0 character.

Instead of continuing to read characters within while loops within the switch/case statement, test if more serial input is available.  Note, avoid exiting early from case 1, after you read a digit at the beginning of loop(), read and discard the line-ending characters that follow.


I think what you have done is a perfectly logical thing to do.  You had three programs that worked and so you pasted them all into the same file and compiled it.  The compiler spat its dummy out of the pram and you didn't understand what the h*ll went wrong.  Is that about right?

// You only need to include each header file once
#include <IRremote.h>

// You need to define objects to represent the leds, we could use an array but for now we'll stick to the basics (makes the code a bit longer)
IRsend irsend_led1;
IRsend irsend_led2;
IRsend irsend_led3;

// This is where you do all the setup, it only gets executed once.
// You might need to assign the pin numbers to the irsend_ledX variables here.
void setup()
{
}

// This function is called repeatedly.  You can only have one of these.
void loop() {
    // I don't understand why you have this for loop, I think you think it may have something to do with pin numbers but I don't think it does.
    // I think the data is being sent multiple times, don't know why though
    for (int i = 0; i < 11; i++) {
        irsend_led1.sendNEC(0xABCDEFGH, 32); //Settings Menu
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 10; i++) {
        irsend_led2.sendNEC(0xSJKLMNOP, 32); //HDMI Port
        delay(1000);
    }
    delay(1000); //1 second delay
    for (int i = 0; i < 9; i++) {
        irsend_led3.sendNEC(0xZXYRWVUG, 32); //Switch off monitor
        delay(1000);
    }
    delay(1000); //1 second delay
}

Give that a try, it might not work, but it will be closer to what you need, I hope I have explained it well enough.

Read the manual for the IR library and find out how to set the port numbers and if you can find out what that loop is about that might help.


Can not initialize ESP module in Arduino SoftwareSerial

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(11,12); // RX, TX
#endif

Because your Mega has a Hardware Serial1 port, HAVE_HWSERIAL1 is defined. Thus the lines inside that preprocessor conditional will not be compiled. This means you should connect the ESP8266 to the Serial1 lines on your Mega:

Mega | ESP8266
--------------
19   | TX
18   | RX


add this variable at the top of your program:

const int buttonPin = XX;   // the pin for the button
bool bState = false;

in the setup() function:

pinMode(buttonPin, INPUT_PULLUP);
// in case INPUT_PULLUP is not defined, comment the above line and uncomment below
//pinMode(buttonPin, INPUT);
//digitalWrite (buttonPin, HIGH);  // enable internal pull-up

in the loop() function, change your code with this:

update_bState();

if (bState) { digitalWrite(motorPin, HIGH); }
else        { digitalWrite(motorPin, LOW); }

then, at the end of your program, add the getButton function:

void update_bState(void)
{
    static bool buttonDone = false;
    static uint16_t timeButton;

    if (!digitalRead(buttonPin))
    {
        if ((!buttonDone) && ((uint16_t) (millis() - timeButton) > 100))
        { // Do once when button is pressed for at least 100ms (debounce)
            bState ^= true;     // Toggle button state
            buttonDone = true;
        }
    }
    else
    {
        buttonDone = false;
        timeButton = millis();
    }
}

Now that all the work is done, you should add acceleration when launching and deceleration when launching and stopping :D

By the way, I did not tested any code, so there may be some typo errors...


Having difficulty uploading sketch to an Arduino Pro Mini

You need to hook it up with the Arduino TX --> FTDI RX, and vise versa, so crossed over.  If you take the FTDI and hook it up to the Ardiono pin to pin as you have it pictured it should work, provided the FTDI works.

No to your note about not having a serial port, you should have that as soon as you plug the FTDI into your computer, the Arduino is not necessary for this.  First things first, check you drivers, and check your USB connection.  You won't get anywhere until that Serial port is recognized on your computer.


According to this guide:

  The RST pin of the ESP8266 is always HIGH while the ESP8266 is
  running. However, when the RST pin receives a LOW signal, it restarts
  the microcontroller.

  If you set a Deep Sleep timer with the ESP8266, once the timer ends,
  GPIO 16 sends a LOW signal. That means that GPIO 16 when connected to
  RST pin can wake up the ESP8266 every time the timer ends.

The only way to wakes up ESP8266 from deep sleep mode without timer is set a LOW signal on RST pin.

Example without timer:

ESP.deepSleep(0);

Connect D0 (GPIO 16) to RST is available only when ESP8266 is in sleep mode with timer.

Example with 30sec timer:

ESP.deepSleep(30e6);

In your case, you can use deep sleep with timer and connect Door sensor to D0 and will act as switch between the RST and D0.