Your calculations are not totally right. I did not check the data you provided, so I'm just using the numbers you put.

The arduino draws up 45mA @5V.
The sensor has a power of 150 mW and is powered at 5V, which means a current of 30mA.
The bluetooth module gets 8mA (are you really sure? it seems too low) @3.3V.

Now, the battery gives you 9V. So you need to convert them to the proper (5V and 3.3V) voltages required by the devices.

You have mainly two options:

you use a linear regulator
you use a switching regulator

(Please note that if you use the regulators already present on the UNO board - the 1117 and the LP2985 - you will use the first approach)

In the linear case, the regulator will drop the voltage by dissipating the excess power through heat. In this case, you will need to sum the currents:

Total current = 45mA + 30mA + 8mA = 83mA. Please note that if using a 9V battery, the 5V regulator will need to dissipate (9-5) * 83mA = 332mW of power (or slightly less if the 3.3V regulator directly interfaces to the 9V battery).

Now, according to the first datasheet I stumbled upon on google, this kind of battery have a capacity rated at 10mA, but at 100mA it loses about 40% of it. In fact, batteries tend to last less when the current increases (if you double the current you will get less than half of the time).

Considering so a mere 30% of loss at 83mA, your battery will last slightly above 4 hours and a half (550mAh*70%/83mA)

Now, if you use a switching regulator to get 5V from the 9V (and then a linear one to get the 3.3V), you will have to generate 83mA at 5V. This means that, considering an efficiency of 85%, your battery will have to provide roughly 54mA (83mA*5V/9V/85%).

According to the datasheet of the battery, this lower current reduces the degradation of the capacity to about 25%. The total uptime is consequently 7 hours and a half (550mAh*75%/54mA).

If you put a second switching regulator to get the 3.3V, you will have
- 75mA at 5V, which with a 85% efficiency will become 49mA
- 8mA at 3.3V, and with a lower efficiency due to the very low current (let's say 75%) become 4.4mA

Total current from battery: 53.4mA (which can be considered equal to the case with just one switching converter.

Just one last note: please consider that a heated sensor like the one you have is not engineered for battery-powered devices, since a lot of power becomes heat. When you want to develop a real battery-powered sensor, you will need to go with a lower-power solution for both the microcontroller (and the board) and the sensor


The second line masks off the top two bytes using a bitwise AND.

When you use a bitwise AND it follows the normal rules for any boolean truth table.  1 & 1 = 1, 1 & 0 = 0...  Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved.  In this way you can extract the lower two bytes out of the four byte long.


As your program is currently written, you should see your LED light. I see nothing wrong with your program or your wiring. I am also assuming that you had no errors while compiling and downloading the program.

With the rest of the lines uncommented, what you should see is your LED light up for 1.5 seconds and then off. Then after another 1.5 seconds, the on-board LED should turn on and then off (both 1 second).

If you have wired up the LED wrong (or a bad connection), you should at least still see the on-board LED flash about once every 5 seconds. If you don't see this then something else is wrong.

One thing I notice from the photos is that you have no way of powering your circuit. (I realise this may just be while you took the photo). Plug a USB cable into the Arduino and the other end into the computer. You should see the LED called "POW" light up.

To verify your LED circuit, try disconnecting the jumper at D12 and connecting it to 5V and you should see the LED light. If this works then your circuit is OK so replace the jumper back at D12.

If the LED still does not light up when the jumper is connected to 5V then we need to dive into that circuit. Possible reasons include:

The LED is dead -> replace the LED
The breadboard is not making good connection -> wiggle the leads (to scratch away any corrosion) or twist together the wires where possible or even solder them together.
The jumper wires are manufactured poorly (eg. the plastic wasn't stripped before crimping) -> check the jumper crimps.
The LED has been manufactured wrong and what should be the anode is actually the cathode (I have seen this) -> reverse the polarity of the LED.
The resistor is burnt out -> replace the resistor.


You may purchase a servo motor with greater torque.

You may find both DC as well as AC servo's. If you are using it in a real industrial scenario I would suggest you to use the AC, as you may not have to convert the ac power to DC and these motors will need real high current. So it would be better if it works on the main voltage. I did find PANASONICs ac servo as google search result.

If you have problems with integrating the greater torque motor to your current system let me know i can help you out.


Use digital pins as analog - Arduino Micro

Constants are variables that cannot change. They are constant.

In this case they are variables that have been set up in the board definition files (in pins_arduino.h in case you're interested) and are named just as they have said - A6 through A11.  This complements the existing A0 through A5 that are normally there anyway.

So you just use those names and it chooses the right pin for you:

int val = analogRead(A8);

The definitions of the pins are:

static const uint8_t A0 = 18;
static const uint8_t A1 = 19;
static const uint8_t A2 = 20;
static const uint8_t A3 = 21;
static const uint8_t A4 = 22;
static const uint8_t A5 = 23;
static const uint8_t A6 = 24;   // D4
static const uint8_t A7 = 25;   // D6
static const uint8_t A8 = 26;   // D8
static const uint8_t A9 = 27;   // D9
static const uint8_t A10 = 28;  // D10
static const uint8_t A11 = 29;  // D12

So no you cannot just use the number 8, you have to use A8 which points to pin number 26. The Arduino core then interprets that number as an analog pin (as opposed to the digital pin, which is 8) and performs an analog read on it.


Modify On board 4 pin switch to work with Arduino

Although it looks like 4 pins it's actually 2. You can see that they are connected together in pairs. This is identical to any other tactile switch of the kind used in many Arduino demos and examples.

All you need is some way of connecting the left pair of pins to the right pair of pins (in the underside image). The right pair are ground (you can tell because they are connected to the ground plane - the large copper area), so the input the left pair of pins are connected to must be active-low with a pullup resistor. That makes things simple enough.

If you can share the grounds between the switch circuit and the Arduino then it's possible to do it with just wires. However care must be taken:

Chances are this is a 3.3V based system (there's very few 5V systems around these days - the Arduino is pretty old technology from that perspective), so just setting an output HIGH or LOW and connecting it directly could damage the switch. Instead you need to emulate an open drain output. That means instead of setting a pin to OUTPUT and toggling it between HIGH and LOW to press the button you actually have to toggle the mode of the pin - that is, toggling between INPUT and OUTPUT + LOW.

For instance:

void press() {
    digitalWrite(BUTTON_PIN, LOW);
    pinMode(BUTTON_PIN, OUTPUT);
}

void release() {
    pinMode(BUTTON_PIN, INPUT);
}

You can, if you so choose, turn any GPIO pin into a real open drain output by using it to switch a transistor which in turn switches the button:

simulate this circuit – Schematic created using CircuitLab

Now it's just output a HIGH to turn the transistor ON and short the button, or LOW to turn the transistor OFF.

If you can't / don't want to share the grounds, then you can replace the transistor with an opto-isolator:

simulate this circuit

That is by far the safest option since it completely isolates (galvanic isolation) the Arduino and the switch box.


Pin headers too long for the sensor i bought

Cut one pin off.

Get some wire cutters and position them in the groove between the last and next to last pins in the row. Squeeze. One pin will pop off.


Pulse Sensor Working Bottom-Side-Up Better?

From what I see, this is a pulse sensor that work with light. It emits a bright light beam, that is reflected by the pulsing blood. To work, it must send the light directed to your veins. It should work well on your finger, because the probability to target a vein directly is much greater with a small finger then e.g. a wide wrist. Also the veins in your finger are closer to your skin and the oxygen situation is more different while pulsing, so the blood has more impact on the reflection.

The second curve might be a light source in your room, or an electrical wave. (?) I doubt it is your heart, because, if the numbers below the graph are milliseconds, then your heartbeat would be between 10-15 beats / second, i.e. 600 - 900 per minute. That would be too much even for a hummingbird ;-).


When you output HIGH you connect the pin to +5V. When you output LOW you connect the pin to ground.  It's called a push-pull interface, and looks like this:

When it's set HIGH the p-FET is turned on and the n-FET is turned off. That connects the output direct to VDD. When it's set LOW the p-FET is turned off and the n-FET is turned off. That connects the output direct to GND.

They are just like switches, as depicted to the right. Only one is closed at a time - when HIGH the upper switch is closed, when LOW the lower switch is closed.

So you just connect the output pins of the Arduino direct to the input pins of your device and write either HIGH or LOW to them to set the 5V or GND connections you need.


Why does the Arduino Due have a native and USB programming port?

Either port can be used for programming, but the native USB port lets you do other things:

  It also enables the Due to emulate a USB mouse or keyboard to an attached computer. To
  use these features, see the Mouse and Keyboard library reference pages.

  The Native USB port can also act as a USB host for connected
  peripherals such as mice, keyboards, and smartphones. To use these
  features, see the USBHost reference pages. http://arduino.cc/en/Main/arduinoBoardDue

So you can use the Due to interface with USB devices or connect it to your computer and have it act like a USB device.


Arduino IDE/Visual Micro - Undefined reference to constructor

You're using a template class. A template class is a special corner case that breaks the "code in .cpp and definitions in .h files" rule.

Because it's a template it can't be pre-compiled - it needs to be specially compiled each time it is used, so that it can get the right values compiled in to the template place-holders, which are provided by the CU that has the template class included with it.

Because of that it is one of the rare cases where the code has to be in the header file.

For a full example you can take a look at my Average library which is a fully templated class.


What functions are disabled with noInterrupts()?

From what I found turning off interrupts will definitely disable incrementing values of micros() and millis() This means that also every method that uses them like delay() will also not work correctly.

Of course manually attached interrupts using attachInterrupt() will also not work as intended.

According to comments by @Juraj Things that also will not work are Serial interrupts. Also libraries like Wire require interrupts for their logic.

EDIT: @EdgarBonet You are right, I removed incorrect info.


How can I add two different programs of bldc motor and servo motor in one so that they work in parallel?

Depending on how the code is driven. The simplest would be to simply run loop1 and loop2 in the new loop.


Is std::array (from the C++ STL) safe to use on arduino? Does it use dynamic memory allocation?

std::array does not use dynamic memory allocations to store its elements. If you use static or stack-allocated std::arrays, you don't have to worry about memory fragmentation (contrary to std::vector or String, for example).
Of course, if you allocate arrays on the stack, you can have a stack overflow if you call too many functions, either by design, or because of a bug.

That brings us to the problem of exceptions. If you look in the standard, you'll see that most of the member functions of std::array are marked noexcept, with the notable exception of the element accessors. Obviously, the at() accessor can throw, but you'd expect that operator[] doesn't.
In practice, operator[] is marked noexcept in the version of the STL (GCC9) that I have on my computer, so if you check it in the STL implementation you're using, you can be pretty confident that it won't throw. Just keep in mind that this is not mandated by the standard.

/usr/include/c++/9/array

      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      { return _AT_Type::_S_ref(_M_elems, __n); }

The debug version is also marked noexcept, but it can throw/abort if the index is out of bounds:

/usr/include/c++/9/debug/array

      // Element access.
      _GLIBCXX17_CONSTEXPR reference
      operator[](size_type __n) noexcept
      {
    __glibcxx_check_subscript(__n);
    return _AT_Type::_S_ref(_M_elems, __n);
      }

      constexpr const_reference
      operator[](size_type __n) const noexcept
      {
    return __n < _Nm ? _AT_Type::_S_ref(_M_elems, __n)
     : (_GLIBCXX_THROW_OR_ABORT(_Array_check_subscript<_Nm>(__n)),
        _AT_Type::_S_ref(_M_elems, 0));
      }

The STL implementations for Arduino I found online don't seem to have the <array> header.

Luckily, you can easily create your own array container, for example:

template <class T, size_t N>
struct Array {
    // Storage
    T data[N];

    static size_t length() { return N; }
    using type = T;

    // Item access
    T &operator[](size_t index) { return data[index]; }
    const T &operator[](size_t index) const { return data[index]; }

    // Iterators
    T *begin() { return &data[0]; }
    const T *begin() const { return &data[0]; }
    T *end() { return &data[N]; }
    const T *end() const { return &data[N]; }

    // Comparisons
    bool operator==(const Array<T, N> &rhs) const {
        if (this == &rhs)
            return true;
        for (size_t i = 0; i < N; i++)
            if ((*this)[i] != rhs[i])
                return false;
        return true;
    }
    bool operator!=(const Array<T, N> &rhs) const {
        return !(*this == rhs);
    }
};

void setup() {
  Serial.begin(115200);
  while (!Serial);

  // Create an array
  Array<int, 5> myArray = {1, 2, 3, 4, 5};
  // On older compilers, use double braces:
  //    Array<int, 5> myArray = {{1, 2, 3, 4, 5}};

  // Iterate over the array
  for (int element : myArray)
    Serial.println(element);

  // Access elements of the array
  myArray[2] = 30;
  Serial.println(myArray[2]);
}

void loop() {}


The first error I see with the sketch is right under this line of code Serial.println("Triggered D");. You are incrementing the variable brightness when you probably meant to decrement it.

The second error is with your call to analogWrite(). This function accepts an integer between 0 and 255. You do not constrain the value to that range, and can see what I mean by adding this line of code Serial.println(brightness); right above this one irrecv.resume(); in your sketch. Going from 0 to -5 turns the LED from off to maximum brightness. Is this what you want it to do?

The errors with your MOSFET circuit is a "General Electronics" question, and should be asked on electronics.stackexchange.com. As I mentioned in one of my comments to your question, there is a recommended format for drawing schematics.

My other comment was regarding this Q+A at EE. You won't find a consensus on exactly how to use a MOSFET there either, but the image in this answer may be helpful to you.


Why can't I upload a sketch while other components/devices are connected to my Uno?

The problem is specifically pins 0 and 1. Although they can be used as regular digital IO pins, they also serve as the RX and TX pins for the Uno's serial port. The USB connection (for uploading sketches etc.) is routed to the same pins internally. Unfortunately that means anything connected on pins 0 and 1 can interfere with the serial connection, preventing communication via USB.

In short, it's not necessary to disconnect everything when uploading a sketch. It should only be necessary to disconnect anything from pins 0 and 1. Rather than going through that hassle every time a sketch is uploaded though, it may be best just to avoid using those pins unless necessary (e.g. you run out of other pins, or your project needs a serial connection to another device).


I strongly suspect the main problems with your code are in these lines:

  if(detect2 <= (master2 - 10) || detect2 >= (master2 + 10)) {
    accumulator++;
  }

If I understand correctly, with this code you are attempting to tell whether you have been over a line of tape, which will be indicated by a change in reading from RGB.readGreen(); - say high, low, high.  If so, accumulator++.  (I have no opinion on whether this is a valid way of sensing it, or how well your sensor will work.)

This is definitely broken in one way, and probably broken in another.

First the definitely-broken way:

You want to sense down-up-down-up-down-up (or up-down-up-down-up-down).  Your code senses simply three higher or lower readings.  Your loop() takes no time at all, so when your buggy moves onto the tape, it will immediately read (say) high, then loop round, read high again, loop round and read high again, and again. accumulator is now 3 and we stop the motor.

Second, the maybe-broken way:

What value does master2 have?  Consider that it is an unsigned integer.  You are subtracting 10 from it.  What do you get if its value is 5?  It can'be be -5 because it is unsigned.  How you solve this depends on the possible range of values from RGB.readGreen();.  The implementation looks like it could give a value anywhere in the range, so we have to be careful.

Here's my reworking of your code.  It assumes the concept of checking for values which vary by 10 from the original value is sensible - I've no idea if it is.  (I don't understand what this "middle" values means, but you say you've "already tested the components individually" which I don't believe because your code could never have worked but, assuming you saw something similar working...)  It also makes a very big assumption that the value will change cleanly - from higher to lower exactly once per edge of strip, with no wobbling.  Log out some values to find whether it really does.

#include <SFE_ISL29125.h>
SFE_ISL29125 RGB;
int master2;
boolean isOn = false;
int changes = 0;

#define BUTTON 7
#define MOTOR_A 8
#define MOTOR_B 9

#define LOWER 0
#define HIGHER 1
int last_state = 0;

void setup() {
  RGB.init();
  pinMode(BUTTON, INPUT);
  pinMode(MOTOR_A, OUTPUT);
  pinMode(MOTOR_B, OUTPUT);
  master2 = (int)(RGB.readGreen()/2);
}

void loop() {
  if(isOn) {
    // Wait for 6 changes: up-down or down-up, three times.
    if(changes < 6) {
      int detect2 = (int)(RGB.readGreen()/2);
      digitalWrite(MOTOR_A, HIGH);
      digitalWrite(MOTOR_B, LOW);
      // Count _changes_ in state only
      if(last_state == HIGHER && detect2 <= (master2 - 5) {
        last_state = LOWER;
        changes++;
      } else if (last_state == LOWER && detect2 >= (master2 + 5)) {
        last_state = HIGHER;
        changes++;
      }
    } else {
      accumulator = 0;
      isOn = false;
      digitalWrite(MOTOR_A, LOW);
      digitalWrite(MOTOR_B, LOW);
    }
  } else if(digitalRead(7) == HIGH) {
    isOn = true;
  } else {
    digitalWrite(MOTOR_A, LOW);
    digitalWrite(MOTOR_B, LOW);
  }
}


Count specific range of output as 1 single output

There are two distinct problems here.
The first problem is to convert the analog reading into a binary value.
You measure a value between 314 and 856, and you want to know whether
the LED is ON or OFF. The simplest solution is to compare the reading to
a threshold that is roughly in the middle of the range you measure. You
could say, for example, that the LED of OFF if the reading is below 580,
and is ON otherwise:
bool led_is_on = analogRead(ldr_pin) >= 580;

If the readings are noisy while they cross the threshold (does not seem
to be the case in the short span of data you show), you may want to use
some noise cancelling techniques. You could, as suggested by Michel
Keijzers, require multiple consecutive “ON” reading before deciding the
LED is actually ON. Or you may research the technique of using
hysteresis, which would be my favorite solution, as it is extremely
simple. However, if your readings are always as clean as what you are
showing us (never fluctuating mid-range), you can stick with the simple
threshold solution shown above.
The second problem is called edge detection. You want to count the
blinks. For this, you need to count how many times the LED turns ON,
which is not the same as how many times the LED is ON. You know that
the LED turned ON if you just detected it is ON and, on the previous
iteration it was OFF. So you have to remember whether the LED was ON
last time you looked at it. This means you have to store this
information (whether the LED was ON) in a static (or, if you prefer,
global) variable. Which leads to the following program:
int blink_count;

void loop() {
    static bool led_was_on = false;
    bool led_is_on = analogRead(ldr_pin) >= 580;
    if (!led_was_on && led_is_on) {
        blink_count++;
    }
    led_was_on = led_is_on;
}

Note the condition: !led_was_on && led_is_on means “The LED was not
ON and now it is ON”.


Very interesting project. What to do depends largely on your exact requirements. I guess you have chosen RFID for its easy usage, when everything is set up (like just placing the item roughly at the right spot, instead of needing extra electrical plugs or similar).

I'm not being able to scale it

In a case like this you normally wouldn't use just one Arduino. I would use multiple Arduino Nanos (or similar), each interfacing only a few RFID readers. Then I would use a long range interface (like RS485) to let a master Arduino communicate with all other Arduinos. That way you can faciliate the RFID interfacing code to many Arduinos (which also gives you an easier method of scaling up). Arduino Nano clones are rather cheap (like about 2$ or less I think).

Now items per rack are about 30 that would be so daunting task to place 30 scanners on each rack

Placing 30 RFID moduls per rack is a big task, yes. But that is the price for such a system. If that is too much for you (either in work time or in money), you would need to think about different approaches than RFID. Each approach, that I can think of, will also give you some caveats.

You could use bar codes and bar code scanners on each place. That has a similar difficulty to the RFID approach.
You could give every item an electrical plug, that connects to a fitting socket  on the rack. The ID of the item could then be hold on the item plug by either a number of electrical connections (giving you a binary code) (many electrical lines needed) or by a single chip like an EEPROM (which was programmed with the item ID) (less lines needed).
You could give each item a unique strip with a color code and use multiple color sensors on each place in the rack to identify the item (it has to be put in at the exact correct orientation for reading the colors) (potentially many electrical lines due to multiple color sensors).

All these options are not really better than the RFID option. I would consider the plug with the EEPROM chip the best option from the RFID alternatives above, since these chips can be rather cheap. Though it will be a toll onto the work, that has be done for each item (assembling the plug with the EEPROM chip). Also the infrastructure with the extra Arduinos for every group of a few places in the rack is also needed here.
All in all the RFID option is rather good in comparison to the others. Its main caveat will be the cost, since the RFID reading pads are not very cheap.
Aside from those options, you could make bigger compromises. Big warehouses often have a system, where a worker caries a bar code reader and has to read the bar code of the item and of the rack space, where he will put it. The system can then know, where the item is and if that location is the correct one, and show that on a handheld. That will be way easier to implement, but takes a greater toll on your usability.

I've tried 4-5 RFID scanners with one Arduino uno watching a youtube tutorial and failed.

If you want help with that, you would need to describe, how exactly you failed. Please provide your code, a link to the youtube tutorial and links to any other resources, that you used. Include a detailed description about, what you expected and what actually happened. And put all this information into your question by editing it (not in the comments).
Also as a side note: I've had rather bad experiences with youtube tutorials. You might wanna search for a text based tutorial.


How to detect if LED is switched on in external circuit using Arduino NANO?

I'm afraid your circuit does not work.
In fact, the base of the transistor is always connected to the power, regardless the LED being ON or OFF. Therefore the BJT would be always in the ON-state. Also a current limiting resistor in series to the LED is missing (but I think that it was just for sake of simplicity).

Assuming that:

you can mount in series something to the LED
an additional 1.3-1.5V voltage drop will not cause too much issues (to be short: if the external circuit power supply is "large enough", and if you will not be too much upset if the LED luminosity will be smaller).
You want to sense a signal LED, i.e. let's say with a current smaller than 20 mA.

Then, the safest way would be to use an optocoupler, such as 4N25-4N35. Put the LED of the optocoupler (transmitter side) in series to the LED you want to "sense", and use the phototransistor side to sense the LED status: it's emitter goes to the GND to your Arduino Nano, the collector to any input, with pull-up (The pull-up is mandatory!).

In this way, when current flows across the LED, it will also flow in the optocoupler LED, therefore the optocoupler phototransistor will be ON.

Also, using the optocoupler the two systems are electrically insulated each other (and you won't need to share the grounds).

Below you can find an example.

EDIT:
If you cannot wire the optocoupler LED in series (e.g. not enough voltage headroom because the power supply is too close to the LED Vf, or your LED is already on a PCB), you can connect the optocoupler in parallel.
Assuming the LED current is much larger than 1mA, you can use the following circuit. Choose RO so that the current flowing on the optocoupler will be 1mA (390-470 Ohm in your case). Usage of high current-transfer-ratio (CTR) optocoupler is suggested, but this might work also with a 4N25 or 4N35 (you'll be pretty close to the limit...)


When connecting, client.connect() returns 0

You need to provide more than just the IP address. The Arduino also needs to know the default router address in order to send packets to the right place.

Unfortunately there isn't a way of giving it that information without also giving it a DNS address, so you have to do that as well.

You need to have:

IPAddress gateway(192, 168, 1, 1);
IPAddress dns(8, 8, 8, 8);
IPAddress ip(192, 168, 1, 25);

And then in setup:

Ethernet.begin(mac, ip, dns, gateway);

Alternatively you can rely on DHCP to give you all the details, and just use:

Ethernet.begin(mac);


This was a problem with using your OneDrive folder.

duskwuff wrote:

  This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

The issue with OneDrive folders has been resolved as of version 1.8.6.

https://www.arduino.cc/en/Main/ReleaseNotes

  ARDUINO 1.8.6 2018.08.23

  [ide]

  Updated arduino-builder to 1.4.0:

  parallel build (improve compile speed)
  better reuse of already compiled files
  Windows: fixed build for sketch stored under OneDrive cloud folders

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.


ESP8266 official library post request returns 400

400 is a HTTP error "Bad request" sent by the HTTP server. Possible reasons for this error are malformed HTTP request line, malformed HTTP request headers, missing empty line after the last HTTP header and a request to 'secure' port without encryption.

In your case the HttpClient library constructs the HTTP request so there should be no error. Only thing you supply for the request is the URL in your case it is the variable host. As we cleared in comments, your URL started with https. The HttpClient library parsed the url, detected the https protocol and used the secure port 443. But the underlying networking Client object was not SSL so it didn't encrypt the request.


You're printing the address of the pointer, not the contents of the pointer.

Say you have the memory map of:

100 20       test1 low byte
101 0        test1 high byte
102 100      ptr1 low byte
103 0        ptr1 high byte

test is located at address 100 and takes two bytes. ptr1 is located at 102 and takes two bytes. ptr1 contains the address of test (100) and test1 contains the value 20.

The different possible combinations of prints are:

Serial.println(test1);  => 20 (contents of test1)
Serial.println(&test1); => 100 (address of test1)
Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
Serial.println(&ptr1);  => 102 (address of ptr1)
Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

(note: some of those will require a cast in order for the C++ to select the correct println() overload function.)


You can Use PIR Sensor which is Cost Effective and covers upto 10 Meters


I thing the problem is not "void does not name a type", but "Void does not name a type".  Subtle difference:

Void setup()

should read:

void setup()

The same on

Void loop()

should be

void loop()

Watch those caps - C is case sensitive.


What is the output format of PINxn on atmega328p

Serial.print(PIND, BIN); will write the value in PIND to the serial port in Base-2 representation.


Cannot include .h files back one directory

Arduino IDE copies the files to a temp folder. You can see that when you compile in verbose mode.
As such the lib folder is not available.
You should place you libraries in [your home folder]/arduino/libraries


How can I split a string into three parts after space and turn the values to doubles?

You're almost there. Strtok returns the first token in the string only. You then have to convert that to a double yourself. You then call strtok again with NULL as the source string to get the next token. And so on.

I have written a good strtok example on here already. Look around, you may find it.


You're masking your outer dvert variable (and potentially others that you want to keep) with local variables inside the loop:

  int dvert = avgtop - avgbot; // check the diffirence of up and down

If you're just assigning a new value to an existing variable you do not want to declare a new variable!

Instead it should be just:

  dvert = avgtop - avgbot; // check the diffirence of up and down

And the same for anything else inside the loop that you want to assign to a variable that you have created outside the loop.


Most metals will tarnish, rust, or corrode when left in water, especially in the presence of an electric current. To be safe, a water sensor should either be gold-plated or made of a conductive, insoluble, non-metallic substance.


SD Card shield and TCRT5000 sensor aren't working together on arduino uno

Did you figure this out yet? If not, you have the +5 volts going to the GND on the breadboard, causing a short.


May I suggest the following. I found this fork of the Adafruit library which works better than the one they have on their website Adafruit_ssd1306syp. The original Adafruit_ssd1306 library doesn't play nice with SPI and when you want to have your OLED running on i2c and use the SPI for something else. This is a great resource. Download, unzip to your libraries directory. Then run this sketch:

#include <Adafruit_ssd1306syp.h>

#define SDA_PIN A4
#define SCL_PIN A5

Adafruit_ssd1306syp display(SDA_PIN, SCL_PIN);

void setup() {

  display.initialize();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  printM("Starting Demo...");

}

void printM(String mess) {

  display.println(mess);
  display.update();
}

void loop() {

  printM("working");
  delay(1000);

}


Extend program space by getting rid of bootloader on NANO

It's enforcing this line from the arduino:avr boards.txt
nano.menu.cpu.atmega328.upload.maximum_size=30720

To be clear, the board is assumed to have a bootloader, even if you're not using it to get the code onto the board, that is upload via programmer.
You could edit that and change some fuses yourself.  But you could also probably just use MCUdude MiniCore, choosing an option that does not use a bootloader, e.g. ATmega328P with No bootloader, which gives you maximum upload of 32768:
328.menu.bootloader.no_bootloader.upload.maximum_size=32768

Keep in mind that in either case you'll have needed to set the fuses for not having a bootloader.  As weird as this sounds, choosing the No Bootloader option in MCUdude MiniCore for the ATmega328P, and then doing Burn Bootloader sets these fuses for you, despite the name not actually burning a bootloader in this case.  If you were to edit the maximum upload size for the Nano board, you would need to manually set the fuses similarly to what Burn "Bootloader" does for the MiniCore ATMega328P with No-bootlader option.


No. You're way off.
If the output can provide 12mA at 3.3V that equates to (P=VI) 39.6mW.  Boosting the voltages does not increase the power. Assuming a 100% efficient boost circuit (which does not exist) you would just be boosting to 12V at 39.6mW - which means (I=P/V) 3.3mA.
You can't magic more power out of thin air - if you could we'd all have "free energy" devices powering everything. Instead we have power supplies or batteries.
And that is what you will need. A source for that extra power to come from.


How can I implement double buffering with an Arduino UNO?

If you're already preparing the next screen's-worth of data before you clear the screen, then double buffering won't help. In that case, the time taken to re-write the screen data is what causes the flicker, and the only way to improve it is to write the screen faster. If the software is to blame, it will be in screen.text(). If the software is already driving the hardware as fast as the hardware will go, then that's the best you can do.

Double-buffering would let you prepare the next screen while the currently-prepared one is loading (and will require interrupt-driven I/O to do it). The result would be more screen refreshes per unit time, but it doesn't sound like that is your problem.

One easy experiment to try is to not clear the screen before you re-write it, if that is possible to do. Then your next screen will overlay the current screen with (we hope...) no blanking period. That might prevent the blinking.


Why doesn't the Micro OLED library compile on my DUE?

That library is uses some AVR specific methods, that aren't implemented for the ARM processor in the Due.

I don't see a real easy way to port those methods.


The Stream member function readBytesUntil() does not null terminate the string. It returns the number of characters read. You must terminate the string with null(0) before calling atoi() and atof() or fill the string will null(0) before calling readBytesUntil().

For more details see Arduino Stream.cpp.

Cheers!


Yep, in fact I would configure them as INPUT_PULLUP (which uses a built-in resistor), unless you are actually wiring pull up resistors of your own to them.

Also the Digital pins Tutorial has a bit more info on the modes possible.


You are almost there. Now you just have to read and parse the hex
numbers supplied by the user.

The simplest way to accept numeric user input is with
Serial.parseInt(). This is not always ideal since it involves blocking
the program until it either receives an invalid character or the reading
times out. It is also not applicable to your situation because it only
works with decimal numbers.

The better standard way to get the input is to put the incoming bytes
into a buffer until you catch a specific character designated as an end
of message marker. This is typically a CR ('\r' in C++) or an LF
('\n'). This technique is more involved than just calling parseInt()
but it is often preferred because it can be done in a non-blocking way.
See for example this simple command line interpreter.

In your case, however, you do not need to buffer the incoming bytes. You
can instead parse the hex number while you read it, like this:

void loop()
{
    if (Serial.available()) {
        static unsigned int val;
        int c = Serial.read();
        if (c >= '0' && c <= '9') {
            val = 16 * val + (c - '0');
        } else if (c >= 'a' && c <= 'f') {
            val = 16 * val + (c - 'a' + 10);
        } else if (c >= 'A' && c <= 'F') {
            val = 16 * val + (c - 'A' + 10);
        } else {  // End of number.
            blink(countSetBits(val));
            val = 0;  // reset for next round
        }
    }
}


The simplest way would be to have two sketches.

One that will store all the strings into EEPROM.

After that you can upload the second actual sketch that uses the values stored in EEPROM.

You only need to upload the first sketch if any of the strings change.

There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.


Function only taking the first 4 elements of a character array

You are passing a pointer (char str[]) and the sizeof operator is giving you the size of that pointer (4 bytes it appears in your case - on some Arduinos it would be 2 bytes).

The length of a character array is found by using strlen - assuming the string is terminated by a null (0x00).


Why is this spitting giberish instead of serial numbers?

Casting a number to a char* doesn't convert the number to a string. Instead it converts the number to a pointer and starts reading chars from that location.

Either pass the number to a String constructor, or pass it through ltoa().

EDIT:

String ss(...);

or

char ss[11];
ltoa(..., ss, 10);

Also, don't forget to allocate memory for finalss and NUL-terminate it.

char finalss[12];
 ...
finalss[11] = 0;


Why is there no embedded c code in arduino libraries?

If you take a look at the Arduino core library (e.g., the AVR version of
wiring.c), you will see lots of low-level register access. That's
why the core code is specific to a processor architecture.

Other libraries are built on top of the core API in order to be
portable.


These are the In System Programming (ISP) pins. They are used to program the microcontroller without using the bootloader.

The bootloader is a program already loaded into the flash of the microcontroller that allows the program to be loaded into the microcontroller through the Tx & Rx serial lines and hence not requiring a programming device.

Using the ISP can be useful when:

The bootloader program doesn't exist in the microcontroller such as on a new chip.
The bootloader is corrupted.
Your program is just that little bit too big and you wish to gain the couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

The standard connection for the ISP is a 100 mil 6-pin header (2x3).

There are two ISP headers on the Arduino Uno because there are actually 2 microcontrollers on the board. There is the main microcontroller (aka the ATmega328P) which is used to execute the program you load into the Arduino board. The second microcontroller (ATmega16U2 or ATmega8U2) is used as a USB interface - converting the USB signals into serial data that is connected to the ATmega328P's UART (ie. Tx & Rx).

The following document details the ISP and gives descriptions of the pins used on the ISP header and how to interface them with the microcontroller etc.:
[PDF] AVR: In-System Programming - Atmel

EDIT: As Majenko correctly points out, the 2x3 ISP header closest to the ATmega328P can also be used to connect sensors and controllers that communicate using the Serial Peripheral Interface (SPI).

More information on the Serial Peripheral Interface and the SPI Library can be found at: https://www.arduino.cc/en/Reference/SPI


it seems like you are using the wrong serial interface. I see Serial and mySerial.

After mySerial.begin() you write to Serial, not to mySerial which runs on pins 10 and 11.

What's when you send the AT Commands from your Serial connection to the Arduino? It Should redirect them to the GSM board.


I don't think anything in your code is going to work.
First,
 you are asking the serial.Read to return an integer if it is working.  You might want to change that to a Boolean.

Second,
You are asking for a 1 and only a 1 to make your next if statement true.  If the serial.Read is working the chance it will only return a one, I think is very low

Third,
On the IF statement for setting timerReady. You will set that at a new number each time the program runs through, with the 90ms delay in the last IF statement, it looks like your timer will reset at about every 95-100ms

Fourth,
I think your last 2 IF statements are wrong, I think you want

if(timerReady==true) {
    if((currentMillis - lastreceivedtime) >= timebetween){
      digitalWrite(11, HIGH);
      delay(90);

If you do get this working you might need to set the Boolean back to false and move pin 11 to low at some point.


Measuring Lithium ion cell voltage used to power Arduino via a boost module

I'm the author of a library called BatterySense and you can use it to achieve your goal. In the repository Readme you can also find wiring diagrams and usage examples, but to give you a rough idea...

Verify the negative side of your battery has continuity to the GND pin of your Arduino: you need to identify if the boost module is messing the common ground, but if you have continuity then you are fine
Add a connection from the battery positive terminal going into one of the Arduino analog pins
Use the BatterySense library to get the battery voltage and percentage level


Run code via NRF24L01+ command "dynamically"?

What you are asking is very tricky at best. Your average Arduino doesn't have enough memory to start storing arrays of Strings.

Instead you will need to "distil" the information as it comes in and store the distilled information.

If the possible keys are all known beforehand then you can assign a number to each possible key - say RCP is 1, CMD is 2, VAL is 3, etc.  If the values are all numeric or can be represented by a number, then convert those to the corresponding number and store those.

Also the Arduino is not good at working with dynamic memory allocations - again because of lack of memory.  If you can decide on a reasonable maximum number of messages to store then you can pre-allocate the memory for them.

For instance it may be good to define a structure which is the content of a message:

struct message {
    uint8_t key;
    uint16_t val;
};

Then make an array of that structure - one slice per possible command, say 10 of them:

struct message messageQueue[10];

That would take a total of 30 bytes in memory - each entry being 3 bytes (1 for the key, two for the value).  Now you can set the keys and values to the correct data as it arrives.

Depending on how you want to deal with the messages as they come in - add them to the end of an existing queue, or always starting the queue from empty every time a new message arrives - you might want to implement a circular buffer.  This is basically how the Serial port on the Arduino works - in involves having two pointers to locations in the array - one where you are writing to, and one where you are reading from. As you write to the array the writing pointer moves along - if it reaches the end it starts from the beginning again.  As you read from the array the reading pointer moves along too.  If the two pointers are together then the array is empty. If the writing pointer would end up where the reading pointer is, the array is full.  Take a look in the Arduino source code (HardwareSerial.cpp) to see how it's implemented.

As for parsing the string as it comes in - if you have it as a single String already then it's a case of looking through it for the | characters and splitting out each portion in turn, then doing the same with each portion looking for the =. Then you can interpret what is in the key/value pairs and decide what to store in the array.


How to calibrate and use MQ-7 gas sensor?

This is the datasheet.  The output is not in PPM, but logarithmic to the PPM.

This Instructables guide,  Arduino CO Monitor Using MQ-7 Sensor, may help you, but calibration is required, preferably using a CO meter and, yes, heating-cooling cycles are required, in order to get the most accurate results. As the guide emphatically states:

  WARNING: SENSOR REQUIRES MANUAL CALIBRATION FOR ANY PRACTICAL USE. WITHOUT CALIBRATION, DEPENDING ON PARAMETERS OF YOUR PARTICULAR SENSOR, THIS SKETCH MIGHT TURN ON ALARM IN CLEAN AIR OR NOT DETECT LETHAL CARBON MONOXIDE CONCENTRATION.

Here is the sensor calibration part of the guide (just to give you an idea of what is involved). There are additional preparatory steps beforehand, that need to be followed, so you need to read the complete guide really:

  Step 7: Sensor Calibration

  According to manufacturer's datasheet, sensor should be running
  heating-cooling cycles for 48 hours in a row before it can be
  calibrated. And you should do it if you intend to use it for a long
  time: in my case, sensor reading in clean air changed for about 30%
  over 10 hours. If you won't take this into account, you can get 0 ppm
  result where there is actually 100 ppm of CO. If you don't want to
  wait for 48 hours, you can monitor sensor output at the end of
  measurement cycle. When over an hour it won't change for more than 1-2
  points - you can stop heating there.

  Rough calibration:

  After running sketch for at least 10 hours in clean air, take raw
  sensor value in the end of the measurement cycle, 2-3 seconds before
  heating phase starts, and write it into sensor_reading_clean_air
  variable (line 100). That's it. Program will estimate other sensor
  parameters, they won't be precise, but should be enough to distinguish
  between 10 and 100 ppm concentration.

  Precise calibration:

  I highly recommend to find a calibrated CO meter, make 100 ppm CO
  sample (this can be done by taking some flue gas into syringe - CO
  concentration there can easily be in the range of several thousands
  ppm - and slowly putting it into closed jar with calibrated meter and
  MQ-7 sensor), take raw sensor reading at this concentration and put it
  into sensor_reading_100_ppm_CO variable. Without this step, your ppm
  measurement can be wrong several times in either direction (still ok
  if you need alarm for dangerous CO concentration at home, where
  normally there should be no CO at all, but not good for any industrial
  application).

  As I didn't have any CO meter, I used a more sophisticated approach.
  First I prepared high concentration of CO using combustion in isolated
  volume (first photo). In this paper I found the most useful data,
  including CO yield for different flame types - it isn't in the photo,
  but the final experiment used propane gas combustion, with the same
  setup, resulting in ~5000 ppm CO concentration. Then it was diluted
  1:50 in order to achieve 100 ppm, as illustrated in the second photo,
  and used to determine sensor's reference point.

However, how accurate this guide is, is anyone's guess, to be honest.


Serial Communication Between 3 Arduinos Doesn't Work (Daisy-Chain)

Arduino #2 should have two SoftwareSerial instances, one to listen to Arduino #1 and another one to talk to Arduino #3:

// In Arduino #2
SoftwareSerial tiny1(10, 11); // Listen to Arduino #1 on pin 10
SoftwareSerial tiny2(8, 9);   // Talk to Arduino #3 on pin 9

You may not need to wire unused signals (11 and 8).

There is an example here : https://www.arduino.cc/en/Tutorial/TwoPortReceive

Note that what you are trying to do is a bus. Serial in Arduino is RS232 based and that is not a bus but a point to point protocol. You should consider using I²C or SPI.


Problem 1:

You wish to send/display on the Serial Monitor the int and float values generated by your sensor, but Serial.print() uses too much memory.

Solution 1:

Optimize your sketch to use less memory.

Problem 2:

Serial.write() doesn't cause the values to show up on Serial Monitor, but something is getting sent, because I see scrolling activity.

Solution 2:

Serial.write() sends raw bytes, whereas Serial.print() converts a variable to a string (or series of ASCII bytes) and sends that string. For example, Serial.write(65) sends A to the Serial Monitor because the ASCII value of A is 65; Serial.print(65) sends 65 to the Serial Monitor because it converts the numeric value 65 into a string containing the character 6 and the character 5, and sends that string to Serial Monitor.

The Serial Monitor expects only ASCII data. You are using Serial Monitor for development/debugging, but your final application does not require ASCII, only to transmit the numbers.

Serial.write() comes in a few forms. One is Serial.write(val) which sends a single byte (named val, of type byte or compatible). Another is Serial.write(buf, len) which sends a series of len bytes, starting at the address of memory pointed by by buf. (This is often when buf is an array of bytes, so buf points to the first element of the array.)

If you wanted to send the 4 bytes of a float using Serial.write(), you could call:

Serial.write(&(event.orientation.x), sizeof(event.orientation.x);

As an alternative, you can use bit shifting to send one byte at a time of the 4-byte float:

Serial.write((byte)((event.orientation.x & 0xFF000000) >> 24);
Serial.write((byte)((event.orientation.x & 0x00FF0000) >> 16);
Serial.write((byte)((event.orientation.x & 0x0000FF00) >>  8);
Serial.write((byte)((event.orientation.x & 0x000000FF)      );

On the receiving end, you need to reconstruct your float by doing the reverse.

But you have multiple 4-byte values to send, in rapid repeating loop, so what happens if your receiver and transmitter get out of sync? Then you might want to put in a "flag" value to indicate the start of a sequence of data and a different flag for the stop of a sequence of data. What happens if your start or stop "flag" value actually shows up as one of the bytes you send as part of a real data byte? Then you need to find some way to modify the "real" data so that it's not to be construed as a flag.

This looks to be getting complicated now? Fortunately, these problems have existed and been solved for decades. Unfortunately, there is no consensus on the best or right way.

I did a quick search and found this arduino library that facilitates packet-based serial communication:

https://github.com/bakercp/PacketSerial

Perhaps that can help you take a bundle of numbers and send them reliably to some other system. I don't know that library in particular, and there are probably others that do something similar. This one claims to be compatible with the PySerial, COBS, and SLIP modules for dealing with packetized serial data communications.


Why can't I read anything but Pin 0 of PORTC?

Judging from your readSensors() function, these seem to be capacitive
sensors:

you charge them to Vcc (DDRC = 1; PORTC = 1;)
you wait until they are fully charged (delay_us(10);)
you tri-state the pin (DDRC = 0; PORTC = 0)
you wait for them to partially self-discharge (delay_ms(1);)
you read the pin (return PINC;)

If my assumption is correct, and if all of those sensors are similar,
then here is your first bug: you are only charging the sensor on PC0. If
you want to charge the four sensors, you need to set bits 0 to 3 of the
port to active high. Thus, the first two statements in readSensors()
should be:

DDRC = 0x0f;   // bits 0 to 3...
PORTC = 0x0f;  // ...set to active high

Your second bug is in printBinaryLCD(). The function name, and the way
you call it, implies it is meant to print on the LCD the value passed as
a parameter. Instead, it is completely ignoring its parameter, and
reading PORTC itself. This is bad because the reading of the
capacitive sensors is time sensitive, so you should let readSensors()
do the work. You should then change printBinaryLCD() so that it
examines val instead of PORTC:

void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = (val & (1<<3)) != 0;
    ...etc...


Rc switch library transmit using protocol 5

I would expect your sending protocol 5 just fine.

But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.

This is the definition of the two protocols from the code:

{ 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
{ 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted.
The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses.
Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.


There's two things wrong with your sketch - one fatal and one that is more confusing for humans.

First the fatal problem:

for(byte i=0; i == count; i++)

That for loop is never going to do anything.  The way it is written it will loop only while i is equal to count (0 == 5) which it never will. Instead you need to loop while i is less than count:

for(byte i=0; i < count; i++)

The second issue is that you have named your function parameter variables the same as your global variables. While this is syntactically valid (the local variables will override the global ones) it is incredibly confusing for people to follow what is what and should be avoided at all costs.


It appears calling the method beginTransaction() prevents additional SPI transactions from interrupting the current transaction.  Calling endTransaction() allows access to the SPI hardware again. This added complexity may sound odd.  Especially in the simple Arduino sketch-writing paradigm.  But as programs grow in complexity, more SPI devices are added and interrupts are used to quickly access SPI devices - the likely hood of SPI contention increases.
In the SPIClass source code, there is this comment immediately before the beginTransaction() method:
  // Before using SPI.transfer() or asserting chip select pins,
  // this function is used to gain exclusive access to the SPI bus
  // and configure the correct settings.

So, it may be, that if the sketch-code is particularly well behaved and does not need protection from accidentally using the SPI hardware from multiple concurrent transactions, that these two methods need not be used.  But why take the chance.


instead of 9, it printed 90

No, it didn't: it printed “9”. However, it did not erase the previous
value before printing “9”. Before printing the 9, the LCD had:
┌────────────────┐
│time left       │
│10              │
└────────────────┘
 ^cursor position

When you printed “9”, that character replaced the “1”, and you end up
seeing “90”.
The fix, as pointed out by Juraj, is to add a space after printing the
numbers.
An alternative is to prepend a space (or a zero), but only when the
number to be displayed is less that 10:
int count = 20 - millis() / 1000;
if (count < 10)
    lcd.print(' ');  // alternatively: '0'
lcd.print(count);


A sketch isn't an object. It is merely a collection of variables, functions and, of course, classes.

Your example seems to be trying to make things incredibly complex when they don't need to be.

There are a number of ways of referencing things in one file from another - whether or not they are in a class.  The simplest is to use the extern keyword.  This is used in a file where you want to reference a variable or function that is defined in the global scope of another file. It says "This variable is global, but it's defined somewhere else."

// Sketch
String myString = "foo";

// Library
extern String myString;
// ... later on ...
myString = "bar";

Of course, that means that the name of the variable is fixed and cannot change.  So you can pass the variable to whatever it is you want to use that variable in.  That could be as simple as passing it to your "changer" function:

// Sketch
String myString = "foo";
StringChanger change;
// ... later ...
change.changeString(myString);

// Library
class StringChanger {
    public:
        void changeString(String &stringToChange) {
            stringToChange = "bar";
        }
};

If you want to "tie" the variable to the class so you don't have to pass it each time you could pass it to the constructor and have the class remember it:

// Sketch
String myString = "foo";
StringChanger change(myString);
// ... later ...
change.changeString();

// Library
class StringChanger {
    private:
        String *_string;
    public:
        StringChanger(String &string) {
            _string = &string;
        }
        void changeString() {
            *_string = "bar";
        }
}

And there's a myriad of other ways of doing it.


Error: invalid types 'int[int]' for array subscript

Take a close look at this line:

motor[1][j]->run(RELEASE);

Looks like it should be:

motor[i][j]->run(RELEASE);

Otherwise it is an illegal index (as there is only one shield).

The next error is in the function switchMotor(). Again, have a close look at the definition of "motor". There is a local variable with that name but you want to also access the global array with the same name.

void switchMotor()
{
  int shield = currentShield - 1;
  int motor = currentMotor - 1;
      ^
  for (int i = 0; i < nShields; i++) {
    for (int j = 0; j < nMotorsPerShield; j++) {
      if (i == shield && j == motor)
        motor[i][j]->run(FORWARD);
        ^
      else
        motor[i][j]->run(RELEASE);
    }
  }
}

My guess is that this is where the compiler give you the error message!

Cheers!


How do I control multiple LEDs strips with Arduino

Assuming your LED strips are essentially "always on" when they have power, you could replace the single LEDs in your diagram with transistors that sit between the power supply and the strip. Then, when your Arduino pin goes high, the transistor turns on the LED strip.


How do I know how many memory that Arduino is use after my code is running for a few time

Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.

You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).

You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.


Troubleshooting WS2812b LED strip with toggle on/off button

The manual for the T2200, which I think is what you're referring to, says:

Note: If the PowerPack does not automatically power on when a device
is connected press the power button. The PowerPack will turn off after
90 seconds when there are no devices connected.

This is a common feature for USB battery banks meant for charging phones and similar devices.  It probably shuts off when the current drops below some set limit, say 50mA for more than 90s.  But it could also be looking every 90s for the average current over the course of 10ms.  They just don't say.  Given their description it sounds likely that it regularly turns on for some short time to probe for a load.  All in all, not knowing the specifics of this may drive you nuts.  Part of the thing to keep in mind is that someone using this thing to charge a cellphone wouldn't necessarily notice or care if it cut in and out every few seconds.  If you want to use this to power an Arduino it's worth getting a good handle on how it behaves through some experimentation.  Some of these power banks do have a way to disable their load detection and auto-shutoff feature; I did not see anything about that for this model.
The Nano, the official one anyway, has a 500mA PTC polyfuse on the USB VBUS ("5V").  Your code says #define NUM_LEDS 14.  The WS2812b LEDs use something on the order of 50mA each at max output.  You should probably measure what you're actually drawing, with the intensity you are commanding them to be, to be sure you're a good margin below 500mA.  If you are in fact using 14 of them, and if it's possible that all can go full brightness, then you are perhaps trying to use something like 735mA, quite a bit above 500mA.  You way find that it's necessary to route 5V around your Arduino to your LED strip, ideally through its own over-current protection.
Each time you power on or reset your project there's going to be some time before the sketch sets the pin connected to WS2812 data signal to output and some defined level.  It may be a good idea to add an external pull resistor on the LED data signal, probably to GND, so that during power-up and reset the LED strip data signal is not picking up noise and trying to interpret it as color data and changing your load on your power source in the process.  Having the powerbank potentially turning your project on and off gives extra opportunities for this to happen.  If you trip the polyfuse, either by commanding the LEDs to draw too much or having the floating data pin do likewise, the voltage on the Nano side of it will drop.  When the voltage drops it may trip the AVR microcontroller's brownout detector, which in turn will reset it the AVR, again bringing about a floating data pin on your LED strip.


Using GPS Module ET314AC With arduino Mega

yes you can, the datasheet is saying that you can read from a serial port which is what you want to do.

Connecting the serial port to TX and RX pins of the Arduino, ground and power, you should be able to talk to the module.

I cant find a breakboard for this module so I suppose you are going to solder it or you can give us the link where you bought it.

I suggest you to try with TinyGPS library to decode the data, after you are sure that the module is talking to the Arduino correctly.


While this may not exactly answer your question, there may be some information about u8g2lib that you have not seen. The library source code is linked here: u8g2lib

Within that repository is the FAQ documentation which includes such gems as:

  Q: U8g2 requires a lot of memory. How to reduce this?
  - Visit https://github.com/olikraus/u8g2/wiki/u8g2optimization
  - Disable U8g2 features if possible (see u8g2.h)
  - Limit the font size. If possible avoid "f" fonts, instead use "r" or "n" fonts
  - If the I2C interface is not required, then uncomment #define U8X8_HAVE_HW_I2C in U8x8lib.h   (Background: Due to a problem in
  Wire.h, the I2C Arduino lib is always included)

and

  Q: How can I generate my own font. A: The font must be available in
  bdf file format. Then use bdfconv to generate the font data. The font
  data can be pasted into an existing file of your project. There is
  also a nice Windows Bitmap Font Editor "Fony"
  (http://hukka.ncn.fi/?fony)  which can export .bdf files. A copy of
  Fony 1.4.7 is available here:
  https://github.com/olikraus/u8g2/tree/master/tools/font/fony

The tools/font directory includes several utilities, including what looks like one that converts OTF fonts to BDF format

Once you get a BDF format font, you use bdfconv to create the C file that holds the font array. One of the arguments for bdfconf is the -m 'map' option. You can place in there a list of Unicode ranges that limit which characters get included. So, you can create a font that has ONLY the characters you need.

For example -m '45-46,48-57,77,107,109,181,937' gets you minus, decimal, 0-9, 'M', 'k', 'm', mu, omega. Unicode character map at https://unicode-table.com/en/

The benefit to creating a font is that the u8g2lib library itself does all the mapping to bitmaps and calculating the character widths, etc. so you don't have to.


Serial Commmunication between two arduino

The problem is that a serial connection usually connects two devices, in your case it's three (sensor arduino, receiving arduino and your pc).

To get around this you have to use an additional software serial on different pins on the receiving arduino (unfortunately the atmega328 has only one hardware serial interface).
As long as you don't have to send anything from pc to the receiving arduino and from the receiving arduino to the sensing one you could try to simply disconnect the wire receiving-TX to sensing-RX and see if it works. In this latter case you could actually get rid of the receiving arduino at all.

Edit: another important point was mentioned in JRobert's answer: grounds of devices communicating with each other must always be connected!


Send big amouts of data to PHP script via gsm module SIM800L

Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

Do a POST request. You can send huge amounts of data in the body.

  In the response from my SIM800l I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.

Nope.

I guess you're doing something like:

sendCommand("AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54");
delay(1000);
printResponse();

The problem there is that you're relying on the internal buffer of SoftwareSerial (or HardwareSerial if you use a real serial port). You wait for a predefined time for characters to arrive, and then after that time print them out.  The serial code has a 64 byte buffer.

I see that kind of code all over the place, and it's the worst possible way of reading serial. Whoever posted the first instance of such code and started this chain of evil should be taken outside and shot.

Instead you must read the serial properly. Being lazy like that doesn't work.

Read this blog post to learn more about reading serial data properly.


If you look at the schematic on the product page it shows that the Vin from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.

With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that it cannot be made to reverse, therefore you should always give the direction pin a high signal. The Sparkfun hookup guide has a example code which shows how to control the motor shield, and some explination.


I got this ILI9341 *i 'm not sure * from ebay and i cant manage to use any librarys

Do a google search for MCUFriend LCD library. I believe you want this library


PROGMEM : pgm_read_float_near() equivalent for double? (Arduino Due)

Arduino Due (ARM Cortex-M3) doesn't need anything like PROGMEM as it has access into the flash memory in the same way as into the RAM. The const qualifier is enough to keep it in program memory only.

The AVR based boards like UNO needs PROGMEM because there are different instructions for fetching data from program memory and g++ is not very advanced in this way (some other compilers supports it directly - but usually expensive ones)


Is it possible to compile and upload code witout the IDE?

Yes, I haven't used it but on the official page it is mentioned, called Arduino CLI (command line interface), available for Mac and Linux.
https://www.arduino.cc/pro/cli
Excerpt:

Arduino CLI is a command line tool that contains all you need to
easily build applications around the Arduino ecosystem. Parse the JSON
output of the CLI or implement it as an always-on service that accepts
commands via a gRPC interface using your language of choice.
Arduino CLI is the backbone of the Arduino Create Web Editor serving
over a million users.

Also, it's open source and can be found on GitHub at https://github.com/arduino/arduino-cli/releases


Can MP3 be sent to SPI of Adafruit Music Maker Arduino shield instead of from its SD card?

As far as I can see the SD card on the shield isn't read by the VS1053 directly, but by the arduino, which sends it to the VS1053.

So as far as I can see, you should be able to do what you want.


How to solve problem AT+INQ ERROR (1F), AT+INIT ERROR(17) on Bluetooth Module HC-05?

I have two modules:

(A) HC-05 with firmware version 3.0-20170601

(B) HC-05 with firmware version 2.0-20100601 (ok)

I have the same problem: when the AT command "AT+INQ" is sent on (A) module, the response is always "ERROR:(1F)". This error code seems not be reported in any document or specification available on internet. This BT module have firmware version (AT+VERSION) 3.0-20170601. Also I have noticed that command AT+INIT on (A) module returns always ERROR:(17), this error normally can be ignored if the command has been sent already (Initiate SPP lib), but the first time should be return "OK" as on (B) module.

The (B) module with firmware version 2.0-20100601 works ok with the following commands (set PIN34 high at power-up, or press button on module and keep pressed during commands):

AT+RMAAD -> delete all paired devices list

AT+ROLE=1 -> Set master mode

AT+RESET -> reset module to enter into master mode

AT+CMODE=1 -> Permit connection with any device

AT+INQM=0,5,9 -> Set Search parameters(Query mode standard, 5 devices, 9secs)

AT+INIT  --> Init SPP profile mode (first time response: "OK")

AT+INQ  --> Start search devices (return device list after some seconds)

The differences between two modules are:

On AT+INIT the (A) module return always ERROR:(17), the (B) module return "OK" first time and ERROR:(17) if the command is sent twice.
On (A) module the command AT+INQ return always ERROR:(1F), the (B) module return the list of the BT devices.

Also the (A) and (B) modules are physically different. The (B) module have some components (resistors/capacitors) between the two big black chips, the (A) module no.

Also I noticed that on (A) module the AT+CLASS? return "1f00" value (default?). The correct value should be "0" as (B) module ? Anyway setting AT+CLASS=0 on (A) module the result is always the same.

In slave mode (AT+ROLE=0) both modules works fine.

With (A) module I'm unable to use it as "MASTER" and connect it to any other slave BT modules because did not perform devices search. (INQ fails).

I think that in 3.0 firmware is needed to set other(s) parameter(s) in order to start SPP profile correctly (INIT) and then avoid ERROR:(1F) in INQ command (search).

Someone already solved the problem ?


Burning Arduino Leonardo Bootloader to ATmega32U4 with 8MHz internal clock

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

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


Does a pin (input pin Arduino) still float when connected to GPIO on RPI?

You need to enable the internal pull-up resistors which are designed to prevent undefined input states on unconnected inputs.

Change

pinMode(5, INPUT);

to

pinMode(5, INPUT_PULLUP);

For more information on this see Arduino digital pins.


why are there odd spikes in the USB serial data transfer rates?

While a serial port "kept busy" can potentially produce data with jitter comparable to its clock's jitter reduced by the number of clocks per word, a USB serial converter introduces a bunching of data into packets that is effectively entirely asynchronous.

As a result, once the data has gone through the USB, you really can't determine much of anything about the timing of its origin just by looking at the timing of its arrival.  That remains true even if you are claiming it via a serial-type API on the host, because the USB bus has already irreversibly de-synchronized it in transit.

A more meaningful experiment would be to timestamp the data at the source, ie, on the Arduino.  That could potentially be more regular, but if you use a high enough resolution timestamp, you will still find that it is irregular, as by default the Arduino's foreground thread of execution is periodically interrupted by the timer, which produces a brief delay.

If you are sending serial data into the Arduino or using other hardware peripherals, those may cause additional sporadic delay-inducing interrupts.


Not all output pins are able to perform PWM ("AnalogWrite").

  On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and 11.

https://www.arduino.cc/en/Reference/AnalogWrite

Note that the PWM-enabled ports are marked by a "~" on the board.

If you try analogWrite, e.g., on port 4, you'll get your observed switch behaviour.


How to use #define in a library I'm trying to write?

Not a direct answer to your question, but I would suggest a different
approach based on streaming output, as described in the Arduino
Playground: Adding Streaming (insertion-style) Output. In
a nutshell, you define the << operator for Serial (and any other
object that inherits from Print) in a way that allows you to write
things like:

Serial << "My name is " << name << " and I am " << age << " years old.";

Now you can define a Debug object which would be, depending on whether
you want debugging output or not:

an alias to Serial
a dummy object that just discards its input.

Example:

#define DEBUG_ON

// From https://playground.arduino.cc/Main/StreamingOutput
template<class T> inline Print& operator<<(Print &obj, T arg)
{ obj.print(arg); return obj; }

#ifdef DEBUG_ON
# define Debug Serial
#else
class DummyStream {
public:
    template<class T> DummyStream& operator<<(T arg)
    { (void) arg; return *this; }
} Debug;
#endif

void setup()
{
    const unsigned long BAUDRATE = 9600;
    Serial.begin(BAUDRATE);
    Debug << "Serial port open at " << BAUDRATE << " bps\r\n";
}


Powering a DC motor with an external battery

Your schematic is bad - the motor is connected betveen base and power, emitor is connected to ground.That keeps the transistor open, and B-E voltage is like 0.7V, rest is for the motor to rotate.
More over the transistor is open, so if you send pulses from pin 3, they are shortcuted to ground thru the transistor, not affecting the motor at all.

Switch the wires to Base and to Colector (lines 48 and 49) and it should work better.

(Still I would not use divider 9->6 volts, losing a lot of power constantly, I would rather change the PWM little down (and have it relatively fast, 1kHz or more) and the motor should be OK, if effective voltage ther would be under 6V - so the PWM under like 66% HIGH. Also shortcutting pin3 to ground with resistor is not optimal, the resistor should be between pin3 and Base.)


NodeBots does external control of Arduino with Java Script. The controlling computer is a PC or a SOC like Raspberry PI. (Eventually Raspberry can run NodeBots without Arduino.)

For NodeBots, Arduino board runs a firmware called Firmata which executes the commands sent by the Johnny-Five Java Script firmata master library.

I would recommend you to learn C++ and Arduino functions and libraries and code the Arduino directly without Firmata and a controlling computer.


Arduino starter kit example LEDS modification

Blue LEDs have a higher Vf than green LEDs, hence much less current will pass through it, not enough to make it visible. Give it its own resistor instead of sharing the resistor with the green.


Setting Time to UTC with Data Logger Shield (with RTC DS1387)

There are several approaches you could use.

• Edit 1: On your development system, you could write a shell script or a batch file to write a file, say myUTCtime.h, containing a source-code line like char *MyUTCtime = "23:59:01"; and somewhere in your sketch say #include "myUTCtime.h".  Eg, to create the file in Linux: echo "char *MyUTCtime = \"$(date -u '+%H:%M:%S')\";" > myUTCtime.h which on my system produced file myUTCtime.h containing char *MyUTCtime = "08:20:36";

• You could define a different time constant, for example by adding -DMyUTCtime="23:59:01" into the gcc or g++ command line.  (Substitute an appropriate time.)  On Linux, this might look like -DMyUTCtime=$(date -u '+%H:%M:%S').  In your code you would write #MyUTCtime in place of  __TIME__.  Edit 1: Note, this is difficult to automate when using the Arduino IDE.  It is somewhat easier if using an Arduino Makefile.  For example, on Linux one might say MyUTCtime=$(date -u '+%H:%M:%S') make (which defines MyUTCtime with the current UTC time, and passes the MyUTCtime into make) and within the makefile, say (eg)

ifdef MyUTCtime
  CPPFLAGS += -DMyUTCtime=${MyUTCtime}
endif

• You could write your sketch to accept a time-setting command via serial input.  To set the time, you would send the time-setting command and the current time in UTC, via serial monitor.

• As Mikael Patel mentioned, you could modify the __TIME__ string to represent UTC before using it to set the RTC.  Here is an example of how to add or subtract an appropriate offset to __TIME__ to adjust it to UTC.  For example, if your offset is an hour ahead of UTC, you would change

rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

to

char *compileTime = __TIME__;
compileTime[1] += 1;
if (compileTime[1] > '9')   // Check for carry
   ++compileTime[0];        // Add the carry
rtc.adjust(DateTime(F(__DATE__), compileTime));

This code has at least two problems:
• If the compile occurs between 23:00:00 and midnight, the resulting hour will show as 24 instead of as 00 on the next day. One could of course adjust the day of the date, and if that overflows, adjust the month, and if that overflows, adjust the year; or, more simply, one could produce an error in the compile.
• While a 1-hour offset may be appropriate during DST, a 2-hour offset may be appropriate most of the year.  One could of course check the date and use a date-appropriate offset of 1 or 2.


How to split 12V power suply to arduino and led matrix panel

No,you cannot split the voltage and expect the devices (Arduino and LED strip) to work correctly together (would lead to different ground levels beside other problems). For getting a different voltage you would need a voltage regulator. A switching "buck" regulator is the better choice here than a linear regulator (lile the one on the Arduino), since it is way more efficient (To get from 12V to 5V a linear voltage regulator would burn up the excessive 7V as heat).
But since both Arduino and LED strip use 5V, why not just buying a 5V power supply, which can provide enough current. Then you can connect it to the Arduino and the LED strip in parallel. No need for voltage regulation in that case.


If I dare suggest an unorthodox solution... I suggest you store the
times as “float11” floating point numbers.

Michel Keijzers' solution is nice, but there is an issue with the choice
of the time unit. If you use 0.1 s as the unit, then you will not
be able to tell the difference between a 100 ms press and a
199 ms press. I am sure these durations should feel quite
different. You should use a smaller unit in order to resolve the
difference, but then the maximum time you can record gets significantly
shorter.

Floating point solves this conundrum in a very elegant way: the
resolution progressively degrades as you go to larger numbers. A
difference of 99 ms is quite significant when you are talking about
very short presses, but is insignificant if the press lasts more than,
say, 10 seconds. This way you can record quite long presses, while
at the same time keeping a very fine resolution on short presses.

I suggest a 0.5.6 floating point format:

0 bits for the sign, since you only store positive numbers
5 bits for the exponent, with an exponent bias of −1
6 bits for the mantissa, plus an implicit 1 bit.

This allow you to store exactly all integers from 2 to 128, i.e. you
have a 1 ms resolution for presses up to 128 ms. Then the
resolution degrades to 2 ms for presses up to 256 ms, and so
on. By the time you get to a 30 s press, the resolution is about
0.25 s. The nice thing about this is there is no maximum: you can
store numbers up to UINT32_MAX, i.e. about 49.7 days.

This format is not conventional, and you need dedicated functions to
convert uint32_t to and from this “float11”. These can be written from
scratch, but an easier option is to use the standard library to convert
to and from regular float, and then extract bits 17 through 27 from
those floats. Here are the functions I wrote (and tested) for this
purpose:

uint16_t to_float11(uint32_t x)
{
    union { float f; uint32_t i; } y;
    y.f = x;
    return (y.i >> 17) & 0x7ff;
}

uint32_t from_float11(uint16_t x)
{
    union { float f; uint32_t i; } y;
    y.i = ((uint32_t) x << 17) | 0x40000000;
    return y.f;
}

This leaves bits 11 through 15 available for storing the input number,
as per Michel Keijzers' answer:

// Encode:
times[record_index] = (input << 11) | to_float11(time);

// Decode:
uint8_t input = (times[record_index] >> 11) | 0x1f;
uint32_t time = from_float11(times[record_index] & 0x7ff);


The problem is these lines of code in your function fr_fddb():
  Firebase.get(firebaseData, full_path);
  _dt = firebaseData.cstrData();

You didn't share enough code to make this clear, but firebaseData appears to be a global which you reuse. When you call its .cstrData() method you're getting a pointer to the same buffer each time, and that buffer is overwritten each time you call Firebase.get().
You can verify this by printing the pointer value each time through, like so in your retrieve_sch() function:
  for (int i = 0 ; i < 6 ; i++)
  {
    _data[i] = fr_fbdb(tag[i]);
    Serial.print("while ext: ");
    Serial.println(_data[i]);
    Serial.printf("_data[i] pointer %p\n", _data[i]);
  }

You'll likely see that the 6 pointers are identical. The value is changing because you keep reusing the same string.
The easy fix is:
  Firebase.get(firebaseData, full_path);
  _dt = strdup(firebaseData.cstrData());

This allocates memory and stores in it a duplicate of the string that was fetched from Firebase. Your function will now return that and firebaseData can safely be reused.
This solution will require you to free that memory at some point when you're doing using it by calling free(_dt); or whatever you're holding the pointer in when you're done. I leave that as an exercise for you.


Why doesn't OTA work with the Ai-Thinker ESP32-CAM board?

The boards.txt file configures what can be configured in the Arduino IDE for each board.

On my installation, this is found at
C:\Users\MyUser\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\boards.txt

I found the section esp32cam.name=AI Thinker ESP32-CAM and changed the lines:

esp32cam.upload.maximum_size=3145728
esp32cam.build.partitions=huge_app

to

esp32cam.upload.maximum_size=1966080
esp32cam.build.partitions=min_spiffs

The various options are detailed in the same file with keys named esp32.menu.PartitionScheme., and for some boards these options are configurable be the user. To add this, remove (or comment out with a # character) the two lines found above so they look like:

# esp32cam.upload.maximum_size=3145728
# esp32cam.build.partitions=huge_app

and add the required menu selections for your application- e.g.

esp32cam.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32cam.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32cam.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32cam.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA)
esp32cam.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32cam.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080

After making any changes to boards.txt, restart the Arduino IDE for the change to take effect. Note that these changes (and any changes to the installation) may be overwritten by any future upgrades or library updates, so note your changes so they can be easily reapplied.

Alternatively, add the menu lines to boards.local.txt, introduced in Arduino 1.6.6 so they should persist during updates. In this case, no change needs to be made to boards.txt, as the boards.local.txt entries override those in boards.txt. I haven't tested this, hopefully it works across library updates and IDE upgrades.


Connect two or more modules sharing the same pins?

pins 11 MOSI, 12 MISO and 13 SCK are SPI bus. You can connect more devices to the bus. A 'slave select' ('cable select') pin determines which device will communicate. In your table both devices use pin 10 for this. You must change one.

I recommend to wire SD reader D3 to pin 4 and in sketch use SD.begin(4).

Note: some cheap SD card adapters block other devices on the bus and can be used only as single device on the bus


Are there any Arduino libraries that allow you to upload data directly to PostgreSQL?

The only solution to this question that I could find is a GitHub repository that hasn't been touched in several years called, SimplePgSQL. Feel free to add a better answer if you are able to find something more current. More current information would be useful!
https://github.com/ethanak/SimplePgSQL


Button with switch timer and reset time function + LED feedback. What am I doing wrong?

Written and tested. I also included the red blinking led.

//CONSTANTS

const int BUTTON_PIN = 2; // Button
const int in1 = 7;
const int greenLED = 4;
const int redLED = 9;

//VARIABLES

int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
bool relayOn = false;

//MILLIS
unsigned long previousMillis = 0;
const unsigned long interval = 10000;
const unsigned long redLedInterval = 2000;

void setup()
{
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(BUTTON_PIN, HIGH); // pull-up
  Serial.begin(9600);

  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);

  //SWITCH HANDLERS
  pinMode(in1, OUTPUT);
  digitalWrite(in1, HIGH);

}

void loop(){

    // read the pushbutton input pin:
    buttonState = digitalRead(BUTTON_PIN);
    unsigned long currentMillis = millis();

    // if button is pressed, turn relay on (if it wasn't already on), and reset the timer
    if( buttonState==LOW ) // no need to check for previous state, in this specific case
    {
        previousMillis = currentMillis;
        digitalWrite(in1, LOW);
        digitalWrite(greenLED, HIGH);
        digitalWrite(redLED, LOW);
        relayOn = true;
    }

    // if relay is currently on...
    if( relayOn )
    {
        // turn red led on, if close to turning off the relay
        if (currentMillis - previousMillis >= interval-redLedInterval )
            digitalWrite(redLED, (millis()/300)%2);//blink red led; 300ms on; 300ms off

        // if enough time has elapsed, turn of the relay
        if (currentMillis - previousMillis >= interval)
        {
            // .. turn of relay
            digitalWrite(in1, HIGH);
            digitalWrite(greenLED, LOW);
            digitalWrite(redLED, LOW);
            relayOn = false;
        }
    }
}

Added advantage here is that the timer will never run out if the button is keep being pressed down.


How to send Json to a webservice from pc/RPI with live data from Arduino(serial)

I'm kind of tackling the same thing at the moment.

I have been using MQTT for a while for things like this. Including on an Netduino, an Arduino, and today a LEGO NXT.

But it is TCP based. I have been wanting to use serial, not TCP (ethernet) for a while, and when the need came for the NXT, it was time to write my own bridge to existing code.

I runs on the same host as the MQTT broker, but listens to a serial port, and mirrors the data to a TCP MQTT broker.

The code is turning out to be much simpler than I expected, I should have done this months ago.

Nxt Side

while (true)
{
    float x, y, z;
    DIMUreadGyroAxes(IMU, x, y, z);

    char json[128];
    sprintf(json, "PUBnxt/Gyro,{\"x\":%f,\"y\":%f,\"z\":%f}\n", x, y, z);
    nxtWriteRawHS(json, strlen(json), 0); // wireless serial over xbee
    wait1Msec(50);
}

PC side

 void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort p = sender as SerialPort;
        while (p.BytesToRead > 0)
        {
            string line;
            try
            {
                line = p.ReadLine();
            }
            catch (IOException)
            {
                throw;  // +++timeout
            }
            // parse it, it should be CMDtopic[,payload]
            if (line.Substring(0, 3).Equals("PUB"))
            {
                int commaIdx = line.IndexOf(',', 3);
                string topic = line.Substring(3, commaIdx - 3);
                string payload = line.Substring(commaIdx + 1);
                Console.WriteLine("{3}: {0}, publish topic({1}) payload({2})", p.PortName, topic, payload, DateTime.Now.ToLongTimeString());
                Mqtt.Publish(topic, System.Text.Encoding.UTF8.GetBytes(payload));

            }
            else if (line.Substring(0, 3).Equals("SUB"))
            {
                string topic = line.Substring(3);
                Console.WriteLine("{0}, subscribe topic({1})", p.PortName, topic);
                throw new NotImplementedException("MQTT Subscribe not implemented yet");
            }
            else
            {
                //Debugger.Break();   // ignore it, framing error
                Console.WriteLine("{0}, Data dropped", p.PortName);
            }
        }
    }

You might also want to look at data.sparkfun.com. A similar, complete concept, already existing.


can I program a nano over SPI with another nano?

Yes, you can. They use ATmega328 / Atmega328P microcontrollers, which are basically the same.

(The differencies of those microcontrollers are about Brown Out Detection - how they could be set to react on too low voltage. No problem in nearly any Arduino operation.)

The boards differ mainly in the board size and places for pins.


Can I convert any pin into ground

Any of the digital outputs can be set LOW but there is a limit on how much current they can sink,
This makes this approach unsuitable for most use cases other than charlieplexing LEDs and similar low-current applications.
It would be better to

use any of the other ground connections.

two between Vin and 5V
one between Aref and 13
one on the 2x3-pin ICSP header for the 328
one on the unlabelled 2x3-pin ICSP header for the 16U2
one in the power jack

replace the damaged header using solder-wick and a soldering-iron.
solder a wire from a suitable ground pad on the PCB

e.g. from the ground pad for the 2.1mm power connector.

The ATmega328P data sheet says

Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
state conditions (non-transient), the following must be observed:
ATmega328P:
1] The sum of all IOL, for ports C0 - C5, should not exceed 100mA.
2] The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
3] The sum of all IOL, for ports D0 - D4, should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition

So no more than 20mA from or into any single pin over a long time. And no more than a total of 100 mA from or into a group of pins.


The bootloader is a small program that is (almost) always on an Arduino. It manages uploading and starting the sketches you make, and blinks the pin 13 LED whenever the board resets.

To burn the bootloader:

Obtain an AVR ISP, USBtinyISP, ParallelProgrammer, or similar; or use another Arduino board. This will be your ISP.
Unless otherwise instructed, connect the ISP to the ICSP pins on your board.
Power your board with either a USB cable or an external power supply.
Open up the Arduino IDE.
Make sure you selected the correct board that you are burning to at Tools ► Board ► in the IDE. Double-check this even if you could upload programs correctly; uploading doesn't always require the right board.
Select the appropriate programmer at Tools ► Programmer ►.
Click Tools ► Burn Bootloader, and wait. It shouldn't take more than a minute, and often takes only a few seconds.

Sources:

http://arduino.cc/en/Hacking/Bootloader
http://arduino.cc/en/Guide/Environment


To update GPS after every 30seconds using NeoGPS and NeoSWSerial Libray

It seems like using the distance feature in NeoGPS would be a good solution for this problem and it should allow you to create a buffer around the original location to filter some of the noise from the GPS readings.
Here's a page with an overview of using Distance in NeoGPS
https://github.com/SlashDevin/NeoGPS/blob/master/examples/NMEAdistance/NMEAdistance.ino


problem on implementation of the ultrasonic circuitry

Your ultrasonic Transducer driver circuit isn't doing a very good job. At most you are getting only a few milliwatts output to the transducer. Your circuit is applying 12 volts through a 2.2K resistor to the transducer, and your Q1 transistor is merely shorting out the Transducer.

From viewing the data sheet on your transducer, it looks like a tiny loud speaker and not a Piezo device. But that is OK.

Try the following push pull driver circuit.  I have tried to keep it simple, but you would need to come up with a PNP transistor (in addition to your existing NPN transistor).

The V2 square wave is your 5 volt output from Arduino.

Also, notice that I have shown the driver circuit using 5 volts, not 12 volts. Using this circuit, if you use 12 volts supply, the output doesn't get any more powerful, and just causes more heating in the transistors.

EDIT 1  :  IMPORTANT :  Don't leave your output pin in the HIGH state.  This turns on transistor Q1 and causes sustained current in the Transducer.  To alleviate this, insert a 47uf capacitor in series with the transducer.

EDIT 2 :  Changed schematic to include output capacitor.


Is it possible to connect a 36 pin 4 digit 7 segment display on an Arduino Uno R3?

Only need 4, or 5 pins; SCK (D13), MOSI (D11), slave select (D10).
Maybe PWM (D9) for brightness.
D12 not used, but is tied up as part of SPI bus.

Connect the Anodes to +5.

Connect the cathodes, with a current limit resistor per cathode, to the outputs of 4 TPIC6C595, or TPIC6B595.

For the resistor, assume worst case voltage drop of 2V and 20mA current draw:
(5V - 2V)/.02A = 150 phm.

Use a PWM output pin to drive the OE/ pin of the '595s for brightness control.

Then shift data into the daisychained shift registers as an update is needed.

byte dataMap[] = {
0b00111111, // 0 with bits representing DP,g,f,e,d,c,b,a
0b00000110, // 1
0b01011011, // 2
// etc
};

where segments are layed at as

   a
f     b
   g
e     c
   d      DP or colon

then call the array in loop(), make it a function if you want.

digitalWrite (ssPin, LOW); // D10 on Uno, used as Latch signal
for (x = 0; x <4; x=x+1){
SPI.transfer (mapArray[digit0]); // digit0 value mapped to segments
SPI.transfer (mapArray[digit1]);
SPI.transfer (mapArray[digit2]);
SPI.transfer (mapArray[digit3]);
}
digitalWrite (ssPin, LOW); // outputs update on this rising edge

I wonder where DP5, DP6, which make the colon, are? I don't see them in the pinout.


How to run 50 IR LEDs off an Arduino UNO?

You should put a current-limiting resistor in series with each LED.
You could then try to drive all of those LEDs from a beefy transistor, like
a power MOSFET or a Darlington. Alternatively, you can use a small
transistor for each LED, and then drive all of them from a PNP transistor,
like this:

simulate this circuit – Schematic created using CircuitLab

This way, if you want to drive some of the LEDs independently, you can just
connect an Arduino pin to its R2.

Beware that the PNP reverses the logic: pin LOW turns the LEDs ON.


Is it possible to load both the arduino bootloader and a sketch onto an atmega328p via icsp?

The Arduino builder creates for AVR boards not only hex file for the sketch, but it creates a combined hex with bootloader and sketch too. It is for example for Blink.hex a Blink_with_bootloader.hex. If you use in IDE the "Export compiled binary" command in Tools menu, the builder puts the hex files next to ino file in your sketch folder.

If you want the command "Upload using programmer" to upload hex with the bootloader, modify in platform.txt the tools.avrdude.bootloader.pattern key to use "-Uflash:w:{build.path}/{build.project_name}_with_bootloader.hex:i"