message:
How to make battery last for months?

I have a simple circuit: detect that a person is walking towards the circuit (with HC-SR04), measure distance, light diodes (a wave effect) according to that distance – the closer, the faster the led wave.

When no person detected, sleep longer:

    LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);

When person detected, sleep shorter (so that diodes can be often turned on/off):

    LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);

Without LowPower use – `delay()` used instead – the current taken is `15 mA`. This is with diodes off. After using LowPower – it's still `~15 mA`. This is very disappointing. I've expected the battery to last at least for 3 months, but it (9V) was drained within hours. Am I missing something?

Also a curiosity: the execution was fully blocking itself on LowPower calls, I've had to add short `delay()` before the calls, then they don't block execution.

    #include <LowPower.h>
    #include <NewPing.h>

    #define trigPin 13
    #define echoPin 12

    NewPing sonar(trigPin, echoPin, 250);

    // Defines speed of LEDs traversal
    int delayTime = 40;

    // Current led
    int currentLED = 0;

    // Direction of travel over LEDs
    int dir = 1;

    // Stores the last time LEDs were changed
    unsigned long timeChanged = 0;

    // Stores the last time sensor was read
    unsigned long timeOfQuery = 0;

    // LEDs
    byte ledPin[] = { 4, 5, 6, 7, 8, 9, 10, 11 };

    // Stores if any diodes are on
    int leds_used = 1;

    // Stores if wave is active
    int off = 1;

    // 5 last distances, circular buffer;
    long distances[7] = { 400, 400, 400, 400, 400, 400, 400 }, currentDistance = 0;

    // Last chosen distance
    long distance = 400;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      for (int x = 0; x < 8; x++) {
        pinMode(ledPin[x], OUTPUT);
      }
      timeChanged = millis();
    }

    void loop() {
      long duration, cur_time, cm;

      cur_time = millis();

      /* Read distance when off, or when some time passed */
      if (off || (!off && (cur_time - timeOfQuery) > 100)) {
        timeOfQuery = cur_time;

        cm = sonar.ping_cm();
        if ( cm == 0 ) {
          cm = 400;
        }

        distances[(++currentDistance) % 7] = cm;
        // At least 1 proper distance?
        off = 1;
        for (int i = 0; i < 7; i++) {
          if (distances[i] <= 200) {
            off = 0;
            // Remember minimum distance
            if (distances[i] < distance) {
              distance = distances[i];

            }
          }
        }
        delayTime = distance;
      }

      if (!off) {
        // Check whether it has been long enough
        if ((cur_time - timeChanged) > delayTime) {

          // Turn off all of the LEDs
          for (int x = 0; x < 8; x++) {
            digitalWrite(ledPin[x], LOW);
          }

          // Turn on the current LED
          digitalWrite(ledPin[currentLED], HIGH);

          // Mark that diodes are being used
          leds_used = 1;

          // Increment by the direction value
          currentLED += dir;

          // If we are at the end of a row, change direction
          if (currentLED == 7) {
            dir = -1;
          }
          if (currentLED == 0) {
            dir = 1;
          }

          // Store the current time as the time we last changed LEDs
          timeChanged = cur_time;
        }

        // Shorter delay when sleeping
        delay(5);
        LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);
        //delay(50);
      } else {
        if (leds_used) {
          // Turn off all of the LEDs
          for (int x = 0; x < 8; x++) {
            digitalWrite(ledPin[x], LOW);
          }
          currentLED = 0;
          dir = 1;
          leds_used = 0;

          // Store the current time as the time we last changed LEDs
          timeChanged = cur_time;
        }

        // Longer delay when sleeping
        delay(10);
        LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
        //delay(200);
      }

      /*
        if (distance >= 200 || distance <= 0) {
          Serial.print(distance);
          Serial.println(" Out of range");
        }
        else {
          Serial.print(distance);
          Serial.println(" cm");
        }
      */
    }

**Update**: The board is Arduino UNO.

body:
The Arduino UNO always consumes current mainly because:

- it has 2 MCU, the ATmega328 which you can power down, and an ATmega16u2 for USB communication which is never powered down.
- in addition, the voltage regulator is permanently leaking some current

To be honest, I am surprised your UNO consumes *only* 15mA, on my boards, it is rather near 40-50mA.

Also, a 9V battery is probably the battery with the smallest charge capacity.

I would suggest you:

1. work on a breadboard with just the ATmega328,
2. power it with two 1.5V batteries (AA or AAA)
3. and run @8MHz

That should already reduce current consumption.

You may even try smaller MCU (e.g. ATtiny84A) which consumes less current than the ATmega328 in the same conditions.

Finally, I **highly recommend** [Nick Gammon's blog on that topic][1]. It includes many good tricks to help you with current consumption.

  [1]: http://www.gammon.com.au/power


sender: user

message:
How to send Multiple decoded IR signals in one script

My final goal is to use my Arduino microcontroller as an "automatic remote". For now I would like to know how to send decoded NEC protocols one after another in a script.

 I am using the Nano V 3.0 with a IR led I salvaged from an old remote. I used a VS838 and a 338R IR receiving module to decode the signals, both work 100%

I know how to send one protocol in a loop.

e.g

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
     for (int i = 0; i < 2; i++) {
      irsend.sendNEC(0x10676897, 32);
      delay(40);
     }
     delay(5000); //5 second delay between each signal burst
    }

I also know how to send the same protocol repetitively.

(Although it won't work in the loop I reckon it'll work in the final script)

e.g

    #include <IRremote.h>

    IRsend irsend;

    void setup()
    {
    }

    void loop() {
        for (int i = 0; i < 2; i++) {
            irsend.sendNEC(0xFFFFFFFF, 32);
            delay(40);
        }
        delay(5000); //5 second delay between each signal burst
    }

However, I would like to include `106722DD`, `10676897` ,`10678877` and send them in one single C++ Script.

I was thinking something like calling each script through a loop might suffice but I have no idea how to do it in C++

Any help will be appreciated.

sender: assistant

body:
I'm not 100% certain what you are asking, so sorry if there is superfluous info in here.

Given that:

    void loop() {
        for (int i = 0; i < 2; i++) {
            irsend.sendNEC(0x10676897, 32);
            delay(40);
        }
        delay(5000); //5 second delay between each signal burst
    }

Sends a single command twice as one burst I think what you want to do is this:

    void loop() {
        for (int i = 0; i < 2; i++) {
            irsend.sendNEC(106722DD, 32);
            delay(40);
            irsend.sendNEC(10676897, 32);
            delay(40);
            irsend.sendNEC(10678877, 32);
            delay(40);
        }
        delay(5000); //5 second delay between each signal burst
    }

If that works it could be generalised into:

    // New function to send 'items' codes which are held in the array 'data'
    void sendMulti (const uint8_t& items, const uint32_t* data)
    {
        for (int i = 0; i < 2; i++)
        {
            for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex)
            {
                irsend.sendNEC(data[itemIndex], 32);
                delay(40);
            }
        }
        delay(5000); //5 second delay between each signal burst
    }

    void loop () {
        static const uint8_t MaxItems = 3;
        uint32_t  data[MaxItems] = {106722DD, 10676897, 10678877};

        sendMulti(MaxItems, data);
    }

Then you could move onto reading the codes from serial or a network, etc.


message:
Arduino and Raspberry Pi - initiate I2C communication as slave

I would like to interconnect Raspberry Pi and Arduino over I2C.

RPi will act as MASTER while Arduino is SLAVE.

I understand that I2C is designed that only master can send messages to slaves and then wait for responses.

I have sensor connected to Arduino, Arduino check periodically sensor value. My intent is, when sensor value exceed defined limit, inform RPi - send message to it. I want RPi as MASTER, because it also can query Arduino anytime. Can I start communication as SLAVE device?

Is it possible somehow? Do I need to use different bus than I2C?

body:
You need to use a separate signalling method to alert the Pi that a sensor value is ready to be collected.

This is usually done using an interrupt signal. Your Arduino changes the state of a GPIO pin which is connected to a GPIO pin (through suitable logic level translation as necessary) on the Pi. When the Pi sees that pin change state it requests the data from the Arduino.

It is most common to have the transition from HIGH to LOW as an interrupt signal (aka Active Low) since that allows a simple wired-OR arrangement (open drain GPIOs with a pullup resistor) to allow more than one device to raise the same interrupt.


body:
Yes you can!

The new pigpio library allows the Pi to act as a slave so all devices are equal.

Before this recent release, the Pi was always a master and had to poll the others, interrupting them.

But now you can let the other devices work on their own time schedules without the interrupts.

[Here is where you get it][1]

  [1]: http://abyz.co.uk/rpi/pigpio/


message:
Lcd display shield, no characters

So, I've been trying to make an [Lcd display shield][1] I got from ebay to work with arduino. Using this very simple code:

    #include <LiquidCrystal.h>

    #define RSPin 8
    #define EnablePin 9
    #define DS4 4
    #define DS5 5
    #define DS6 6
    #define DS7 7

    #define LCDColumns 16
    #define LCDRows 2

    LiquidCrystal lcd(RSPin, EnablePin,DS4,DS5,DS6,DS7);

    void setup()
    {
      lcd.begin(LCDColumns, LCDRows); //Configure the LCD
      lcd.setCursor(0,0);
      lcd.print("Hello, World!");
    }

    void loop()
    {

    }

  [1]: http://www.hobbytronics.co.uk/image/cache/data/dealextreme/arduino-lcd-keyboard-shield-500x500.jpg

Actually I've tried several simple examples, checked pins physically to make sure I'm using the right order, But no luck. backlight is on, no characters at all. Am I missing something? Or should just contact the seller to send another shield.

body: So, after some close inspection I noticed that the blue potentiometer wasnt soldered in correctly. Also, its needs to be turned quiet a lot to have some effect. Might replace it completely. But now it works!


message:
How do I write the codes in #define in an IR Receiver circuit?

So I'm trying to turn an ON LED OFF or an OFF LED ON using a TV Remote. In the #define line, I write the hex code received from pressing the designated button on the TV remote. However, during compilation, an error saying `unable to find numeric literal operator 'operator""DE74847'` appears. I've scoured the web and can't come up with a solution.

    #include <IRremote.h>
    #include <IRremoteInt.h>
    int ledPin = 13;
    int IRPin = 3;

    #define code1 0575

    IRrecv irrecv(IRPin);
    decode_results results;
    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn();
      pinMode(ledPin, OUTPUT);
    }
    void loop()
    {
      if (irrecv.decode(&results))
      {
      unsigned int value = results.value;
      int ledState  = digitalRead(ledPin);
      switch(value)
      {
        case code1:
        if (ledState = HIGH)
        {
          digitalWrite(ledPin, LOW);
        }
        else
        {
          digitalWrite(ledPin, HIGH);
        }
        break;
      }
      }
      else
      {
        digitalWrite (ledPin, LOW);
      }
       unsigned int value = results.value;
      Serial.println(value);
        irrecv.resume();
    }

Here's the code. Please help.

body:
Your problem is that you don't know how to form hexadecimal numbers.

In your code (in future, if you have an error in the code please post the code that is causing the error, not something else entirely - it makes it nigh on impossible for people without my psychic abilities to answer your question) you have defined a macro containing what you think is a hexadecimal number. In fact it's just a random string of characters and the compiler doesn't know what to make of it:

    #define code1 DE74847

So in your switch construct, when `code1` gets replaced with the content of the macro, you end up with:

    switch (value) {
        case DE74847:
            ....

The compiler has no idea what a DE74847 is.

Numbers other than decimal numbers (0-9 and the decimal point) are identified by the use of a prefix:

* `0b...` is binary
* `0` is octal (in your completely different code you have the number 0575, which is actually octal, and represents the decimal value 381)
* `0x` is hexadecimal.

So adding `0x` to the start of your hexadecimal value will tell the compiler to treat it as hexadecimal:

    #define code1 0xDE74847


message:
Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64

I have tried to install many versions of IDE, but non of them has started successfully. There is just the logo of the program shows up and then nothing happens.
My laptop: Toshiba Satellite C50-A630
The releases I have installed: 1.6.12 , 1.6.13, 1.0.6

body: I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.


message:
How does an 8bit MCU make use of data-types over 8bits?

how does an 8bit MCU handle 16bit output?
How does an 8bit MCU store values higher than 8bits?
I am using an attiny, on an adafruit trinket. and other 8bit MCUs.
http://www.atmel.com/devices/attiny85.aspx
I was doing some things with uint32_t datatypes, when it hit me, that it would seem like uint32_t would be an incompatible datatype. Even 2Byte data type like int seems peculiar. "[int stores a 16-bit (2-byte) value][1]"
considering the MCU is 8bit.

I saw this link, that sounded like it would have more info, but its pages are incomplete. http://playground.arduino.cc/Code/DatatypePractices

So how does that work?
How does an 8bit MCU make use of data-types over 8bits?

  [1]: https://www.arduino.cc/en/Reference/Int

body:
The basic answer is that the processor does math in 8-bit chunks, so it takes more instructions than it would on a 32-bit processor.

A good answer is found in [EE.SE][1]

  [1]: https://electronics.stackexchange.com/questions/166218/how-can-a-8-bit-cpu-calculate-big-numbers


body:
Actually a 1-bit MCU could be used to execute code (e.g. C/C++) with N-bit numbers. Not very fast as it will require *O(N)* operations for addition and subtraction.

To better understand this for the 8-bit AVR MCU used in Arduino I recommend reading the [Instruction Set Description Manual][1], [AVR/GCC Wiki][2] and assembler code listings for some sketches. This will reveal the secret(s) behind this "alien technology/magic".

Cheers!

  [1]: http://www.atmel.com/images/Atmel-0856-AVR-Instruction-Set-Manual.pdf
  [2]: https://gcc.gnu.org/wiki/avr-gcc


message:
RF signal boosting

I'm working on a quadcopter project. The quadcopter will be quite autonomous, but sometimes I'll need to send some messages to it. So I built a simple, one-way RF communication system based on two simple 433 MHz modules.

It works, but when the propellers of the quadcopter approach the take-off speed it begins having trouble in receiving the RF messages, and after a certain speed it stops working.

I suppose this is due to the electrical noise produced by the four little brushed motors. Yesterday I increased a little the transmitter's voltage, and that increased a little the minimum antenna-antenna distance with the motors on, but that is far from enough.

What else could I do to increase the transmitter's power?

Thanks in advance

Noè

P.S.: Here are my RF modules:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/LGFOC.jpg

body: I have been using RF modules for different projects that involves using motors. And I have never experienced something like that. Since the motors a significant quantity of current to take off, I recommend using another power supply for the electronic part of the drone and use the actual battery just for the motors.


body:
As has been mentioned adding an antenna to the "ANT" pin on the transmitter will help. You need to get the length right though, but it's easy to calculate.

Best is to use single-core insulated wire (0.6mm is a good choice).

To calculate the right length you first need to know your frequency. Then you convert that to the wavelength, and then cut your wire to a quarter of that length.

Wavelength is `c/f` where `c` is the speed of light (in m/s), and `f` is the frequency.

So for 433MHz you have a wavelength of (299792458/433000000) 0.69m.

A quarter of that is 0.173m (17.3cm), so cut your wire to that and solder it on.

For 315MHz the wavelength is (299,792,458/315000000) 0.95m, so an antenna length of 0.238m or 23.8cm.

This is known (unsurprisingly) as a *quarter wavelength antenna* and is the most efficient length for a simple wire antenna.

Whether it will be strong enough to penetrate the noise from the motors is anyone's guess.

You can also add small capacitors (0.1µF ceramic) across the terminals of the motor and between the terminals and the body, to absorb some of the EMI which may help to allow more signal through - [as shown here](https://electronics.stackexchange.com/questions/19517/why-connect-capacitors-to-motor-body).


message:
Custom ISR triggering function/value

Is there a way to write a custom function which would be the mode/reason to trigger an interrupt. I have an analog joystick connected to my arduino analog pin. It reads a value of 689 on one end and 0 on the other and around 480 in the center. I would like to trigger an interrupt based on these value changes i.e an interrupt when it  more then 600 and another when less then 10. None of the pre-defined modes RISING,HIGH,LOW,FALLING,CHANGE are working satisfactorily.

body:
No. Interrupts are hardware. You cannot "create" interrupts in software.

The closes there is to what you are after is the Analog Comparator (see section 27 of [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf)).

The analog comparator allows you to trigger an interrupt if a voltage is above (or below) a reference voltage which is up to you to provide.

For anything more complex you would need to use external comparators to trigger on different voltage levels which then trigger external INT pins on the ATMega.


body:
As Majenko already said, you cannot do that. But you can look for
alternative ways of achieving a similar end result. The real question
is: what are you trying to achieve? Interrupts may not be the best
answer.

I assume what you have in mind is a program roughly along these lines:

<!-- language-all: lang-c++ -->

    // Interrut handler called when input > 600.
    void handleHigh()
    {
        // ...
    }

    // Interrut handler called when input < 10.
    void handleLow()
    {
        // ...
    }

    void setup()
    {
        // Register the interrupt handlers.
        attachInterrupt(ANALOG0, handleHigh, MORE_THAN_600);
        attachInterrupt(ANALOG0, handleLow, LESS_THAN_10);
    }

    void loop()
    {
        doSomeStuff();
    }

Of course, that syntax for calling `attachInterrupt()` does not work, I
just made it up.

The most obvious alternative is to read the value through an analog
input in `loop()` and act accordingly:

    void loop()
    {
        // Check the analog input.
        int sample = analogRead(A0);
        if (sample > 600) handleHigh();
        if (sample < 10) handleLow();

        // Do the rest of the job.
        doSomeStuff();
    }

No need to use interrupts. The only drawback is that the latency of your
response to a change in the joystick position can be as long as the time
your program takes to run through `loop()`. This should normally not be
a problem: the joystick is a very slow mechanical device, and your loop
should take no more than a few milliseconds. If the loop if really too
slow, you are probably doing something wrong, like using `delay()`. You
should then _fix_ that problem rather than trying to work around it with
interrupts.

Just for completeness, there _is_ an interrupt-based solution. Assuming
you have no other analog input to read, you could configure the ADC to
_continously_ read the same input (say, A0) in the so called “free
running mode”, and trigger an interrupt on each reading. In the ISR, you
can then call one of your interrupt handlers if needed (if the sample you
get is outside [10, 600]). Here is how you can do it on an Arduino
Uno:

    void setup()
    {
        // Configure the ADC in "free running mode".
        ADMUX  = _BV(REFS0)  // ref = AVCC
               | 0;          // input channel = A0
        ADCSRB = 0;          // free running mode
        ADCSRA = _BV(ADEN)   // enable
               | _BV(ADSC)   // start conversion
               | _BV(ADATE)  // auto trigger enable
               | _BV(ADIF)   // clear interrupt flag
               | _BV(ADIE)   // interrupt enable
               | 7;          // prescaler = 128
    }

    // ADC interrupt service routine.
    // Called each time a conversion result is available.
    ISR(ADC_vect)
    {
        // Read the ADC.
        int sample = ADC;

        // Call the handlers if needed.
        if (sample > 600) handleHigh();
        if (sample < 10) handleLow();
    }

**Edit**: With the code above, the ISR runs every 104 µs. Then you
should make sure that your handlers take significantly less than that
time to complete. Otherwise they will consume 100% of the CPU power
whenever the joystick is in the range to trigger one of them. As a small
optimization, you could declare the handlers `static inline` in order to
avoid the overhead of a function call.


body:
Of course, you can make software interrupts on Arduino; it just costs a hardware pin. The following is a quote from the Atmel ATmega48A/PA/88A/PA/168A/PA/328/P datasheet:

"13. External Interrupts
The External Interrupts are triggered by the INT0 and INT1 pins or any of the PCINT23...0 pins. Observe that, if enabled, the interrupts will trigger even if the INT0 and INT1 or PCINT23...0 pins are configured as outputs. This feature provides a way of generating a software interrupt."

You set up an interrupt on the pin you select for the purpose, you set the pin as output, and then you trig your "software interrupt" by writing a value to the pin.


message:
Which library to choose? <Wire.h> or "Wire.h"?

I know that in C++, to include a library, you either put the library name in `<x>` or `"x"`. Now, I believe that this was because of a major change in the C++ language a some time ago.

Now, in Arduino, there are 2 types of `Wire` (I2C) library : `<Wire.h>` and `"Wire.h"`.

Which one is the right one?

I've seem people using both, and they both seem to work.

body:
http://en.cppreference.com/w/cpp/preprocessor/include

    #include <filename>

> The intent of this syntax is to search for the files under control of the implementation. Typical implementations search only standard include directories. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.

    #include "filename"

> The intent of this syntax is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides and, only if the file is not found, search the standard include directories as with (1).

So basically it's intent is to give some idea of where the file should be.
I, myself use "" for files that are inside the directory of my program. And <> for files or libraries that are in my path or other external locations.

----------

This question is also more related to programming in general as Arduino specific.

Also see:
https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename


body:
The proper distinction is exactly what paths are searched for the include files.

`<...>` searches the "system" paths, while `"..."` searches both the system an "local" paths.

From the GCC manual:

> **`-I dir`**
>
> Add the directory dir to the list of directories to be searched for header files.  Directories named by `-I` are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated .  If dir begins with `=`, then the `=` will be replaced by the sysroot prefix; see `--sysroot` and `-isysroot`.
>
> **`-iquote dir`**
>
> Search dir only for header files requested with `#include "file"`; they are not searched for `#include <file>`, before all directories specified by -I and before the standard system directories.  If dir begins with `=`, then the `=` will be replaced by the sysroot prefix; see `--sysroot` and `-isysroot`.

Note that the Arduino IDE only uses `-I`, so there is little to no distinction between `<...>` and `"..."`.

Commonly the main usage of the distinction is to use `<...>` to include system or library headers, and `"..."` to include headers that are part of the actual sketch / application, since the "current directory" is automatically added as a local include path.


message:
Why can't my .cpp file have a class of the same name?

I made a new Arduino IDE `project ABC`, and am given `ABC.ino`. Then I create a `XYZ.h` and `XYZ.cpp`.

---

`ABC.ino`:

    #include "XYZ.h"

    void setup() {}
    void loop() {}

`XYZ.h`:

    #ifndef XYZ
    #define XYZ

    #include "Arduino.h"

    class XYZ { };

    #endif

`XYZ.cpp`:

    #include "Arduino.h"
    #include "XYZ.h"

---

When I try to compile this, I get some error:

    In file included from sketch/XYZ.cpp:2:0:
    XYZ:8: error: abstract declarator '<anonymous class>' used as declaration
     };
     ^
    exit status 1
    abstract declarator '<anonymous class>' used as declaration

---

However, when I rename my class to something other than the file name, like `XYZa`, the compilation succeeds.

---

**Why can't I have the same name class as the file?**

I've done C++ projects (independent of Arduino) via `Xcode` and `nano`, and this has never been a problem.

body:
    #define XYZ
    ...
    class XYZ { };

After preprocessing, what do you think that ends up as?


body:
    #define XYZ

    class XYZ { };

The first line tells the "C preprocessor" (called before C and C++ compilers) to replace `XYZ` with nothing everywhere it happens, hence after preprocessing, and before compiling, that code becomes:

    #define XYZ

    class  { };

This is where C++ compiler complains. It has nothing to do with your file name.

Among C and C++ programmers, it is commonly admitted that header files should be protected by macros named after the file name **including the extension**:

    #ifndef XYZ_H
    #define XYZ_H

If you use this practice, you won't have this problem anymore.


message:
How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?

`MyProject.ino`:

    #include "MyClass.h"

    void setup()
    {
      Serial.begin(9600);
      // MyClass.MyStaticMethod();
      MyClass::MyStaticMethod();
    }

Both uncommented lines work, but the commented (when uncommented, of course) results in this error: `expected unqualified-id before '.' token`.

Now, I know this is because of the incorrect scope-resolution. Yet, how come `Serial` manages to call static functions without the need to use `::` to correction to scope-resolution.

**How come `MyClass.MyStaticMethod()` doesn't work, but `Serial.begin()` does?**

body:
`.` is used to call a method on a class *instance* whereas `::` is used to call a static method within a class itself.

There is no `Serial` class - `Serial` is merely an instance of the `HardwareSerial` class.

    #if defined(UBRRH) && defined(UBRRL)
      HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
    #else
      HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
    #endif

If you want to use `.` then you have to instantiate your class and not use a static method:

    class MyClass {
        static void myStaticMethod() {
        }
        void myMethod() {
        }
    };

    MyClass Fred;

    // ...

    Fred.myMethod();
    MyClass::myStaticMethod();


message:
Bootloader on Atmega328p overwrites whenever it gets programmed

[![enter image description here][1]][1]I built my first custom circuit board with an Atmel ATMega328p-AU the tqfp-32 form factor. I connected xtal1 and xtal2 to an external 16mhz crystal to 22pf caps tied to ground. It seems to work great, I load the Arduino Bootloader using AVRDude and an arduino as an isp. As soon as I load a sketch on using the ftdi it blows out the bootloader and I can't upload a new sketch until reloading the bootloader. The sketch works as expected, my board has an on board relay and an onboard mosfet I've programmed various blink patterns on both the mosfet and relay.I just don't want to have to reload the bootloader everytime I want to make a change, my sketch is an evolving piece of work and it's frustratinf to take these steps. So far I've tried changing the lock bits to 0x0F 0xEF 0xFF and 0X2F. I've tried various fuse bits, I've changed the signature 0x1e 0x95 0x14 to 0x1e 0x95 0x0F. Nothing seems to change the results, the only thing I've managed to do is one upload caused the chip to run at 8mhz instead of 16mhz, oops. That was easily fixed though. Please if someone can help that would be great, unfortunately the fuse bit calculators I have found don't have the 16mhz crystal as an option even though it's clearly functional.

In Summary

Sketches overwrite my bootloader and I want my bootloader locked but I can't find a solution after nearly a full day of googling and experimenting

  [1]: https://i.stack.imgur.com/eiAQd.png

body:
I suspect you aren't writing the fuses on the AVR correctly in some way (or at all?). Try using the "Tools > Burn Bootloader" functionality of the IDE itself (which will set the fuses as well as loading the flash). You have to make sure you pick your ISP programmer under tools as well for this to work (e.g. Arduino as ISP). See if that works any better for you.

As an aside, there are a variety of AVR online fuse calculators if you're not into reading the datasheet. For example, http://www.engbedded.com/fusecalc. I seem to remember some rumblings in recent history that full swing external crystal configurations wouldn't be supported in new silicon for the ATmega328p, but that's what I always used to pick, and I think it probably still works as a setting.

Honestly, though, the easiest thing to do is to run Arduino in verbose (check the boxes in Preferences) and borrow their avrdude commands that get displayed when you run Burn Bootloader.

**Continuations...**

If *that* (Burn Bootloader) doesn't work for you, we're going to need to see some schematics, and I'd be staring pretty hard at your reset sub-circuit and FTDI sub-circuit.

Arduino Uno bootloader wants you to talk to it at 115200 baud... see the [boards file][1].

What do you mean "My IDE doesn't hae a 328p UNO"? Download the latest Arduino from https://www.arduino.cc/en/Main/Software and choose Genuino Uno.

[![enter image description here][2]][2]

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/boards.txt#L47-L80
  [2]: https://i.stack.imgur.com/PQxmH.jpg


body:
Almost certainly your fuses are wrong. The fuses tells it whether or not to run the bootloader. With an empty PROGMEM (ie. no sketch) the processor probably skips over all the 0xFF bytes until it hits the bootloader. Once you have a sketch there it will run the sketch.

On my Uno (which is an Atmega328P) running at 16 MHz from a crystal, my fuses are:

    Low = FF High = DE Ext = FD Lock = EF

I suggest you visit <http://www.engbedded.com/fusecalc> to work out fuse settings.

You want the BOOTRST fuse set (that is, the high fuse should be 0xDE or something with the low-order bit **clear**). On the AVR chips, having a bit clear (0) means the fuse is **set**.

I have a [bootloader programmer sketch](http://www.gammon.com.au/bootloader) which not only puts the bootloader there, it sets the correct fuse bit.

I also have a [chip detector sketch](http://www.gammon.com.au/forum/?id=11633) which will tell you the current fuse settings.


message:
How much ohm resistance I should put between tp120 base and uno?

I have set up solenoid on of based on soil moisture,
The solenoid is powered by 24 volts, so I power solenoid by 24 volt and Arduino uno by stepping down to 6 volt powering through Vin and gnd.

I have used resistance of 10k ohm but I have twice burnt em.
Not sure how should calculate resistance required of signal coming out from D6 pin to TP120 base !

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/hT0Hv.png

body:
To calculate you need to know the maximum current the solenoid uses. The TP120 has a gain of around 500-1000. So the current going into the base needs to be 1/500th of the current going through the solenoid.

So now you know the current needed. Then you can calculate the resistance value you need with `R = V/I`. So `R = 5 / ( <solenoidcurrent> / 500 )`.

So with e.g. a 2A solenoid, you get a value of 1.2kOhm.


message:
Making WiFi hotspot for 3G network sharing controlled by Arduino

I am trying to make a WiFi internet network from 3G using Arduino as access control. I need the Arduino to act as server and control users, consumption, and connection speed. (When users connect to the WiFi, they have to enter a passcode in a webpage to use internet for a limited time,  or limited data.)

So is this possible? I still did not try anything because I can not afford to buy many objects and fail to make it work.

I am thinking of using a 3G shield and a WiFi shield, or a router connected to 3G dongle connected to an Arduino via ethernet, or a 3G shield Arduino to ethernet shield to WiFi router.

I don't know if any of these can work, so I really appreciate any guidance.

body:
Not a chance, I am afraid (you were right not to buy things yet). Things like the 3G shield and WiFi shield don't work in the way that is needed for a WiFi hotspot like that. You're better off with a Raspberry Pi and a 3G USB dongle and run `hostapd` along with the other software needed for your project - things like apache, etc.

You may be able to do it with the Linux portion (OpenWRT) of an Arduino Yun with a USB 3G dongle attached, but it would be sluggish. Best to stick to something with enough processing to do what you want, which means a Raspberry Pi or similar.


body: What you want (on at least an ARM board) is a captive portal, which catches and releases new users if and only if they pass the required challenge. There are numerous software packages for this. If you use a pi, and need to do something with the GPIO pons, have a look at the WiringPi project, which is much nicer than python's silliness. 'Inspired by Monty Python' ... indeed.


message:
Arduino Skill Stop Push button error

I made a skill stop game from Arduino Uno and a pushbutton.Here is the code:

    byte led_one=2;
    byte led_two=3;
    byte winner_led=4;
    byte led_four=5;
    byte led_five=6;
    byte pushbutton=12;
    byte score=0;
    int pushbutton_value=digitalRead(pushbutton);

    void setup()
    {
    // put your setup code here, to run once:
       pinMode(led_one,OUTPUT);
       pinMode(led_two,OUTPUT);
       pinMode(winner_led,OUTPUT);
       pinMode(pushbutton,INPUT_PULLUP);
       pinMode(led_four,OUTPUT);
       pinMode(led_five,OUTPUT);
       Serial.begin(9600);
      }

    void loop()
    {
    // put your main code here, to run repeatedly:

      for (int x=1;x<=6;x++)
      {
        digitalWrite(x,HIGH);
        delay(250);
        digitalWrite(x,LOW);
        delay(250);
        if(pushbutton_value==HIGH && x==winner_led)
        {
           score+=500;
        }
        else if(pushbutton_value==HIGH && x==led_one)
        {
           score+=100;
        }
      }
     Serial.println(score);
    }

My Problem is that Whenever I push the button The Serial Monitor is printing out the wrong score
[![serial print output][1]][1]

  [1]: https://i.stack.imgur.com/GajTX.png

body: I wonder why you initialized `score` as byte! Change it to `int`. As you can see when you `Serial Print` your `score` value doesn't cross 256 because the largest value a `byte` can have is 256 but you are summing `score` to 500


message:
What would be a good way to identify items spending as little as possible?

I'm a software developer for quite some time and now I'm going to start developing for Arduino. My question is related to technology I can use. It's also my first time posting here, so if this site is not the proper place for this questions would you tell me which one I could use to get this answer?

My problem:

I need to identify items within a certain range (~3ft). So I thought about a RFID tag on each item and a reader. The problem with that approach is currently the price. The lowest price I found for RFID tags are about US$0.09 per unit. Which is way too much for this project. up to US$0.01 per unit would be acceptable.

Is there any other way I could identify these items, based on range, not being directed to the reader's laser, that would be cheaper?

I though also about something like stores do with their products to prevent theft. Adding a plastic thingy on their clothes and those totems alert if an item with that plastic thingy passed through.

I appreciate any help :)

Thanks

**EDIT**

Imagine a bag and products being thrown inside this bag. In my mind I'd have a mechanism in which there would be like a rim around this bag that reads the products information. That rim would be a RFID (just for illustration's sake) reader.

Items would be thrown inside this bag, sometimes plenty of items at once. And they all need to be identified.

Something like this:

[![enter image description here][1]][1]

I'm not actually going to implement this solution on a bag, but I think it perfecly illustrates my point.

I hope I was able to clarify the problem now :)

  [1]: https://i.stack.imgur.com/P5Rle.png

body:
Seems like you're stuck in "requirements hell". In my theorie this means that your requirements are too strict, and you or your client won't let go of these requirements.

It can help to do a research, set up some "research questions". And if possible with some sub questions, like:

"How can we measure multiple objects at a price of only 0.01$ per object. Withouth having direct line of sight to all sides of the packaging."

With sub questions:

1. What techniques are available to identify objects.

2. In what environment will this system work?

3. How do other companies detect Products?

4. What techniques fit these requirements and environment.

And if none fit at question 4

5. How can we change the requirements or environment to have one technique fit.

----------

The idea is, that after the research, you probably have a valid answer. But also that you can convince your Boss/client (or yourself), bases on your research, what solution is acceptable, even if it means altering the requirements.

You may also want to check how other companies do this, since it's a pretty common thing to identify objects etc.

----------

For us, it is extremely difficult to say whatever will fit your needs. And you'll most likely have to adapt something.

To start off, you will either need some kind of vision or RF. But any RF tag is most likely to be too costly.

So you're either stuck with vision or increasing the price limit.

With vision, usually you either require some kind of barcode or qr code. Or you'll have to detect the object itself.

Another wat could be to differentiate on the objects' variables. Like check the weight, color, conductivity or even shape. This could be tricky, but not unlikely.

Mind that it also depends on what items you want to detect.


message:
Arduino Leonardo - disabling the debugger port

My Sketch program is working perfectly as a specialized keyboard application on the Leonardo. I want to disable the development tools drivers from the USB, (COM PORT) leaving only the HID Keyboard drivers.  I understand I will need to use the Arduino ISP or other method to load my code.

Is there any way to disable the drivers for the development tools from the on board USB, leaving just the HID drivers?

body: There is no easy way, no. You have to reprogram the core to break the connection between the USB interface and the CDC/ACM driver. That means working out a new set of descriptors, deleting chunks of code, patching around the newly created holes, etc.


message:
I would like to add a RGB led strip to my arduino alarm system

[![enter image description here][1]][1]I am new to programming and would be grateful for any helpful answer...Thank you
I used a ping sensor, a piezo buzzer and an RGB strip. I used the Schematic from Adafruit Learning System..
Here is my code:

    #define trigPin 5
    #define echoPin 6
    #define RED_PIN    10
    #define GREEN_PIN   11
    #define BLUE_PIN  9
    int Buzzer = 3;

    void setup() {
        //set pinModes for RGB strip
        pinMode(RED_PIN,OUTPUT);
        pinMode(BLUE_PIN,OUTPUT);
        pinMode(GREEN_PIN,OUTPUT);

        pinMode(Buzzer, OUTPUT);

        //reset lights
        analogWrite(RED_PIN,0);
        analogWrite(BLUE_PIN,0);
        analogWrite(RED_PIN,0);

        delay(5000);
        Serial.begin (9600);
        pinMode(trigPin, OUTPUT);
        pinMode(echoPin, INPUT);
        pinMode(Buzzer, OUTPUT);
    }

    void loop() {
        int duration, distance;
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(1000);
        digitalWrite(trigPin, LOW);
        duration = pulseIn(echoPin, HIGH);
        distance = (duration/2) / 29.1;
        if (distance >= 80 || distance <= 0){
            Serial.println("No object detected");
            digitalWrite(Buzzer, LOW);
        } else {
            Serial.println("Object Detected");
            tone(Buzzer, 1000); // play 400 Hz tone for 500 ms
            delay(500);
            tone(Buzzer, 10000); // play 800Hz tone for 500ms
            noTone(Buzzer);
        }
        delay(300);
    }

  [1]: https://i.stack.imgur.com/rMXjp.png

body:
An interesting problem with the Arduino paradigm is that not only do you need basic programming knowledge but you also need basic electronics knowledge.

On the plus side, there are plenty of good tutorials where you can over look these issues if you follow the tutorials step by step.  That is, get exactly the same parts and wire them up exactly the same way.  Later, if you like, you can go over the tutorial, ask questions here and discover how and why what you did works.

In your diagram:

You are implying you are using ordinary Red, Green & Blue LEDs and are going to vary their brightness using the Arduino's Pulse Width Modulation feature.

Possible problems:

You are powering the LEDs from the 9 volt pin of the Arduino.  And the LED strip in the diagram is clearly marked 12 volts.  This may work.  But is out of specification.

Also, this setup makes the assumption you are powering your Arduino with a 9 volt wall power supply.  Are you?  You could also power the Arduino with 5 volts using only the USB cable.  There would then be no 9 volts available at the 9 volt pin.  (I would avoid plugging in both power sources at the same time.  I think the Arduino design has changed over time.)

You are using a strip of Red, Green & Blue LEDs.  Which implies more than 1 of these Red, Green & Blue LEDs.  There is an upper current limit on the outputs of the Arduino.  More LEDs means more current.  Too many LEDs will damage the Arduino.  I would stick to 1 LED until you research the amount of current 1 LED takes verses the upper current limit of an Arduino output pin.


body:
If you are not sure which LED lights you want to use, take a look at this [tutorial][1]  and use [these LED lights][1]

No, I have no connection to this video or its author.

  [1]: https://www.youtube.com/watch?v=7Dv70ci-MOw


message:
Using SPI Interrupt causes two servos to lose functionality

My Arduino MEGA clone (ATMEGA 2650) reads SPI data as a slave using an interrupt.
There are also two servos that make an arm (shoulder and elbow).

 - When I comment out the line that attaches the SPI interrupt, the servos
   work properly.

 - When the SPI interrupt is attached, three strange things happen:

  1) The PWM of the elbow remains at a fixed duty cycle. The shoulder works fine.

  2) The shoulder PWM is somewhat jittery time-wise, I assume though that this is unavoidable with interrupts.

  3) Writing an angle to either servo, (appears to) write to *both* servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read() ). And vise-versa.

Again, none of those problems occur when I comment out the SPI interrupt attach.

It doesn't make sense to me though. Why would attaching an interrupt make two servos have the same value? And how can the values of the servos be the same, when only one PWM duty cycle actually changes!?

I wonder if this is a timer issue. Maybe the SPI interrupt interferes with the servo timers or something.

*How can I receive SPI messages while also controlling two servos?*

    #include <Servo.h>
    #include <SPI.h>

    const float pi = 3.14159;
    const float L1 = 27;
    const float L2 = 27;
    float c2;
    float s2;
    float psi;
    float theta;

    float angle_shoulder = 90;
    float angle_elbow = 90;

    volatile int arm_x;
    volatile int arm_y;
    volatile int puck_x;
    volatile int puck_y;

    Servo shoulder;
    Servo elbow;

    int sweepDir = 0;
    int sweep1 = 0;

    unsigned char spiBuffer[5];
    volatile byte buffPos;
    volatile bool process_spiBuffer;

    void setup()
    {
     Serial.begin(115200); //Initialize serial communication
     Serial.println("### SETUP ###");

     shoulder.attach(25); //5
     elbow.attach(43); //3

     // BEGIN SPI SETUP
     // Turn on SPI in slave mode
     SPCR |= bit(SPE);

     // Send on master in, *slave out*
     pinMode(MISO, OUTPUT);

     // Get ready for an interrupt
     buffPos = 0;   // buffer empty
     process_spiBuffer = false;

     // Turn on interrupts
     SPI.attachInterrupt();

     // END SPI SETUP
    } // END SETUP()

    void loop()
    {
     arm_y = 30;

     if (process_spiBuffer)
     {
      spiBuffer[buffPos] = 0;
      // X is a two-byte value, SPI only sends one byte at a time, so merge the bits upon receipt
      puck_x = (spiBuffer[1] << 8) | spiBuffer[2];
      puck_y = spiBuffer[3];
      //Check if received message is acceptable, else throw warning and reject message
      if (spiBuffer[0] != '<' || spiBuffer[4] != '>' || puck_x < 0 || puck_x > 320 || puck_y < 0 || puck_y > 240)
      { //Message received was corrupted
       Serial.print("SPI: Bad MSG Data!:\"");
       //Serial.print(spiBuffer);
      }
      else
      { //Message received "OK"

       Serial.print("SPI MSG Received:\"");
       //Serial.print(spiBuffer);
       Serial.println("\"");

       Serial.print("SPI puck coords:(");
       Serial.print(puck_x);
       Serial.print(",");
       Serial.print(puck_y);
       Serial.println(")");

       // Decide on new paddle position. (x,y) of puck is 90degrees CW from AI (arm) POV, so x and y are swapped. Arm origin (0,0) is at bottom-right corner from the AI POV.
       arm_x = map((240 - puck_y), 1, 320, 5, 49); // map(value, fromLow, fromHigh, toLow, toHigh)

      }
      buffPos = 0;
      process_spiBuffer = false;
     }

     crunchAngles();
     moveArm();

    } // END loop()

    void crunchAngles()
    {
     c2 = (sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2);
     s2 = sqrt(1 - sq(c2));

     angle_elbow = acos((sq(arm_x) + sq(arm_y) - sq(L1) - sq(L2)) / (2 * L1 * L2)) * (180 / pi); // theta?
     angle_shoulder = asin((arm_y * (L1 + L2 * c2) - arm_x * L2 * s2) / (sq(arm_x) + sq(arm_y))) * (180 / pi); // psi?

    }

    // Update the servos
    void moveArm()
    {
     // TODO: Clip servo output with serial warning
     if (angle_shoulder < -10) { angle_shoulder = -10; } // Actual min angle is about -18deg (Model HS-225BB)
     else if (angle_shoulder > 179) { angle_shoulder = 179; } // Actual max angle is about 181deg (Model HS-225BB)

     shoulder.write(180 - angle_shoulder + 2); // Shoulder increments clockwise, so subtract from 180

     if (angle_elbow < 0) { angle_elbow = 0; } // Actual max angle is about -5deg (Model SG90)
     else if (angle_elbow > 170) { angle_elbow = 170; } // Actual max angle is about 190deg (Model SG90)

     elbow.write(angle_elbow + 3); // Elbow increments clowise from

    }

    ISR(SPI_STC_vect)
    {
     byte c = SPDR;

     if (buffPos < sizeof spiBuffer)
     {
      spiBuffer[buffPos++] = c;

      // End of message is ">"
      if (c == '>') // if (c == '\n')
       process_spiBuffer = true;

     }
    }

body:
You have multiple issues here. For a start, you have a buffer (`spiBuffer`) of 5 bytes, into which you place `<Xxy>` (that's 5 bytes) and then finish off with:

<!-- language: lang-c++ -->

        spiBuffer[buffPos] = 0;

That has now overwritten some other memory.

---

Next, you don't seem to be detecting the "<" symbol and resetting to the start of the buffer, so if you ever get out of sync, you will stay out of sync. I suggest something like making `buffPos` equal to `0xFF` initially. Then in the ISR:

<!-- language: lang-c++ -->

    ISR(SPI_STC_vect)
    {
        byte c = SPDR;

        // exit if haven't processed last one
        if (process_spiBuffer)
          return;

        if (c == '<')
          buffPos = 0;
        else if (buffPos == 0xFF)
          return;  // ignore until we get a '<'

        if (buffPos < sizeof spiBuffer)
        {
            spiBuffer[buffPos++] = c;

            // End of message is ">"
            if (c == '>')
                process_spiBuffer = true;

        }
    }

Now we use 0xFF as a "flag" that we haven't received a "<" yet. When we do, we reset `buffPos` to zero, ready to process the next 5 bytes. In the main loop, once we are done with processing the buffer we set `buffPos` to 0xFF again (rather than zero). Also you might have the ISR called before you have processed the previous one, so I put in a test to exit if `process_spiBuffer` is true when you enter the ISR.

---

I found your code to work out the arm positions confusing. For debugging this issue I would replace it with simply moving the servo to the position received by SPI, eg.

<!-- language: lang-c++ -->

       // crunchAngles();
       // moveArm();

       elbow.write (puck_x);

Now just debug that rather than getting confused about the difference between interrupt issues and logic issues. I found once I had done that, that my servo responded without any major issues (there was a bit of jittering occasionally).

---

I found that I got a lot of data errors until I slowed down the **sender** (a few microseconds delay after each SPI.transfer) because sending SPI at high speed didn't give the receiving sketch time to put the data into the buffer.

---

The servo library is rather dependent on interrupts (it manually does the PWM duty cycles). I wrote a sketch a while back that controls one server by using the hardware timer (Timer 1) rather than interrupts:

<!-- language: lang-c++ -->

    const byte potpin = A0;  // analog pin used to connect the potentiometer

    const unsigned long PRESCALER = 8;         // Timer 1 prescaler
    const float PULSE_PERIOD = 0.020;          // 20 ms
    const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
    const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

    // how far apart the pulses are
    const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
    // minimum pulse width (-45 degrees)
    const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
    // minimum pulse width (+45 degrees)
    const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

    void setup()
      {
      TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
      ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

      // Configure timer 1 for Fast PWM mode using ICR1, with 8x  prescaling
      TCCR1A = bit (WGM11);
      TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
      TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,
      pinMode (9, OUTPUT);
      }   // end of setup

    void loop()
    {
      int val = analogRead(potpin);  // reads the value of the potentiometer (value between 0 and 1023)
      OCR1A = ZERO_POSITION_COUNT + (val * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
      delay(15);                     // wait for the servo to get there
    } // end of loop

That is for the Atmega328P, not the Mega, but you could adapt it easily enough. You could use Timer 2 for the other servo (I think).

Since it doesn't use interrupts, then having interrupts going off in the background won't affect the servo.

---

# Example code

After considerable mucking around, I've got a simpler case working reliably.

> Writing an angle to either servo, (appears to) write to both servos! (In the software anyway.) So if I only write to the elbow, the shoulder will have the same value ( printed with shoulder.read()

That's **exactly** what happened to me! Until ... I realized I should power the servos independently. As soon as I connected both servo's +5V and Gnd to an external power supply (and connected the ground of the power supply to the Mega) it all started working properly. So, lesson #1 is: power your motors properly!

I made up a test "driver" on my Uno using the code below:

<!-- language: lang-c++ -->

    #include <SPI.h>

    void setup (void)
    {
      digitalWrite(SS, HIGH);  // ensure SS stays high
      SPI.begin ();
      SPI.setClockDivider(SPI_CLOCK_DIV32);
    }

    void loop (void)
    {
      int val;

      // enable Slave Select
      digitalWrite(SS, LOW);

      SPI.transfer ('<');
      val = analogRead (0);    // read A0
      SPI.transfer (highByte(val));
      SPI.transfer (lowByte (val));
      val = analogRead (1);    // read A1
      SPI.transfer (highByte(val));
      SPI.transfer (lowByte (val));
      SPI.transfer ('>');

      // disable Slave Select
      digitalWrite(SS, HIGH);

      delay (100);
    }

That reads a pot on A0 and A1 and sends the full value (2 bytes) over SPI (which is slightly different to what you are doing).

Then the receiving end (on a Mega2560) has this code:

<!-- language: lang-c++ -->

    #include <SPI.h>

    const unsigned long PRESCALER = 8;         // Timer prescaler
    const float PULSE_PERIOD = 0.020;          // 20 ms
    const float ZERO_POSITION_WIDTH = 0.0005;  // 0.5 ms
    const float FULL_POSITION_WIDTH = 0.0024;  // 2.4 ms

    // how far apart the pulses are
    const unsigned long PULSE_WIDTH_COUNT = F_CPU / PRESCALER * PULSE_PERIOD;
    // minimum pulse width (-45 degrees)
    const unsigned long ZERO_POSITION_COUNT = F_CPU / PRESCALER * ZERO_POSITION_WIDTH;
    // minimum pulse width (+45 degrees)
    const unsigned long FULL_POSITION_COUNT = F_CPU / PRESCALER * FULL_POSITION_WIDTH;

    const byte NO_DATA_YET = 0xFF;

    volatile unsigned char spiBuffer[6];  // '<' xH xL yH yL '>'
    volatile byte buffPos = NO_DATA_YET;
    volatile bool process_spiBuffer = false;

    void setup()
      {
      Serial.begin (115200);   // debugging

      // Turn on SPI in slave mode
      SPCR |= bit(SPE);

      // Send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // Turn on interrupts
      SPI.attachInterrupt();

      TCCR1A = 0;          // disable all PWM on Timer1 whilst we set it up
      ICR1 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

      // Configure timer 1 for Fast PWM mode using ICR1, with 8x prescaling
      TCCR1A = bit (WGM11);
      TCCR1B = bit (WGM13) | bit (WGM12) |  bit (CS11);  // fast PWM top at ICR1
      TCCR1A |= bit (COM1A1);  // Clear OC1A/OC1B on Compare Match,

      #ifdef __AVR_ATmega2560__

        TCCR3A = 0;          // disable all PWM on Timer3 whilst we set it up
        ICR3 = PULSE_WIDTH_COUNT - 1;   // frequency is every 20ms (zero-relative)

        // Configure timer 3 for Fast PWM mode using ICR3, with 8x prescaling
        TCCR3A = bit (WGM31);
        TCCR3B = bit (WGM33) | bit (WGM32) |  bit (CS31);  // fast PWM top at ICR3
        TCCR3A |= bit (COM3A1);  // Clear OC1A/OC1B on Compare Match,

        pinMode (11, OUTPUT);   // OC1A is D11 on Mega2560
        pinMode (5, OUTPUT);    // OC3A is D5  on Mega2560
      #else
        pinMode (9, OUTPUT);    // OC1A is D9  on Uno
      #endif
      }   // end of setup

    int xValue,
        yValue;

    void loop()
    {

      if (process_spiBuffer)
        {
        if (spiBuffer [0] == '<' && spiBuffer [5] == '>')
          {
          xValue = makeWord (spiBuffer[1], spiBuffer[2]);
          yValue = makeWord (spiBuffer[3], spiBuffer[4]);
          }

        // ready for another interrupt
        buffPos = NO_DATA_YET;
        process_spiBuffer = false;

        }

      // adjust PWM amount
      OCR1A = ZERO_POSITION_COUNT + (xValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;

      #ifdef __AVR_ATmega2560__
        OCR3A = ZERO_POSITION_COUNT + (yValue * (FULL_POSITION_COUNT - ZERO_POSITION_COUNT) / 1024) - 1;
      #endif

    } // end of loop

    ISR(SPI_STC_vect)
    {
      byte c = SPDR;   // get byte from SPI hardware

      // exit if haven't processed last one
      if (process_spiBuffer)
        return;

      if (c == '<')
        buffPos = 0;
      else if (buffPos == NO_DATA_YET)
        return;  // ignore until we get a '<'

      if (buffPos < sizeof spiBuffer)
        {
        spiBuffer[buffPos++] = c;

        // End of message is ">"
        if (c == '>')
          process_spiBuffer = true;

       }  // end of room in buffer
    } // end of ISR(SPI_STC_vect)

This incorporates my suggested use of the timer hardware to do the servo positioning, rather than the servo library. There are a couple of `#ifdef`s in there, so you can run it on a Uno as well (it just won't do the second servo).


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

I want to control 4 pins using hexa code like this ff00ff00 (255, 0, 255, 0).

strtol() function works fine with three pins like 00ff00, but when i add two extra caracters to &payload[1] variable like this ff00ff00.
((rgba >> 24) & 0xFF) is equal to 127 when it should be 255.
How to make this work?

each analog pin should be set from 0 to 255

        analogWrite(LED_WHITE,  ((rgba >> 24) & 0xFF));
        analogWrite(LED_RED,    ((rgba >> 16) & 0xFF));
        analogWrite(LED_GREEN,  ((rgba >> 8) & 0xFF));
        analogWrite(LED_BLUE,   ((rgba >> 0) & 0xFF));

        uint32_t rgba = (uint32_t) strtol((const char *) &payload[1], NULL, 16);

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

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

Cheers!

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaea44aa48bda8261f794dcb2d1e7ab2b2


message:
Arduino RGB component identification

[![Arduino set RGB Component][1]][1]

Can someone help me identify this component?

Thanks in advance.

  [1]: https://i.stack.imgur.com/Z5pIH.jpg

body: It's a common-cathode RGB LED module. The LED package itself has 3 independent LEDs, but the board ties the cathodes together.


message:
Most efficient method to turn a gear extremely slowly?

I have a gear that needs to have roughly one rotation per day.  It does not have to be smooth or consistent.  So far, the best I have come up with is to have a stepper motor with an arduino that sleeps, wakes up once an hour maybe and turns the stepper a little bit.

Which arduino should I use for this and is there perhaps a simpler method?  Is there any way to fully cut power then when powered on the arduino advances the motor and then shuts off?

Any ideas?

I want to run off of a 9v battery and get as much time as possible.

edit: adding details as requested

the rotation needs to happen slowly over the 24 hour period.  The tube being turned is a light plastic 1" diameter tube that weighs about 2 lbs.

body:
Steppers require current - and power, due to I^2*R losses) to hold a position. Power off, they free-wheel. What kind of efficiency do you need? A stepper might not be the most power efficient.

An escapement permits or causes a gear to index one position and prevents it turning any farther. In a clock, it permits a weight-driven or spring-driven shaft to index. You'll probably want one that drives the shaft as well, probably with a solenoid.

Another option that comes to mind and doesn't need an Arduino, is a clock motor. Gear down the hour hand 2:1 and you're done. Find a 24-hour clock motor and even that gearing will have been done for you.


body:
Turning of the stepper in between, will result in reduced holding torque. This might be a problem.

I'd suggest using a AA battery pack. 4 AA batteries will give you around 5V. The Arduino doesn't require a precise 5V, so you don't need a voltage regulator.

I'd suggest using something like a Arduino Pro Mini, or Arduino Micro, as those don't have USB-to-Serial chips on the board, using up power all the time. Remove the power led, and put the uC to sleep as much as possible.

If you want accurate timing, you'd want to add and RTC module.


message:
Need Help in circuit diagram of 8*8 reed switch matrix

I am designing 8*8 reed switch matrix which will be connected to Arduino. I am using Arduino Duemilanove. I have completed the matrix portion but don't know how to connect and where to connect the other elements.
![My Matrix circuit][1]

  [1]: https://i.stack.imgur.com/76A84.jpg

I decided to use the following items:

 - Arduino (Duemilanove)
 - 64x Reed Switch
 - 64x Diode (1N4148)
 - 20x Resistors (10K)
 - 1x 74HC595
 - 1x 74HC165

I don't know where to place the Resistors and shift Registers and connection from shift registers to arduino. I need help in the circuit diagram. Please help me out with the circuit diagram.

**Reference:** https://mtifall10.wordpress.com/2010/12/10/magnetic-sensing-chessboard/

body:
**This answer is based on a previous version of the question**

1. Not necessarily. You can use the internal pullups of the arduino if you're willing to accept that reading a "1" means that no piece is there and reading a "0" means a piece is there.

2. Connect each wire up to a pin on the arduino. If you do it wisely, step 3 becomes fairly easy.

3. You need to configure the pins connected to the letter wires as inputs with their pullups enabled. Set the number pins to inputs as well, but without the pullup enabled so that they are floating. The number pins will be each set as an output in sequence with the value being low (non-active number pins are set back to inputs). As you do so, you can read the pins on the letter wires and build a picture of the board.

**Example**

This is how I would do it just taking a naive stab at it. I'm sure there are more effective ways to do this.

Wiring:

[![Wiring][1]][1]

Configure the outputs and inputs in `setup`:

    pinMode(2, INPUT_PULLUP);
    pinMode(3, INPUT_PULLUP);
    pinMode(4, INPUT_PULLUP);
    pinMode(5, INPUT_PULLUP);
    pinMode(6, INPUT_PULLUP);
    pinMode(7, INPUT_PULLUP);
    pinMode(8, INPUT_PULLUP);
    pinMode(9, INPUT_PULLUP);
    pinMode(10, INPUT);
    pinMode(11, INPUT);
    pinMode(12, INPUT);
    pinMode(13, INPUT);
    pinMode(14, INPUT); //A0
    pinMode(15, INPUT); //A1
    pinMode(16, INPUT); //A2
    pinMode(17, INPUT); //A3
    pinMode(18, INPUT); //A4

Make a function to scan the rows into an array of bytes:

    void scan_rows(uint8_t *rows)
    {
        uint8_t i, j;

        for (i = 0; i < 8; i++)
        {
            if (i)
            {
                pinMode(i+9, INPUT);
            }
            pinMode(i+10, OUTPUT);
            digitalWrite(i+10, LOW);
            for (j = 2; j <= 9; j++)
            {
                rows[i] <<= 1;
                if (digitalRead(j))
                    rows[i] |= 1;
            }
        }
        pinMode(18, INPUT);
    }

Now, just call that function with a pointer to an array with 8 bytes in it whenever you need to scan the board. Each byte in the array represents one of the rows and each bit represents a column.

<sub>[moderator note: This answer appears in this thread as a result of a merge]</sub>

  [1]: https://i.stack.imgur.com/106zF.png


body:
Use 16 digital i/o pins on the Arduino. The ones connected to a-h should be configured as OUTPUT pins. The ones connected to 1-8 should be configured as INPUT pins. Start with all of the outputs (a-h) low.

You check for a closed switch at the lower left corner by making the output pin connected to 'a' HIGH then look at the value of the input pin connected to '1'. If it's high then that switch is closed. If it's low then that switch is open.

While the 'a' output is HIGH you can check the rest of the left column by looking at inputs '2' through '8'.

I don't see any need for the resistors or shift registers, but maybe your teacher had something in mind.

EDIT: I see that by using the shift registers you need only one INPUT pin and one OUTPUT pin on the Arduino. I'll leave that for you to figure out as I think I've given enough to get you started.


message:
How to make 12V flashing LEDs using an Arduino Uno?

I have 3 LEDs powered by an Arduino; each LED has its own flash rate.

Now I want it to be powered by an external 12V power source and still have the flashing function of the Arduino?

body: Use a N-channel MOSFET, wire load to drain pin, source to (common) ground, and place a 1 kilo-ohm resistor in series with your arduino pins. Bear in mind that MOSFETs respond to voltage, not milliamps, on the gate - get one that responds well to 5V logic.


body: Or you could use a relay. Many small ones available for a couple of dollars.


body:
As has been mentioned, you could use an N Channel MOSFET, but preferably look for a Logic Level MOSFET.  These are capable of being turned on by lower voltage levels such as on the pins of an Arduino.

Having said that, i have used two non logic level MOSFEt's in Arduino projects successfully.  They are the IRF3205 and IRF 520 - both are readily availalable and will work OK with the Arduino output pins for your low-current-driving-an-LED requirement.


message:
Questions on how to connect Arduino to Matlab through the serial port

I have an Arduino board with Intel Edison on it. I have tried to read data in Arduino from MatLab through the serial port. I'm sure the Arduino board is working because when I use the serial monitor from Arduino, it shows the data read from the Arduino board. My command is like this in Arduino:

       reading = Wire.read();
       Serial.println(reading)

I got errors in Matlab when I tried to work with these piece of code:

       s=serial('COM4');
       set(s,'BaudRate',9600);
       fopen(s);

MatLab complains that "Port: COM4 is not available. No ports are available.
Use INSTRFIND to determine if other instrument objects are connected to the requested device." I have tried with "instrfind()" in matlab and got this:

       Instrument Object Array

       Index:    Type:     Status:   Name:
       1         serial    closed    Serial-COM4
       2         serial    closed    Serial-COM4
       3         serial    open      Serial-COM4
       4         serial    closed    Serial-COM4
       5         serial    closed    Serial-COM4

I still can't get any clue on this. Can anybody help me?

body: I might try to reboot with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable. Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.


message:
Getting a reset error on a WEMOS D1

As a learning effort, I am trying some sample code on my WEMOS D1, which is basically an Arduino compatible board with a built-in ESP8266 (Wi-Fi module).

This is the output of my Serial Monitor:

    1384, room 16
    tail 8
    chksum 0x2d
    csum 0x2d
    v09f0c112
    ~ld
    Initializing Wifi...
    Start printMacAddress
     ets Jan  8 2013,rst cause:4, boot mode:(1,4)

    wdt reset

It stops there and I see no more messages. Below is the code I am trying (from https://www.arduino.cc/en/Guide/ArduinoWiFiShield):

    #include <SPI.h>
    #include <WiFi.h>

    void setup() {
      // initialize serial and wait for the port to open:
      Serial.begin(115200);
      // attempt to connect using WEP encryption:
      while(!Serial) ;
        Serial.println("Initializing Wifi...");
        printMacAddress();
        // scan for existing networks:
        Serial.println("Scanning available networks...");
        listNetworks();
    }

    void loop() {
      delay(10000);
      // scan for existing networks:
      Serial.println("Scanning available networks...");
      listNetworks();
    }

    void printMacAddress() {
      Serial.print("Start printMacAddress");
      // the MAC address of your Wifi shield
      byte mac[6];
      // print your MAC address:
      WiFi.macAddress(mac);
      Serial.print("MAC: ");
      Serial.print(mac[5],HEX);
      Serial.print(":");
      Serial.print(mac[4],HEX);
      Serial.print(":");
      Serial.print(mac[3],HEX);
      Serial.print(":");
      Serial.print(mac[2],HEX);
      Serial.print(":");
      Serial.print(mac[1],HEX);
      Serial.print(":");
      Serial.println(mac[0],HEX);
    }

    void listNetworks() {
      // scan for nearby networks:
      Serial.println("** Scan Networks **");
      byte numSsid = WiFi.scanNetworks();
      // print the list of networks seen:
      Serial.print("number of available networks:");
      Serial.println(numSsid);
      // print the network number and name for each network found:
      for (int thisNet = 0; thisNet<numSsid; thisNet++) {
        Serial.print(thisNet);
        Serial.print(") ");
        Serial.print(WiFi.SSID(thisNet));
        Serial.print("\tSignal: ");
        Serial.print(WiFi.RSSI(thisNet));
        Serial.print(" dBm");
        Serial.print("\tEncryption: ");
        Serial.println(WiFi.encryptionType(thisNet));
      }
    }

I am not a hundred percent sure, but I think this started happening when I connected D8 (Digital Pin 8) to a relay.  I later read that it has a specific use (to flash firmware I think). The error message appears to point to something called a "WatchDog Timer", but I am not even sure what to eat that with. :-)

There are no error messages in the IDE and it even uploads fine. So why is this happening and how do I fix it?

TIA!

body:
If Watchdog timer is the cause of reset that means there is at least one place in your code that runs too long without allowing subsystems to do the background tasks. It **might** be possible the part of your code causing the problem is:

<!-- language: lang-cpp -->

    while(!Serial) ;

Instead that loop use:

<!-- language: lang-cpp -->

    while(!Serial)
      delay(100);

so the background tasks will get the chance to be exectuted during the while loop.

**EDIT:**
In fact you can completely remove that while loop as it is not necessary. There is a possibility `!Serial` is **always** true so the loop never ends. And I suggest you using `74880` instead of `115200` so you can see the debug messages sent automatically by ESP8266.
**END OF EDIT**

However, if that is not the part of the code that causes the problem (and I think it is not) then the problem **might** be `for loop` where you list networks. You can check if that is the problem by adding a small delay inside the loop as follows:

<!-- language: lang-cpp -->

    for (int thisNet = 0; thisNet<numSsid; thisNet++) {
      delay(1);
      Serial.print(thisNet);
      Serial.print(") ");
      Serial.print(WiFi.SSID(thisNet));
      Serial.print("\tSignal: ");
      Serial.print(WiFi.RSSI(thisNet));
      Serial.print(" dBm");
      Serial.print("\tEncryption: ");
      Serial.println(WiFi.encryptionType(thisNet));
    }

If the problem will still exist then you can add a few more `delay(1);` statements through the code.

Instead of `delay` you may use `yield();` which is the same as `delay(0);`.


message:
How to add Attiny13 to Attiny board profile in Arduino IDE 1.6?

Several months ago, I asked how to add (or where to get) Attiny13 to the list of boards in the Attiny package available in github: https://github.com/damellis/attiny In post 1.5 IDE, the package is installed by adding repo's JSON file to boards manager, as described in this post: https://arduino.stackexchange.com/a/23056/2955

Nowhere it says how to modify the files, not at all. And the package doesnot contain Attiny13 info.

The [answer][1] to my question was to do it myself and make a pull request. So ok, but how do I do it? I don't understand those files. The JSON file refferences some SHA-256 named zip files. That's hardly something that can be clearly and simply edited.

Can anyone tell me clearly what do I have to do to get Attiny13 working within that profile?

  [1]: https://arduino.stackexchange.com/a/21775/2955

body:
[this is the official Arduino IDE 1.5 3rd party Hardware specification][1]. It is still valid for 1.6.

It is probably lots easier to just copy past a similar board; rename the board ID and try.

Note that for a change in the boards.txt to be seen in the Arduino IDE you need to stop and start the Arduino IDE.

  [1]: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification


body:
You can easily add entries for the ATTiny13 to the IDE, but won't show in the same listing as damelis's ATTiny cores, as he hasn't added the ATTiny13 yet.

Here is what I have found for ATTiny13 Arduino core files, working with  boards.txt, loading them into the IDE, etc.  The boards.txt is all laid out, just drop it into your personal workspace per the directions provided.

https://github.com/MCUdude/MicroCore

    How to install
    Boards Manager Installation
    This installation method requires Arduino IDE version 1.6.4 or greater.
    Open the Arduino IDE.
    Open the File > Preferences menu item.
    Enter the following URL in Additional Boards Manager URLs: https://mcudude.github.io/MicroCore/package_MCUdude_MicroCore_index.json
    Open the Tools > Board > Boards Manager... menu item.
    Wait for the platform indexes to finish downloading.
    Scroll down until you see the MicroCore entry and click on it.
    Note: If you are using Arduino IDE 1.6.6 then you may need to close Boards Manager and then reopen it before the MicroCore entry will appear.
    Click Install.
    After installation is complete close the Boards Manager window.

This will get you quite a lot of functions, configurable clock speeds, etc. The readme for this project helped me quite a lot  in understanding what is going on inside the box and how I can enable only the Arduino core functions that I want, to save space.

Microcore is based upon :
sourceforge.net/projects/ard-core13/files/latest/

And both projects have code updates as of this summer.

For other ATTiny (I'm using an ATTiny85 sometimes since for some things I ran out of space on the ATTiny13)

github.com/damellis/attiny

This will get you:
ATtiny 25 (8 pin)

ATtiny 45 (8 pin)

ATtiny 85 (8 pin)

ATtiny 24 (14 pin)

ATtiny 44 (14 pin)

ATtiny 84 (14 pin)


message:
wire.h onReceive only triggering once

I am writing a program to emulate a LCD driver chip (PCF8576) in a piece of equipment where I need to replace an unobtainable LCD display.

I have wire.h set up and the code in place to decode chip commands and load the segment data to an array.  That all works, and I can take that data and drive a new LCD just fine.

My problem is that the onReceive handler only triggers once.  To get it to be armed and trigger again I need to press the reset button on the Uno board.  I put code in to pulse an output pin and can verify with a scope that the onReceive only runs once.

When I just began the coding last week the handler would trigger each time the equipment would write to this particular I2C address, and I can tell the equipment is operating correctly since an Arduino reset will then result in the onReceive event triggering again.

Does anyone have any clue what's happening here?  I tried commenting out most of my code but it still won't trigger on each receive.  Obviously there's something subtle I changed that I'm missing, but what?

body:
I looked at what docs I can find (not much) for 'onReceive' handler, but have not looked at the code itself.  I would ask, does the system keep running in spite of the fact that your handler isn't being invoked?  I'm asking if the bus is actually working after the first invocation of the handler? My guess is no. I also guess this ("onReceive" handler) has never worked as designed (hoped for?)

Also it sounds like you have a DSO scope, neat. Decades in electronics and I still get fooled by them (or the software:) now and then.  So make sure it's setup properly. Sounds like you do... but...

Does the i2c bus have only this **one** device?

I've found that 99.99% of my problems turn out to be chip configuration.  Improper interrupt or mask bits, etc. If it's driven by an interrupt, then it almost has to be the chip's interrupt configuration.  Of course if your code goes awry then it could change some of these bits that control the micro's operation and most can also write over the **interrupt vector table**.

Since it **works** after a reset, *once*, it may be wise to track down what happens in your particular micro's configuration after the reset, compared to what you change to get it to work.  Some of the parts of the micro I use (328p, maybe you also) have to be reset after an interrupt.

A last but not least option, since I'm not familiar with the function is to look at the assembler and see if it's resetting the required interrupt enable flags or masks. Most of these handlers end with some type of return from interrupt instruction that enables the interrupts and returns.  Generally alleviating the programmer of that task.

Best of luck :)


body: You are correct and that was the second part of the problem. The first part was that my code wasn't always retrieving every byte and this was hanging up the OnReceive function. Once I fixed that bug I found something very close to what you mentioned. On rapid device writes my handler routine didn't finish fast enough and thus could miss updates. What I did was to streamline the routine to take minimum time and that worked as the sending processor needed time between updates itself. In testing this works fine, what I did was to toggle a port pin and look at the I2C bus and that pin and could verify I was cleared out of the routine before the next update could come in. If it was close I would have gone to assembly for that routine but it turned out ok in this case. Thank you for your analysis!


message:
manual square wave period is off

I'm generating a square wave with my Arduino UNO using the following:

    #define pin 10 // data pin to control servo

    // pulse width (in microseconds)
    int pulsewidth = 2500; // 400 Hz

    // wave period in microseconds
    int period = 20000; // 50 Hz

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

    void loop() {

      // turn pulse on for pulsewidth duration
      digitalWrite(pin, HIGH);
      delayMicroseconds(pulsewidth);

      // turn pulse off
      digitalWrite(pin, LOW);
      delayMicroseconds(period - pulsewidth);

    }

When I check the wave freq on the scope it's reading something like 115Hz instead of 50Hz; however, the pulsewidth is correct (4Hz).

Why is this exactly?  Is it because `digitalWrite()` is slow?

body:
> Why is this exactly? Is it because digitalWrite() is slow?

There is "hidden" code in the main() function which is calling loop(). Also digitalWrite() is slow compared to what is possible. Last, the millis() ISR is executing in the background.

Try the below:

    void loop() {

      while (1) {
        // turn pulse on for pulsewidth duration
        digitalWrite(pin, HIGH);
        delayMicroseconds(pulsewidth);

        // turn pulse off
        digitalWrite(pin, LOW);
        delayMicroseconds(period - pulsewidth);
      }
    }

And then try turning off interrupts.

Cheers!


body:
From Arduino reference on `delayMicroseonds`:

> Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Although the reference does not specify further what happens if `delay > 16383`, a look at the actual code explains this (in `wiring.c`):

    /* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
    void delayMicroseconds(unsigned int us)
    {
    ...
    #elif F_CPU >= 16000000L
     // for the 16 MHz clock on most Arduino boards

     // for a one-microsecond delay, simply return.  the overhead
     // of the function call takes 14 (16) cycles, which is 1us
     if (us <= 1) return; //  = 3 cycles, (4 when true)

     // the following loop takes 1/4 of a microsecond (4 cycles)
     // per iteration, so execute it four times for each microsecond of
     // delay requested.
     us <<= 2; // x4 us, = 4 cycles

     // account for the time taken in the preceeding commands.
     // we just burned 19 (21) cycles above, remove 5, (5*4=20)
     // us is at least 8 so we can substract 5
     us -= 5; // = 2 cycles,
    ...

     // busy wait
     __asm__ __volatile__ (
      "1: sbiw %0,1" "\n\t" // 2 cycles
      "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
     );
     // return = 4 cycles
    }

The line `us <<= 2;` explains why `us` should not exceed 16383, otherwise the left-shifted value will overflow (`unsigned int` is 16 bits on AVR).

In your situation, `(20000-2500) << 2` will not be `70000` or `0x11170` in hexa (that does not fit into `unsigned int`), hence the result will be truncated to `0x1170` i.e. `4464`, which will make the last part of the function (the busy wait) wait for the wrong duration.

In order to fix it, you have to split your second `delayMicroseconds` in one `delay` in milliseconds plus one `delayMicroseconds`:

    delay(17);
    delayMicroseconds(500);


message:
wire.h multiple slave addresses

Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?  For example I'd like it to emulate two different devices, one at I2C address 23 and the other at address 57.

I'm either looking for a way to do this directly, or to run multiple instances (each would need a different onReceive handler).

body:
> Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?

The quick answer is: No!

The ATmega328 2-Wire Serial Interface has a special register for the address match in slave mode. This only allows a single address to be matched.

> 22.5.4   Address Match Unit
>
>The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address
> Register (TWAR). If the TWI General  Call Recognition Enable (TWGCE)
> bit in  the TWAR is written to one, all  incoming address bits will
> also be compared against the General Call address. Upon  an address
> match, the  Control Unit is informed, allowing correct action to be
> taken. The TWI may or may not acknowledge its address,  depending on
> settings in the TWCR. The Address Match  unit is able to compare
> addresses even when the AVR  MCU is in sleep mode, enabling the MCU to
> wake up if addressed by a Master. [Reference, pp. 213][1]

On an ATtiny with USI it is actually possible to implement multiple address matching as this is controlled by software.

Last, a pure software approach could be used, i.e. implement the I2C protocol with external interrupt pin and fast pin access. See Amtel Application Note [AVR154][2]. The code for this app-note can be found on [github][3]. [This][4] could be modified to allow multiple slave addresses.

Cheers!

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [2]: http://www.atmel.com/Images/doc8478.pdf
  [3]: https://github.com/AinonLynx/twi-slave-software-emulation
  [4]: https://github.com/AinonLynx/twi-slave-software-emulation/blob/master/TWI.c#L147


message:
First Serial.print voltage is wrong, way too low. Ruins average calculation

The first Serial.print voltage reading is so far off it really screws up the moving average calculation. For example, the first reading is like 0.00014981, which is wrong. From the second line on it prints the correct voltage, like 0.00475721. I don't know where this first line is coming from. How can I keep that first line from being used in the average calculation? Here are links to the sketch and adc.

<https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries>
<http://www.ti.com/lit/ds/symlink/ads1262.pdf>

For the average calculation I added:

count = count + 1;

volt_mV = ((count-1)/count)*volt_mV + (1/count)*volt_V;

body:
The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables.  Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running.  You could revise your question and include the actual sketch within it.

Nevertheless, the code at the link looks like it will take a reading ok.  Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown.  Or there may be some hardware glitch that spoils the first reading.

Several fixes are possible.  You could discard the first reading.   You could discard the first reading of each set of readings.  You could take readings in sets of three or five and only keep the median reading.  You could take sets of readings and discard the highest and lowest readings.  You could apply [exponential smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing) or some other form of smoothing to the readings.

Note, the formula you show for averaging – `((count-1)/count)*volt_mV + (1/count)*volt_V` – has a number of problems.  First, if `count` is an integer, both of `((count-1)/count)` and `(1/count)` will compute to zero values.  Secondly, as `count` becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic.  Third, although the formula computes a *running* average, it does not compute a *moving* average.  That is, your formula computes the average of all readings taken so far, with all readings equally weighted.  A [moving average](https://en.wikipedia.org/wiki/Moving_average), on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an [exponential smoothing](https://en.wikipedia.org/wiki/Exponential_smoothing) formula like `movingAverage = (15*movingAverage + newReading)/16`.


body: If it is truly only the first reading that is bogus, you could take one or a few readings during `setup()` whose values you ignore, before your program starts collecting data. Or you could investigate why your first reading is bogus....


message:
What am I doing wrong with my millis()?

Im new to Arduino and have been trying to use the millis() function for an assignment of mine. I have had a lot of trouble trying to get the millis() function to work but now it seems to be working properly as far as I can tell through the serial viewer but it wont stop my loop once it goes higher than the run time. Im trying to stop my loop after 10 seconds, but it continues going and I feel like it has something to do with my millis().

     // Pin 13 is the LED

     int led = 13;        // pin 13 on the board
     int ledOFF = 8;      //led off time delay
     int ledON = 5;            //led on time delay
     unsigned long Timer = 0;      // store time
     int runtime = 10000;      // run loop for 10s

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

       Serial.begin(9600);
       delay(1000);
     }

     void loop() {
       Timer = millis();
       int state = 0;
       while(millis() - Timer <= runtime){
         Serial.println(Timer);
         if(state==0){
           digitalWrite(led,LOW);
           state = 1;
           delay(ledOFF);
         }
         else{
           digitalWrite(led,HIGH);
           state = 0;
           delay(ledON);
         }
        }
       }

body: You are always re-init Timer as millis on every loop. So millis() - Timer is probably always a few milisecond and never reaches your runtime value.


body: as @Andre said on comment, you give variable 'Timer' a new value each loop. One of the solution is putting `Timer = millis();` on the `void setup` instead on `void loop`


message:
How to setup an I2C bus which stays valid if a slave is powered down or fails?

I have setup an I2C bus between 3 Arduinos (Master, Slave1 and Slave2) by connecting all 3 A4 pins together, all 3 A5 pins together and one GND pin of each Arduino to a common ground line. The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

The slaves use the Wire library: Slave1 is at address 0x07 and Slave2 at 0x08. The Master uses the I2C library by Wayne Truchsess, because this library has timeout functionality. Master polls Slave1 and 100 ms later, polls Slave2. If either Slave is unavailable, Master should still read the other Slave (this is why Master doesn't work with the Wire library).

However, even though Master doesn't get locked-up, it can't read one Slave if the other gets powered down but left connected. If I cut the power of Slave1, Master becomes unable to read data from Slave2 until I physically disconnect Slave1. If I disconnect Slave1, Master is immediately able to read from Slave2 again. I2C scanning suggests the whole bus becomes invalid when a Slave is powered down (SCL and/or SDA turned low?).

From what I have been reading, this is not a software issue but an electronics circuitry problem: leaking current related to Slave1 and Slave2 having some diodes, something that perhaps could be solved with some transistors or N-FETs which would act like check-valves? Please advise.

P.S.: I have very little background in electronics and English is not my first language.

body:
An [I2C bus][1] should use [open drain lines or open collector][2] drivers AND there should be only 1 (one) pull up resistor for each of the 2 I2C wires.  In this way, should a slave fail, it will not effect the I2C bus.

An Arduino does not truly have an open collector driven pin.  Instead people have been clever and either set the pin connected to an I2C line low pulling the I2C bus low or as an input allowing the I2C bus to float high through the pull up resistor. In this way multiple I2C devices (Arduino or not) can share the bus.

However, if you power down an Arduino, it can no longer operate in this manner.  In fact it will likely appear as a load or path to ground and effect the normal operation of the I2C bus.

In the end, I2C is designed for chips (usually) on the same board so that they can talk with one another.  It would follow that they are all powered off the same supply. It is an unlikely scenario for power to fail for only one device on the board.

Alternatives:

There are protocols designed to go between devices (as in separately located and separately powered).  [RS485][3] is one such protocol and has been around for years.  A quick search show both sheilds made specifically for Arduinos as well as [tutorials using generic RS485 interfaces][4].

  [1]: https://en.wikipedia.org/wiki/I²C
  [2]: https://en.wikipedia.org/wiki/Open_collector
  [3]: https://en.wikipedia.org/wiki/RS-485
  [4]: https://arduino-info.wikispaces.com/SoftwareSerialRS485Example


body:
> The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

I think your problem here is that if you power down one Arduino, it isn't really powered down, because it will get "parasitic power" from the I2C line, particularly from the pull-up resistors which should be there. The protection diodes (internal to the processor) will allow power to flow from the A4 and A5 pins to the Vcc pin of the chip, which will then power up, probably in some sort of indeterminate state.

Since you are planning to power them from the same supply anyway, your problem should simply go away when you do that. Connecting a device with active inputs to a circuit (ie. a voltage present) when the device itself is not powered up, is not recommended. Exceptions would be devices that are specifically designed to handle that, for example, commercially produced printers via their USB input.


body:
> From what I have been reading, this is not a software issue but an
> electronics circuitry problem: leaking current related to Slave1 and
> Slave2 having some diodes, something that perhaps could be solved with
> some transistors or N-FETs which would act like check-valves? Please
> advise.

A nice solution to this problem is to use I2C Bus Isolation with [TI TCA4311A Hot Swappable 2-Wire Bus Buffers][1] alt. [Analog Devices ADUM1250][2].

Please see the [EEVblog Electronics Community Forum][3] for further details and discussion.

Cheers!

  [1]: http://www.ti.com/lit/ds/symlink/tca4311a.pdf
  [2]: http://www.analog.com/en/products/interface-isolation/isolation/isolated-i2c-isolators/adum1250.html#product-overview
  [3]: http://www.eevblog.com/forum/microcontrollers/i2c-bus-isolation-for-un-powered-avr/


body:
Mikael has the correct answer above.

I had this same issue when using two Megas communicating over I2C, along with other items running on the I2C bus. I needed the system to continue running if one Mega went down due to loss of power. The other Mega should detect it and execute some abort commands for my mission.

Initially I wired the Megas up on the same I2C bus, just as I would any other device. When I unplugged one Mega, the other would freeze the next time it tried to address another device on the bus.

The solution was to use a hot-swappable I2C buffer. I used this one, and everything worked immediately without issue after wiring it up: http://www.mouser.com/search/ProductDetail.aspx?r=595-TCA4311ADR

To integrate the SOIC-8 package onto a standard DIP breadboard for Arduinos, I used an adapter from Adafruit.

Cheers and good luck

Chris

High Altitude Photography Platform 360 video from a jet-stabilized platform at the edge of space http://hialtphoto.blogspot.com

Facebook @hialtphoto