body:
I've been doing a fade function for the NeoPixels. However, the moment I have maximum brightness for the pixels, *I noticed there 2 colours even though in my function I have only specified one colour*.

Some strips are one colour and the others are another colour. I
specified the colour to be blue for the strips however many strips are blue and the strips nearer the end are green (but closer to a blue-green colour).

Is there any way to keep the colour even when the brightness changes? I've read somewhere online a different colour is seen with different brightness levels i.e. `setPixelColor(brightness, r,g,b)`.

I've also tried FastLED library and followed documentation. However, the lights are not doing what it has said in the codes, I've tried `leds[i].fadeLightBy(200)` and it has given me no result.

My code for the fade function (edited from http://moving-rainbow.readthedocs.io/en/latest/guide/fade-in-and-out/):

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

    void fade(uint32_t color) {
      for (int i = 0; i < 255; i++) {
        for (int q = 0; q < strip.numPixels(); q++) {
          strip.setPixelColor(q, Wheel((color) & 255));
        }
        strip.setBrightness(i);
        strip.show();
      }

      //decreasing brightness
      for (int l = 255; l > 255; l--) {
        for (int p = 0; p < strip.numPixels(); p++) {
          strip.setPixelColor(p, Wheel((color) & 255));
        }
        strip.setBrightness(l);
        strip.show();
      }
    }

The method "Wheel" is from the Arduino Neopixel strandtest example.

    uint32_t Wheel(byte WheelPos) {
      WheelPos = 255 - WheelPos;
      if (WheelPos < 85) {
        return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
      }
      if (WheelPos < 170) {
        WheelPos -= 85;
        return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
      }
      WheelPos -= 170;
      return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
    }

Any advice on how I should go about doing it?

title: (Neopixels) How to keep the pixels of the same colour despite increasing brightness?

Answers: 1

body:
I have some simple NeoPixel fading going on in this example sketch:

    /*
     *
     * NeoPixels demo - fades colours (in array) up and down
     *
     */

    #include <SPI.h>
    #include <NeoPixels_SPI.h>

    const unsigned int PIXELS = 8; // Number of pixels in the string

    void setup()
      {
      ledsetup();
      } // end of setup

    float patterns [] [3] = {
      { 1, 0, 0 },  // red
      { 0, 1, 0 },  // green
      { 0, 0, 1 },  // blue
      { 1, 1, 0 },  // yellow
      { 1, 0, 1 },  // magenta
      { 0, 1, 1 },  // cyan
      { 1, 1, 1 },  // white
      { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
      { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

    };

    // number of items in an array
    #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

    void loop()
      {

      for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
        {
        // fade up
        for (byte m = 0; m < 100; m++)
          {
          showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
          delay (10);
          } // end of for

        // fade down
        for (byte m = 100; m > 0; m--)
          {
          showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
          delay (10);
          } // end of for
        } // end of for each array item

      } // end of loop

This is using the simple [NeoPixel library](http://www.gammon.com.au/forum/?id=13357) that I wrote using the SPI hardware. The library with the exact code above is [available here](https://github.com/nickgammon/NeoPixels_SPI).

Basically the fading is done by multiplying the floating-point values for the R/G/B values by a constant from 0 to 100 (you could make it 0 to 255).

Since the colours themselves are expressed in the range 0 .. 1 then the result of the multiplication would be 0 to 255. To my naked eye the colours seem true at all brightnesses.

To use the library on your Uno just connect +5V, Gnd, and the data pin is MOSI (D11 on the Uno).


body: I have noticed that when I used a log pot from a guitar amp I found, it gives janky results when using it in a motor PWM sketch, but if I use it in a fade sketch, it works. why does log pots give sketchy results when using them in a PWM control sketch, like when using the `map()` function?

title: Log vs linear pots and the arduino

Answers: 1

body:
There are two associated issues here that underly your problem.

Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:

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

(* a "commercial" log pot is how log pots are usually manufactured - two linear traces of different resistances back to back).

So when turning you get "not much ... not much ... not much ... lots ... even more ... full".

Now couple that with how a motor works. A motor has a "stall current", which is higher than the "run current" (especially the "unloaded" run current).  This is the minimum amount of current required to overcome the inertia of the motor and start it spinning. This is, in effect, a lower threshold on the PWM value that you need to exceed before the motor will begin moving (once it's started moving you can go a little below that threshold and it will still move).

With a linear pot it's easy to get to that threshold and stay around it, increasing slowly above it, etc.  However, as you can imagine looking at the curve of the log pot above, if the "flatter" area of the pot is below the stall current threshold of the motor, the motor will do nothing until you are well into the sharper up-turn of the curve.  The effect of this is you will go from "stopped" to "quite fast" in one jump. It's very very hard to get even close to the stall current threshold.

For instance, if your motor needs a minimum of 30% duty cycle to start it running, that's about a 160 degree turn on the log pot above, compared to just 70 degrees of a linear pot, and the rest of the log pot's PWM range is compressed into a tight space.

  [1]: https://i.stack.imgur.com/BNipp.gif


body:
Why are there two Serial.begin() function calls? What does that signify?
   Here is the minimal code i am working on:

    void setup() {
          Serial.begin(115200);
          Serial.begin(9600);
          Serial.println("Pressure Sensor Test"); Serial.println("");
        }

Here is the full Code:

    #include <SimpleDHT.h>
    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BMP085_U.h>

    int pinDHT11 = 2;
    Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085);

    void displaySensorDetails(void)
    {
      sensor_t sensor;
      bmp.getSensor(&sensor);
      Serial.println("------------------------");
      Serial.print  ("Sensor:       "); Serial.println(sensor.name);
      Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
      Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
      Serial.print  ("Max Value:    "); Serial.print(sensor.max_value); Serial.println(" hPa");
      Serial.print  ("Min Value:    "); Serial.print(sensor.min_value); Serial.println(" hPa");
      Serial.print  ("Resolution:   "); Serial.print(sensor.resolution); Serial.println(" hPa");
      Serial.println("----------SDNx real time scientific data---------------");
      Serial.println("");
      delay(500);
    }

    void setup() {
      Serial.begin(115200);
      Serial.begin(9600);
      Serial.println("Pressure Sensor Test"); Serial.println("");
      if(!bmp.begin())
      {
        /* There was a problem detecting the BMP085 ... check your connections */
        Serial.print("  Ooops, no BMP085 detected ... Check your circuit some errors are there!");
        while(1);
      }

      /* Display some basic information on this sensor */
      displaySensorDetails();

    }

    void loop() {

      Serial.println("===========");
      Serial.println("Sample DHT11...");

      byte temperature = 0;
      byte humidity = 0;
      byte data[40] = {0};
      if (simple_dht11_read(pinDHT11, &temperature, &humidity, data)) {
        Serial.print("Read DHT11 failed");
        return;
      }

      Serial.print("Sample RAW Bits: ");
      simple_dht11_serial_print(data);

      Serial.print("SDNx says you are genius and every thing is OK: ");
      Serial.print((int)temperature); Serial.print(" *C, ");
      Serial.print((int)humidity); Serial.println(" %");

      // DHT11 sampling rate is 1HZ.
      delay(1000);

      sensors_event_t event;
      bmp.getEvent(&event);

      if (event.pressure)
      {

        Serial.print("Pressure:    ");
        Serial.print(event.pressure);
        Serial.println(" hPa");

        float temperature;
        bmp.getTemperature(&temperature);
        Serial.print("Temperature: ");
        Serial.print(temperature);
        Serial.println(" C");

        float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
        Serial.print("Altitude:    ");
        Serial.print(bmp.pressureToAltitude(seaLevelPressure,
                                            event.pressure));
        Serial.println(" m");
        Serial.println("");
      }
      else
      {
        Serial.println("Sensor error");
      }
      delay(1000);
    }

title: Confusion with two Serial.begin() function calls

Answers: 1

body:
It looks like a mistake, as Chris says.  I can't tell you what will happen but my **guess** is it will work at 9600.

I would recommend that you delete one of the lines to avoid further confusion.


body:
I need to submit HTML form from my remote website to my ESP8266 server using `POST` method. I'm looking for something like that :

        <form action="my esp8266 IP" method="POST">
            <input type="text" name="foo" value="go">
            <input type="submit">
        </form>

Can I use IP address in `action` attribute?
How can I detect and print received data on ESP8266 side?

title: Submit data from HTML form to ESP8266

Answers: 1

body:
> Can I use IP address in action attribute?

Sure, if your ESP8266 is either on the same internal (behind a NAT router) subnet as your web server, or your ESP8266 has a public IP address.

> How can I detect and print received data on ESP8266 side?

By parsing the data as it comes in through the socket.

If your ESP8266 is on your home network and your website is out on the internet somewhere you will have to arrange some form of port forwarding through your router (outside the scope of this site) and have some way of your website tracking your (most likely dynamic) home IP address. Again, outside the scope of this site.

It is much more common to use protocols such as MQTT or another RESTful API to have your ESP8266 check in with a remote server to request updated data and instructions, rather than a web server blindly pushing the information directly to the ESP8266.  This is because:

* Putting your ESP8266 directly (or indirectly through port forwarding) on the internet is a security nightmare, and
* Putting all the pieces of the jigsaw together to make it work reliably is not trivial.


body:
I've made my own AVR programmer with an Arduino Nano V3 clone. It has been working fine, but yesterday I was trying to program a faulty board that pulled too much current. Was powering via USB and my OSX laptop told me it had disabled it due to pulling too much power.

After that I couldn't power it anymore, not even from a simple phone charger. I thought I had burnt something, but when testing with a DVM I accidentally shorted pin 1 and 2 of the USB connection:

1 - (red) VDC / plus / +5V

2 - (white) Data -

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

Then it boots up and is powered as long as I have them connected. Without it wont start with any usb connection, laptop or phone charger. Just to show what I mean:

https://photos.app.goo.gl/rtFj6bp3j4SbuYKr1

Why is this and is there something I can do to save this Nano - it seems to be working fine when usb is shorted like this…

Would hate to have to build up another one while waiting for a new programmer from China :)

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

title: Arduino doesn't boot unless I short USB pin 1-2 (VCC/Data -)

Answers: 2

body:
When you plug the board in, the computer enumerates it. The normal device descriptor (IIRC) requests 50mA. If you are (as you most likely are) drawing more than that then the computer is quite within its rights to turn it off.

By shorting those pins you are preventing it from enumerating, so the computer doesn't know the requested amount, so it assumes (probably) 500mA.

You can achieve the same effect by using a cable with no data wires in it.

body:
It's possible you've blown the voltage regulator.  If you happen to have a source of those, like another dead Nano, you can try replacing it to see if that works.

Shorting the +5 to data is likely going to destroy your computers USB controller, so please quit.


body:
Why can't i assign the value to a variable  outside the function?

    void setup(){}
    int a;
    a=12;   //  WHY IS THIS GIVING ME ERROR
    void loop(){
    }
Why the line `a=12` gives me an error?
Thanks!

title: variable doesnt have a type name

Answers: 1

body:
> a=12;   //  WHY IS THIS GIVING ME ERROR

Because you can't do assignments like that outside of a function.

You can, though, create *and* assign the variable at the same time:

    int a = 12;

That is a declaration of the variable, whereas

    a = 12;

is a procedural statement. Procedural statements cannot be executed in the global scope. They can only be executed inside a function during the execution of the program (the global scope never gets executed).


body:
I'm working on some software using an Uno (ATmega328P). I have a stage byte that can be 1 of 5 values (0-4) in my code and it will increase by 1 every 2.5 hours. If I lose power I need to ensure that on wake up the stage is the same as it was at the time of power loss, so each time the stage is updated I save it to EEPROM.

To ensure the EEPROM lasts as long as possible I want to write some code that uses more than a single byte which I continually erase and write to. I was wondering if there is any library to do this or if my idea below would work?

I currently don't need to use the EEPROM for anything else so to extend the EEPROM life I was going to section of 1 quarter of it (0-255 bytes) for saving this value. Each time I change the stage I will write 3 bytes to EEPROM which will be:

 - An index byte (used to shift addresses I write to).
 - A stage byte (the stage I need to store).
 - A count byte (the amount of times I have wrote the stage at the current index).

To begin with the index will be written to byte 0 in the EEPROM, the stage to byte 1 and the count to byte 2.

My plan is to allow the stage to be written to byte 1 250 times, then clear the count and shift the index to 3. This will in turn move the bytes that the stage and count are being written to to 4 and 5. I will do this until the index reaches the end of the 255 bytes and then return the index to 0. So in total I should be able to shift 85 times.

Each byte has 100,000 erase/write cycles so this means I can pass through bytes 0-255 400 times, writing the stage 250 times each pass. So instead of having 100K writes I would have about 8.5 million writes.

This is my first idea and I realize there is also some waste in the way I do it. I haven't worked with EEPROM much and I was just hoping for some advice as I'm sure I could be going at this completely wrong.

title: Extending EEPROM life

Answers: 3

body:
You can load spread by saving the current value ORred 0x80 or 0x00.

When writing you write to the next memory location and when it wraps you take the other value to OR with.

The values in the eeprom will be

    [{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value},{0x00|value},{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value}]

or

    [{0x80|value},{0x80|value},{0x80|value},...,{0x80|value},{0x80|value},{0x80|value},{0x00|value},{0x00|value},{0x00|value},...,{0x00|value},{0x00|value}]

Then you read the first and last byte and if the upper bit is equal you take the last value.

If they are not equal you binary search until to the position changes, the most recent value will be the one right before the change.

body:
There are many ways of achieving what you want. The method I would use would be to use pairs of bytes, but split up differently.

For each 16 bits I would have 13 for a counter, and 3 for a value. The counter, being 13 bits, can count from 0 - 2^13-1, or 0 - 8191.  The 3 value bits can store 0 - 2^3-1, or 0 - 7, which is fine for your 0-4 value.

The size of the counter is important, since it is more than double the number of 16-bit pairs in the EEPROM.  Assuming a 1kB EEPROM that's 512 16-bit values, so you want more than 1024 values available in your counter (if you wanted to change the split to store a larger number...).

The algorithm is simple:

1. Read through the EEPROM looking at the next counter value. If the count increases by more than 1 the last value read is the current one.
2. If the count goes from 8191 to 0 then keep going, you have just looped is all.
3. Increase the counter by 1 and write to the EEPROM addresses where the count jumped by more than 1.

For example, if you have:

    78 1
    79 2
    80 3
    8191 7
    8191 7
    8191 7

you know that the space after 80 hasn't been used (0xFFFF is split as 0x1FFF and 0x7) so you write "81 4" to it.

Another:

    8190 2
    8191 3
    0 4
    1 0
    2 1
    7283 3
    7284 4
    7285 0

The jump from 8191 to 0 is just a wrap around and can be considered sequential. However the jump from 2 to 7283 isn't sequential, so you can overwrite entry 7283 with "3 2".

When you write, if you are going past the end of the EEPROM's memory space, you just loop back round to the start again.

This gives you 512 * 100,000 writes, or 51.2m writes.

body: Also, check that the values you want to write are actually changing. No point in erasing and writing a value that is already there. And you save 3.3 ms by not having to do the write.


body:
I am building a ESP-07 based IOT device, that detects the status of 4 doors. The device must connect to WiFi and send an http request, when 1 of 4 doors is opened. I want to place a reed switch, for example on each door. The battery consumption should be minimal, so I thought of using deepsleep () or something similar to keep the device asleep most of the time, or keep it completely off (like most Dash buttons does).

I have studied several options, but almost all use a single GPIO to wake up the device. For example, this option wakes the device up if D3 goes high, and sleep if D3 is low.
<!-- language-all: lang-cpp -->
    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>
    #define WAKE_PIN D3

    const char* ssid = "SSID";
    const char* pass = "PASSWORD";

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

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

    void setup(){
        WiFi.begin(ssid, pass);
        uint8_t i = 0;
        while (WiFi.status() != WL_CONNECTED && i++ < 10) delay(250);
        Serial.begin(115200);
        Serial.println("Setup");
        pinMode(WAKE_PIN, INPUT_PULLUP);
        pinMode(LED_BUILTIN, OUTPUT);
        digitalWrite(LED_BUILTIN, LOW);
        gpio_init(); // Initilise GPIO pins
    }

    void loop(){
        Serial.println("Do something...");
        if(!digitalRead(WAKE_PIN)){
            sleep();
        }
        delay(1000);
    }

    void sleep(){
        Serial.println("Going to sleep...");
        delay(10);
        wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); // set sleep type
        gpio_pin_wakeup_enable(GPIO_ID_PIN(WAKE_PIN), GPIO_PIN_INTR_HILEVEL);
        wifi_fpm_open(); // Enables force sleep
        wifi_fpm_do_sleep(0xFFFFFFF); // Sleep for longest possible time
        delay(100);
        Serial.println("Woke up!");
    }

Here, GPIO_ID_PIN(2) corresponds to GPIO2 on ESP8266-01 , GPIO_PIN_INTR_LOLEVEL for a logic low, can also do other interrupts.

My question is:

Can I use more than one GPIO, that is, one of 4 GPIOs to wake up the device?

I have the problem of knowing which of the four doors has been opened!

The other option I have thought is to use a latch circuit that turns on the (previously turned off) device using a single GPIO. Something like this:

[![Latch circuit][1]][1]

What I meant is that ESP-07 can latch its own power on (and off) using an MOSFET pair connected in parallel with the physical (momentary contact) power switch. When the power switch is pressed (or a door is opened), one of the  first things the ESP8266 needs to do is latch the power on. When the current iteration of this programm is done, it simply turns it's own power off again.

    #define POWER_SW   2   // GPIO connected to POWER_LATCH

    void LatchOn() {
        pinMode(POWER_SW, OUTPUT);
        digitalWrite(POWER_SW, HIGH);
    }

    void LatchOff() {
        digitalWrite(POWER_SW, LOW);
    }

What I want to know is how I can use more than one signal from each of the 4 doors, or, use 4 GPIOs to activate the latch circuit. I tried with one single door connected to the GPIO that wakes the chip up. I want to extend the functionality of my program so that any of the 4 doors turns the chip on.

Thanks in advance!

P.S.
I have opened a thread about this topic in [Arduino Forum][2] as well.

  [1]: https://i.stack.imgur.com/hqTtk.png
  [2]: http://forum.arduino.cc/index.php?topic=523073

title: Wake up ESP8266 with multiple GPIOs

Answers: 0


body:
I'd like to know if it's possible, and if so how to use the serial Rx pin in a shared way to read a push button?

I've seen people using it in sort of a dedicated way but my idea is to use it dynamically. Which means it would stay as a standard Rx pin, with a push button sharing it. So the question is, what would happen if the push button was pressed? Would it be possible to detect it from the Rx stream?

title: Sharing serial Rx to read a push button on ESP8266-01

Answers: 1

body:
I have experimented with my NodeMCU (ESP8266-12F, but the core chip is the same ESP8266EX).

First, the theory: UART is a asynchronous serial protocol. It has a configuration which consits of the baud rate (bits per second), parity bit (enabled or not) and number of stop bits (between 1-2). A common configuration is "9600N1", meaning 9600 bits per second, **n**o parity bit, 1 stop bit.

If you want to trasmit the bitstring `0101 0101` with no parity, 1 stop bit, the RX line voltage will be:

[![uart1][1]][1]

RX line idles in high state (for us: 3.3V). Transmission is started by the start bit, which means that the line is pulled LOW. Then, the bits are transmitted LSB to MSB, followed by parity (if enable) and the stop bits.

I wrote the sketch

    #include <Arduino.h>

    void setup() {
     //use 300 Baud, lol
     Serial.begin(300);
    }

    void loop() {
     if(Serial.available()) {
      char readChar = (char) Serial.read();
      Serial.println("Read char: " + String(readChar) + " hex " + String((int)readChar, HEX));
     }
    }

When transmitting a normal "A" (binary: `0100 0001`) over serial, it looks like this in a logic analyzer:

[![uart_1][2]][2]

When I connected a pulled-up button the RX line and press, the signal goes as

[![uart2][3]][3]

As one can see, the analyzer sees the pushing down of the button as a start bit, but the timing is way of. The line is pulled back to high much later. The time slot for the stop bit (which must be *1*) was missed, so the logic analyzer displays "FRAMING ERROR". But the UART circuit inside the ESP8266 doesn't seem to care. It reads this as the transmission of a byte of the value "0x00".

Serial output: `Read char:  hex 0`

So, in response to the question "what would happen the push button was pressed?" we can say: At this speed of 300 baud (lowest possible setting), the UART received a bogus transmission but still reads it as an incomming `0x00` byte. However, depending on the bouncing of the signal due to the button presses, other received byte values might well be possible. You could be able to de-bounce the button to make the signal more stable, timing wise.

Anyway, you should not make a push button act as a crude UART transmitter if it isn't the absolute last possible solution. Depending on your application, you might be able to use the solution from [this question][4] and switch the function of the TXD0 and RXD0 to GPIO ([more info][5]). If you know exactly when to expect a button push, switch the pins to GPIO mode before and poll the status of the button (or install an interrupt).

However, as a bottom line: If you have no idea when the button will be pushed, then you will be fundamentally unable to distinguish the cause of the RX line falling low at the time the transition happens. It could be the transmission of some actual data (maybe also the zero-byte), but it could have also been the button.

A I²C GPIO port expander like the MCP23017 ([link][6]) would make much more sense, especially if you already have an I2C bus. There are also SPI devices available for this.

  [1]: https://i.stack.imgur.com/0SFpa.png
  [2]: https://i.stack.imgur.com/6QiTC.png
  [3]: https://i.stack.imgur.com/TJwc2.png
  [4]: https://arduino.stackexchange.com/questions/29938/how-to-i-make-the-tx-and-rx-pins-on-an-esp-8266-01-into-gpio-pins
  [5]: http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations#uart_pins
  [6]: http://www.instructables.com/id/Adding-an-MCP23017-IO-Extender-to-Arduino-or-ESP82/


body:
I have created a class like this:

    #ifndef MyList_h
    #define MyList_h

    #include "Arduino.h"

    template <typename T>
    class MyList {
    public:
      MyList(void);
      ~MyList(void);

      void addItem(T* item);

      //more stuff

    };

    #endif

And implementation is like this:

    #include "Arduino.h"
    #include "MyList.h"

    template<typename T> MyList<T>::MyList(void) {
      // constructor implementation here
    }

    template<typename T> MyList<T>::~MyList(void) {
      // desctructor implementation here
    }

    template<typename T> void MyList<T>::addItem(T* item) {
      // function implementation here
    }

    // ...more stuff

In my .ino Sketch I'm doing this (found this solution in a C++ example):

    #include "MyList.h"
    MyList<word>* list = new MyList<word>(); // global scope
    //... more stuff

But when compiling, Arduino IDE complains:

> Test.ino:5: undefined reference to `MyList<unsigned
> int>::MyList()'

I googled a bit and found this alternative way for creating the instance:

    ArrayList<word>* list;

Then there's no error, just compiles file. BUT as soon as I want to use this instance (=adding code) like this:

    list->addItem(i);

compiler complains again:

> Test.ino:25: undefined reference to `MyList<unsigned
> int>::addItem(unsigned int*)'

What's wrong? Why is this reference undefined?

I tried another way:

    ArrayList<word> list; // again global scope

But then the compiler also tells me:

> Test.ino:5: undefined reference to `MyList<unsigned
> int>::MyList()' /tmp/ccp8qmCz.ltrans0.ltrans.o: In function
> `_GLOBAL__sub_D_list':
> /....../Test.ino:5:
> undefined reference to `MyList<unsigned int>::~MyList()'

So, how can I create an instance of my class that uses a template?

----
Environment: Arduino IDE 1.8.3 (I know, I could update...) + Arduino Nano Board.

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

Answers: 1

body:
I think I found the solution:

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

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

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


body:
I have been working with Unos and just started working with Yun. I have 1.86 currently installed but the Yun starts up saying to use 1.5.6-r2 Beta IDE. Should I uninstall 1.8.6 and install 1.5.6-r2?

Thanks for your help.

Lisa

title: Arduino Uno and Arduino Yun software. Which version of the IDE works with both best?

Answers: 1

body:
The Yun startup was written when the normal IDE didn't support the yun, so you had to use a release candidate of a future version.

Those days are long gone.

Always use the latest version of the IDE.


body:
I am having problems getting the Bluesmirf Mate Silver (RN-42) into command mode once I have switched to HID mode. I have bought a second new Bluesmirf Mate Silver to confirm my issue.

I soldered the Bluesmirf and connecting to Arduino Uno. I used the ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

I then entered the following commands in command mode (leaving out the comments):

    SM,5   // Mode = 5, (any) Auto reconnect
    SA,2   // Authentication Mode 2 (SSP, "just works" mode)
    S-,myName  // // Set BT Name, This short name with no spaces is Picked up ok on windows
    S~,6   // Enable HID on reboot
    R,1    // Reboot to lock in perameters

Next I use a PC and pair with the bluetooth ‘keyboard’ I have created above. I am able to use the Bluetooth and Arduino sketches to write into notepad on the bluetooth connected PC.

However now I cannot get back into command mode to make changes to the Bluesmirf config. Trying to use the example code above I can see ‘`$$$U,9600,N`’ typed into notepad on the connected PC each time I load the sketch, rather than being used to enter command mode.

How do I get back into command mode after HID mode has been triggered.

title: Bluesmirf Mate Silver (RN-42) enter command mode when in HID mode

Answers: 1

body:
I believe that the problem is caused by the mode I entered. According to the [datasheet][1] on pg 10 Auto-Connect Master Mode (SM,3) enters high speed mode and this `connection cannot be broken via commands or software break characters`.
It goes on to explain that both Auto-Connect DTR Mode (SM,4) and Auto-Connect ANY Mode (SM,5) (which I used) function like Auto-Connect Master Mode (SM,3), so I guess that in these modes the `$$$` escape characters cannot be used to enter command mode either.

I was able to resolve this by performing a hard factory reset on the Bluesmirf Mate Silver (RN-42). I previously tried following a couple of you-tube tutorials that weren't very clear and didn't have any success. I looked at the [instructions in this thread][2] titled 'Factory Reset the RN-41 or RN-42' to get me on the right lines.

This worked for me:

 1. Connect the Bluesmirf Mate Silver GND pin to GND and disconnected all other pins
 2. Connect a wire to 3.3v on Ardunio
 3. Load the Ardunio with an empty sketch, and keep it powered on
 4. Touch the 3.3v wire repeatedly (3+ times) to the GPIO4/PIO4 connection hole on the Bluesmirf. This is a third of the way down one edge of the board.
 5. Factory reset should now be complete - note I didn't see any indication lights during this process.

Then I could wire up the Bluesmirf as normal and use ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

  [1]: https://cdn.sparkfun.com/datasheets/Wireless/Bluetooth/bluetooth_cr_UG-v1.0r.pdf
  [2]: https://learn.sparkfun.com/tutorials/using-the-bluesmirf/discuss#comment-55a587adce395f07568b4567


body:
I am experimenting with IR receive and transmit (basically I want my IOT to be able to turn on the TV, satellite receiver, and set the channel - yes, I am really that lazy).

I can receive and record the remote codes, and I can transmit the codes to an IR LED.

Now for the puzzle. I originally had my IR LED on Pin 13, but to clean things up I moved the output to pin 2 and changed the pin assignment in the sketch. Now it doesn't work. My phone camera shows that the IR LED is pulsing as before, but the appliance code is not working. Moving back to pin 13 and it works again.

So, what could be different between pins 13 or 2? I know that Pin 13 has the built-in LED but since I am setting it to output that shouldn't make a difference.

I am bit-banging to create the 38kHz pulses to the IR LED, so I am wondering if there is a latency difference from pins 2 and 13?

The sketch, since I know someone will ask for it:

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

    int IRledPin =  13;
    int buttonPin = 4;

    void setup()   {
      pinMode(IRledPin, OUTPUT);
      pinMode(buttonPin, INPUT);
      digitalWrite(buttonPin, HIGH); // pullup
      Serial.begin(115200);
    }

    void loop()
    {
      if (! digitalRead(buttonPin)) {
        // button down
        Serial.println("Sending IR signal");
        SendCode();
      }
    }

    // This procedure sends a 38KHz pulse to the IRledPin
    // for a # of microseconds.
    void pulseIR(long microsecs) {
      // we'll count down from the number of microseconds we are told to wait

      cli();  // this turns off any background interrupts
      while (microsecs > 0) {
        // 38 kHz is about 13 microseconds high and 13 microseconds low
        digitalWrite(IRledPin, HIGH);  // this takes about 3 microseconds
        delayMicroseconds(10);         // hang out for 10 microseconds
        digitalWrite(IRledPin, LOW);   // this also takes about 3 microseconds
        delayMicroseconds(10);         // hang out for 10 microseconds
        // so 26 microseconds altogether

        microsecs -= 26;
      }
      sei();  // this turns interrupts back on
    }

    void SendCode() {
      // This is the code for my FIOS FF
    Serial.println("FIOS- FFwd");
      pulseIR(9220);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(22320);
      pulseIR(9200);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2260);
      pulseIR(520);

    }

title: Output works on UNO Pin 13, but not on 2?

Answers: 1

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

    void SendCode() {
      // This is the code for my FIOS FF
      Serial.println("FIOS- FFwd");
      pulseIR(9220);
      delayMicroseconds(4540);

Personally I would be putting the `cli()` around everything in `SendCode` (apart from the Serial.println) because the serial print will cause interrupts, and they could occur between successive function calls there.

I checked your code using IDE 1.6.9 and got this pulse width for pin 2:

[![Pulse width on pin 2][1]][1]

And this pulse width on pin 13:

[![Pulse width on pin 13][2]][2]

You'll notice they are virtually identical and that neither show a frequency of 38 kHz. The measured period of 30.71 µs gives a frequency of 32.563 kHz.

Unless your version of the compiler generates different code than mine, I suggest you need to tweak your timing loops.

> I am wondering if there is a latency difference from pins 2 and 13?

No, I think not. The problem may be elsewhere, such as electrical. I suggest you try to measure the frequency of your timing loops using whatever external equipment you have to hand. For example, just call your pulseIR function constantly and measure with a frequency meter. I measured 32.555 kHz on my meter, for example.

---

## Use a timer to generate 38 kHz

You will get a more accurate 38 kHz signal if you use the hardware timers, properly configured. For example:

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

    const byte LED = 10;  // Timer 1 "B" output: OC1B
    const byte buttonPin = 4;

    // Clock frequency divided by 38 kHz frequency desired
    const long timer1_OCR1A_Setting = F_CPU / 38000L;

    void setup()   {
      pinMode(buttonPin, INPUT_PULLUP);
      pinMode (LED, OUTPUT);
      Serial.begin(115200);

      // set up Timer 1 - gives us 38.005 kHz
      // Fast PWM top at OCR1A
      TCCR1A = bit (WGM10) | bit (WGM11);                // fast PWM
      TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
      OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
      OCR1B =  timer1_OCR1A_Setting / 2 - 1;             // duty cycle
    }

    void loop()
    {
     if (! digitalRead(buttonPin)) {
        // button down
        Serial.println("Sending IR signal");
        SendCode();
        delay (200);
      }
    }

    // This procedure sends a 38KHz pulse to the IRledPin
    // for a # of microseconds.
    void pulseIR(const unsigned int microsecs) {
      TCCR1A |= bit (COM1B1); // clear OC1B on compare
      delayMicroseconds (microsecs);
      TCCR1A &= ~bit (COM1B1); // don't clear OC1B on compare
      digitalWrite (LED, LOW);
    }

    void SendCode() {
      // This is the code for my FIOS FF
      Serial.println("FIOS- FFwd");
      noInterrupts ();
      pulseIR(9220);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(4560);
      pulseIR(520);
      delayMicroseconds(4560);
      pulseIR(540);
      delayMicroseconds(4540);
      pulseIR(540);
      delayMicroseconds(22320);
      pulseIR(9200);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2240);
      pulseIR(540);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(520);
      delayMicroseconds(24684);
      pulseIR(9200);
      delayMicroseconds(2260);
      pulseIR(540);
      delayMicroseconds(24664);
      pulseIR(9220);
      delayMicroseconds(2260);
      pulseIR(520);
      interrupts ();
    }

This sets up Timer 1 to output 38 kHz, and then for the timing of the pulses you just turn its output on and off.

Note that you have to use D10 on your Uno because that is where Timer 1 outputs to.

---

For more information see [my page about timers](http://www.gammon.com.au/timers).

I have a graphic which shows a lot of the useful registers:

[![Timer 1 information][3]][3]

  [1]: https://i.stack.imgur.com/UtD6v.png
  [2]: https://i.stack.imgur.com/qunZi.png
  [3]: https://i.stack.imgur.com/xU8Nd.png


body:
I am trying to create a very simple menu to use with my lcd keypad shield, I have tried looking into how tutorials say to do this but I don’t really understand them.

Would it be possible to do it by doing something like creating an integer I.e menuTotal, that depending on the what the value of menuTotal is a menu item would display, then have the the up and down buttons add or subtract 1  of the menuTotal value.

Any help you can give would be greatly appreciated.

Liam

title: Creating a simple menu for Arduino LCD button shield

Answers: 1

body:
Your approach of holding the "current" menu selection and incrementing or decrementing upon external input (button press) is a sound approach.

Consider writing a `drawMenu()` function that draws the screen, based on the current menu. In your program, keep a `bool updateScreen` variable. Then, any time you get an external input that would change the screen, set the `updateScreen` variable to `true`.  The actual `drawMenu()` function, after drawing the screen, should reset the `updateScreen` variable back to `false`.

In your `loop()` function, have a section like:

    loop() {
      // [... other code ...]

      if (updateScreen) {
        drawMenu();
      }

      // [... other code ...]
    }

In this way, the screen is updated when necessary, and your main loop can keep running, processing input, etc.


body:
I'm new to the Arduino (I'm a developer but didn't have a chance to work with this kind of device before) and wanted to connect my ESP8266 to the Arduino Uno. I followed this [tutorial][1] but I got errors:

    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_memfailed
    error: espcomm_upload_mem_failed

I tried running WiFiScan from the examples. I've installed SiLabsUSB Driver (I'm on macOS) and tried different solutions across the internet and I couldn't make it work.
There are screenshots of the settings.

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

  [1]: http://www.instructables.com/id/Getting-Started-With-the-ESP8266-ESP-01/
  [2]: https://i.stack.imgur.com/otlnU.png
  [3]: https://i.stack.imgur.com/6xM4A.png

title: espcomm_sync failed when connecting ESP8266 (ESP-01)

Answers: 0


body:
I'm trying to use a DC motor with pinion engaged to a rack gear, and have that motor move a distance, save the distance, delay, reverse, and travel back the same distance from where it started, delay, do it again. I want to start/stop the initial save with a button push, then from those saves, loop the motor movement.

I have considered using a Hall effect sensor or reed switch to count, but it seems a software interrupt or timing is easier using `millis()`. I researched and found that `millis()` cannot be reset, so I'm wondering if this is possible.

I haven't started a sketch, but I got this idea from the BlinkWithoutDelay example sketch included with the Arduino IDE. Like, have the motor positioned at "home" position, button push, start the timer, motor travels to end of work piece, stop the timer, save that forward distance traveled into a variable, reverse the motor, (at this point the timer would be at 0 again for the reverse travel) travel back to "home" save that reversed distance traveled into another variable with a button push, and then use these start/stop values in a loop. So I would save the values with a button pushes, then just loop that.

Or I'm thinking about putting an if or while button push outside the loop with a nested `counter++`, eyeballing the motor travel, once it gets to where I want it, save those counts in variables, then using them in the loop to `analogWrite()` to the motor.

title: Using millis() to time the start / stop of a DC motor

Answers: 1

body:
You can't reset the `millis()` function, but you can count the amount of milliseconds and stop when necessary: beware though, the positioning might not be as precise as you wish and you have to consider the error will accumulate on the long run.

Nonetheless here is the code:

    uint16_t duration;
    bool direction = true;
    void loop() {
      if (duration != 0 and !buttonPressed()) {
        // running back and forth if setup and no "finish" button detect
        uint16_t start = millis(); // reset the timer
        startMotor(direction);
        while (millis() - start < duration && !buttonPressed()) {
          ; // keep going
        }
        direction = !direction; // reverse direction
      } else if (duration == 0) {
        // your motor positioning setup
        while (!buttonPressed()) {
          ; // wait for button to start positioning
        }
        uint16_t start = millis(); // ask for time
        startMotor(true); // run the motor cw
        while (!buttonPressed()) {
          ; wait for button to end positioning
        }
        duration = millis() - start; // store duration
        direction = false; // reverse motor direction
        // next time loop() is executed the motor will go back to home
      }
    }
    bool buttonPressed() {} // define this to determine if the button has been pressed, safer if you use an interrupt
    void startMotor(bool cw) {} // define this to run your motor clockwise or counterclockwise


body: The [Ticker](https://github.com/esp8266/Arduino/tree/master/libraries/Ticker) library for the ESP chips is quite useful, which wraps a `os_timer_t` object. I'd like to be able to see the time remaining on the timer, is it possible to do that witha `os_timer_t` object?

title: Time remaining with os_timer_t

Answers: 1

body:
The library just calls `os_timer_setfn` and `os_timer_arm` which will call the callback function after some time. To add the feature to see how many remaining time there is, you would need to extend the library (the `Ticker` class, specifically) to save a timestamp when the timer was started. You can then write a function which returns for how much time is remaining or has passed by doing `uint32_t remaining = timestamp_now() - timestamp_started`.

A good function to hook would be the `_attach_ms` in Ticker.cpp. Add a `uint32_t timestamp_started` variable in the `Timer.h` header for the class. Then set `timestamp_started = system_get_time()` (from `user_interface.h`). Then write a function `uint32_t remainingUs() { return system_get_time() - timestamp_started; }`. Beware of integer overflows -- `system_get_time` returns passed microseconds since µC startup.


body: I tried using millis, but I wanted to know if there is any better way to find out the exact time from when a function is called and finally when it terminates.

title: How can I find the time taken while a function is being called?

Answers: 3

body:
There is `micros()` which returns the number of microseconds the board has been active. But it rolls over much more frequently (a bit over an hour vs the month and a half for `millis()`)

    unsigned long preFunction = micros();
    foo();
    unsigned long timeElapsed = micros() - preFunction;

body:
Beyond the answer of ratchet freak, I also suggest to (for test only), put it in a loop and divide it to get a better result, like:

    unsigned long preFunction = micros();
    for (int i = 0; i < 1000; i++)
    {
      foo();
    }
    unsigned long timeElapsed = (micros() - preFunction) / 1000;

The number of repeats depend on the length of foo(), make sure it will not have a value beyond an unsigned long.

body:
The most accurate method would be to toggle a pin high right before the function, and low after.

If you than connect an oscilloscope or logic analyzer to the pin, you can measure the exact time it took for the function to execute.


body:
[![circuit][1]][1]

Using Arduino, how can I detect that the switch is on? I have access to the wire within the red rectangle only. That's because the switch is closely connected to the car body (ground). When the handbrake is up, the switch is pushed by a coil to touch car body and close the circuit. And when the handbrake is down, the switch go away from the car body and the circuit is open.
[![switch][2]][2]

  [1]: https://i.stack.imgur.com/zgn7r.png
  [2]: https://i.stack.imgur.com/xsQkE.jpg

title: Detect current in car handbrake circuit

Answers: 5

body: If you truly only have access to the red rectangle content, and not the Ground or +12V supply, you could use an opto-isolator, assuming you can use enough of the wire in the red rectangle to be able to form a voltage divider to get at least 1-2 mA through the input side of the opto.

body: Wrap the wire around a ferrite or some iron core and detect magnetic field.

body:
If you can modify the cabling, you can add a shunt resistor in series and measure the voltage drop between the terminals. This way you can measure the current draw that would be 0 if the switch is open and something if the switch is closed.
Other way you can use an ACS712 Current Sensor.

body:
Based on your comments:

"It's the handbrake switch button..." and "..if the switch is closed, the voltage would be zero as the ground, and if the switch is open, it will read 12 V.",

you could splice into the wire and use it as an input for the Arduino. You can NOT connect it directly to an Arduino because 5V is the maximum voltage permitted on a digital input (assuming your Arduino is running at 5V).

There are several ways to connect it to the Arduino safely, such as an opto-isolator, a level-shifter or using passive components.

This circuit using 2 resistors and a zener diode may work for you:

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

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

Be sure to connect the vehicle ground to the Arduino GND.

body:
After examining the answers provided by "Jose can u c", "Alberto Perro" and "VE7JRO", and the comments by "Mark Smith", It was clear to me that there are a lot of methods to use, but I found out that the simplest way is to just measure the voltage at any point within the red rectangle. While the circuit is close, it will read 0V, and while the circuit is open, it will read about 12V.
And of course we will use voltage divider to reduce the voltage to  about 4V, and 4.7 zener diode to protect Arduino's pin.

[![open circuit][1]][1]

[![closed circuit][2]][2]

  [1]: https://i.stack.imgur.com/5x9R3.png
  [2]: https://i.stack.imgur.com/hGFf7.png


body:
Can anybody tell me what drawmenu() means, I got an answer on here that has the term on and I don’t quite understand it, I’m very new to this.

Any help you can give will be greatly appreciated.

Liam

title: What does drawmenu() mean

Answers: 1

body:
I gave you [that particular answer][1]

The function `drawMenu()` has no meaning. I was suggesting that you **create** a function with that name, whose action is to write text to the LCD with your selected menu item. The name of the function is not relevant. It does not exist until you create it.

  [1]: https://arduino.stackexchange.com/questions/48904/creating-a-simple-menu-for-arduino-lcd-button-shield


body:
I want to print text and numbers mixed in a table with Serial.print(); from a char array. My problem is the conversion between the different data types. My idea is to print the data of the rows in a for loop with the variable i and the columns in a for loop with the variable j.

I have in the following example two variable, one is type integer and the second is a double. Now i want to add the values of the variables into the char-array, but I can't find a way to do this...

In my main program the variables need to have this data types and should be inserted later into the char array.

Does someone have a solution for this challenge?

Here is a small example code:

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

    char* myStrings[][6] = {"This is string 1", "This is string 2", "This is string 3",
                            "This is string 4", "This is string 5", "This is string 6"
                           };

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

    void loop() {

      //now put the integer and double variables into the char array in the second column

      //Print the values
      for (int i = 0; i < 2; i++)
      {

        for (int j = 0; j < 6; j++)
        {
          Serial.print(myStrings[i][j]);
          Serial.print("  ");
          delay(100);
        }
        Serial.println();
      }

    }

Many thanks in advance.

Guss

EDIT:
The output should look like this:
Headline (in this example it is the text "This is string 1", "This is string 2"...)
and then the values of the variables in the next row. It should be like this:

    This is String 1     This is String 2     This is String 3

    Variable a           Variable b           Variable int

    Variable double      Variable double      Variable int

title: Put integer and double into char array

Answers: 1

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

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

Here is the code.

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

    #include <Arduino.h>

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

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

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

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

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

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

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

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

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

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

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

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

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

     delay(5000);
    }

Two rounds give the output:

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

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

  [1]: https://stackoverflow.com/questions/27651012/arduino-sprintf-float-not-formatting


body: Im doing some experiments with Pocketlab and Arduino, Vacuum will get to around -30inHg. I tried with my raspberry pi and it just kept dying everytime a vacuum was pulled. The only problem I can image is the arduino heating up.

title: How well will the Arduino Uno survive in a vacuum?

Answers: 1

body:
Interesting question. You're right- heat is your enemy. Given the power dissipated by a Pi even when idle I'm not surprised it died. Most chips depend on convection to get rid of heat. A loaded Pi might require a (convective) heat sink and/or fan to keep it's core temperature down to an acceptable level, and that's at normal pressure and temperature. An Arduino -might- be able to work in a vacuum- it can lose some of it's heat through lead conduction- it'll only draw ~.25 watts normally vs 2.5 watts plus for a loaded Pi.

Ultimately it will depend on your application. If you have idle time when you can put the Arduino to sleep that will help keep it cool. If you have a conductive heat sink you can use then that would certainly help.


body:
I am trying to do a project on temperature control and found an example but cannot get the code to work. I have read forums and tried to fix the issue which is below the code.

Code:

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

    #include<DHT.h>      // Including library for dht
    #include<LiquidCrystal.h>
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    #define dht11dpin 12
    DHT11;
    #define pwm 9
    #byte degree[8] =
    {
      0b00011,
      0b00011,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000,
      0b00000
    };

    #void setup()
    {
      lcd.begin(16, 2);
      lcd.createChar(1, degree);
      lcd.clear();
      lcd.print("   Fan Speed  ");
      lcd.setCursor(0, 1);
      lcd.print("  Controlling ");
      delay(2000);
      analogWrite(pwm, 255);
      lcd.clear();
      lcd.print("Circuit Digest ");
      delay(2000);
    }

    void loop()
      DHT11.read(DHT11pin);
      int temp = DHT11.temperature;
      lcd.setCursor(0, 0);
      lcd.print("Temperature:");
      lcd.print(temp);   // Printing temperature on LCD
      lcd.write(1);
      lcd.print("C");
      lcd.setCursor(0, 1);
      if (temp < 26 )
      {
        analogWrite(9, 0);
        lcd.print("Fan OFF            ");
        delay(100);
      }
      else if (temp == 26)
      {
        analogWrite(pwm, 51);
        lcd.print("Fan Speed: 20%   ");
        delay(100);
      }
      else if (temp == 27)
      {
        analogWrite(pwm, 102);
        lcd.print("Fan Speed: 40%   ");
        delay(100);
      }
      else if (temp == 28)
      {
        analogWrite(pwm, 153);
        lcd.print("Fan Speed: 60%   ");
        delay(100);
      }
      else if (temp == 29)
      {
        analogWrite(pwm, 204);
        lcd.print("Fan Speed: 80%    ");
        delay(100);
      }
      else if (temp > 29)
      {
        analogWrite(pwm, 255);
        lcd.print("Fan Speed: 100%   ");
        delay(100);
      }
      delay(3000);
    }

Error:

<!-- language: lang-none -->

    In file included from C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:2:0:
    C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected unqualified-id before numeric constant
     #define DHT11 11
                   ^
    C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:6:1: note: in expansion of macro 'DHT11'
     DHT11;
     ^
    C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected initializer before numeric constant
     #define DHT11 11
                   ^
    C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:35:1: note: in expansion of macro 'DHT11'
     DHT11.read(DHT11pin);
     ^
    sketch_jan20b:36: error: request for member 'temperature' in '11', which is of non-class type 'int'
     int temp=DHT11.temperature;
                    ^
    sketch_jan20b:37: error: 'lcd' does not name a type
       lcd.setCursor(0,0);
       ^
    sketch_jan20b:38: error: 'lcd' does not name a type
       lcd.print("Temperature:");
       ^
    sketch_jan20b:39: error: 'lcd' does not name a type
       lcd.print(temp);   // Printing temperature on LCD
       ^
    sketch_jan20b:40: error: 'lcd' does not name a type
       lcd.write(1);
       ^
    sketch_jan20b:41: error: 'lcd' does not name a type
       lcd.print("C");
       ^
    sketch_jan20b:42: error: 'lcd' does not name a type
       lcd.setCursor(0,1);
       ^
    sketch_jan20b:43: error: expected unqualified-id before 'if'
       if(temp <26 )
       ^
    sketch_jan20b:50: error: expected unqualified-id before 'else'
         else if(temp==26)
         ^
    sketch_jan20b:57: error: expected unqualified-id before 'else'
          else if(temp==27)
          ^
    sketch_jan20b:64: error: expected unqualified-id before 'else'
          else if(temp==28)
          ^
    sketch_jan20b:71: error: expected unqualified-id before 'else'
         else if(temp==29)
         ^
    sketch_jan20b:77: error: expected unqualified-id before 'else'
          else if(temp>29)
          ^
    sketch_jan20b:83: error: expected constructor, destructor, or type conversion before '(' token
       delay(3000);
            ^
    sketch_jan20b:84: error: expected declaration before '}' token
     }
     ^
    exit status 1
    request for member 'temperature' in '11', which is of non-class type

title: Temperature control using a DHT11

Answers: 1

body:
It's a bit hard to see, but

    DHT11;

does not look like a correct statement, assuming DHT11 is a class (not a define like shown) it should be something like

    DHT11 dht;

where dht is an instance and you can use that.

Than in

    DHT11.read(DHT11pin);

you should replace it by

    dht.read(DHT11pin);


body:
I recently encountered a problem that's been bugging me for days. I want to make a project using a RFID reader and log data on an SD card with an Arduino Nano, but apparently no matter what I do, I can't seem to make them work together on SPI. They both work individually, and the SD shield works in parallel with the RFID reader, but the RFID doesn't work in parallel with the SD shield.

I'm absolutely sure that the wiring is correct, slave select on both modules are wired to different digital pins, and both are connected through bidirectional level shifters.

I noticed that the RFID reader works fine when I disconnect the MISO pin from the SD shield. I tried putting a diode between SD MISO and digital pin 12, I tried adding pullup resistors on both SS pins, I tried adding resistors on MISO lines, I tried pulling HIGH the SS i don't use, and low the one I want active. Nothing seemes to work and I'm out of ideas. The last thing I will try is conencting the modules on separate VCC, but I don't have faith that it will make any difference.

I hope someone has some advice for my problem.

Thanks in advance

title: Rfid reader and SD card shield won't work together

Answers: 2

body:
SD cards (or really their breakout boards) don't tend to obey the rules with regards to SPI. In particular the MISO pin isn't set to high impedance when the slave select is not selected.

You can fix this with a tri-state buffer that you feed the SD card's miso line to and controlled by the slave select. The output from the buffer goes to the arduino's MISO.

body:
The only way I could get it to work was to buy a separate SD logger shield (which contains an SD card via SPI).

When I used the SRAM (SPI) together with the SD card (SPI) it never did work. At least not on an Arduino (Uno or Mega).


body:
I'm thinking about making a custom Arduino-based mouse and I expect not to be the first one to have the idea. Does anybody know what speed I can expect to achieve? Suppose I use a mechanical mouse as a base, meaning I'll have to monitor 3 buttons and 3 axes (X, Y and wheel), debounce the signals coming from the buttons and transmit all that data via USB. How many times per second will I be able to do this, theoretically? Are there any projects which did something similar, and if so, what speed were they able to achieve?

To make a good mouse, I suppose I should at least beat my display's refresh rate which is 60 Hz, otherwise pointer movement won't be smooth. My current (commercially produced) mouse runs at 100 Hz.

title: How fast an Arduino mouse would be?

Answers: 0


body:
I have three RF24, all of them are connected to one arduino-uno each. The first one has sensors that sends data to the second one then the second one passes it to the third one. The first pass from RF24 #1 to RF24 #2 is successful but from the RF24 #2 to RF24 #3 there seems to be a problem.

Code for the RF24 #1 (I just copied the setup and loop the other functions are for the sensors, I think it's unnecessary):

    //Libraries for temperature
    #include <OneWire.h>
    #include <DallasTemperature.h>
    #define motor1 8
    // Data wire is plugged into port 2 on the Arduino
    #define ONE_WIRE_BUS 2
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
    OneWire oneWire(ONE_WIRE_BUS);

    // Pass our oneWire reference to Dallas Temperature.
    DallasTemperature sensors(&oneWire);

    //for pH meter
    #define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
    #define Offset 0.00            //deviation compensate
    #define LED 13
    #define samplingInterval 20
    #define printInterval 800
    #define ArrayLenth  40    //times of collection
    int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
    int pHArrayIndex = 0;

    //for NRF24L01
    RF24 radio(7, 8); // CE, CSN
    const uint64_t waddress = 0xB00B1E50D2LL;
    struct package {
      float temperature, ph, Do, inch, cm1;
    };
    typedef struct package Package;
    Package data;
    int LID = 4, LOD = 6;

    //for ultrasonic
    const int trigPin = 3;
    const int echoPin = 4;
    long duration, inches, cm, meter;

    void setup(void)
    {
      // start serial port
      radio.begin();
      radio.openWritingPipe(waddress);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();

      pinMode(LED, OUTPUT);
      // Start up the library
      sensors.begin();
    }

    /*
       Main function, get and show the temperature
    */

    void loop(void)
    {
      static unsigned long samplingTime = millis();
      static unsigned long printTime = millis();
      static float pHValue, voltage;
      if (millis() - samplingTime > samplingInterval)
      {
        pHArray[pHArrayIndex++] = analogRead(SensorPin);
        if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
        voltage = avergearray(pHArray, ArrayLenth) * 5.0 / 1024;
        pHValue = 3.5 * voltage + Offset;
        samplingTime = millis();
      }
      if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
      {
        digitalWrite(LED, digitalRead(LED) ^ 1);
        // call sensors.requestTemperatures() to issue a global temperature
        // request to all devices on the bus

        sensors.requestTemperatures(); // Send the command to get temperatures

        // After we got the temperatures, we can print them here.
        // We use the function ByIndex, and as an example get the temperature from the first sensor only.

        //Serial.print(pHValue,2);
        //Serial.print(",");
        //Serial.print(sensors.getTempCByIndex(0));

        radio.write(&data, sizeof(data));

        data.ph = (pHValue);
        data.temperature = (sensors.getTempCByIndex(0));
        Serial.print(data.ph);
        Serial.print(data.temperature);
        Serial.print(data.Do);
      }
    }

RF24 #2

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    RF24 radio(7, 8); // CE, CSN
    const uint64_t raddress = 0xB00B1E50D2LL;
    const uint64_t waddress = 0xB00B1E50B1LL;
    struct package {
      float temperature, ph, Do, inch, cm1;
    };
    typedef struct package Package;
    Package data;

    void setup() {
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(waddress);
      radio.openReadingPipe(1, raddress);
      radio.setPALevel(RF24_PA_MIN);
    }

    void loop() {
      radio.startListening();

      while (radio.available()) {
        radio.read(&data, sizeof(data));
        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);
      }
      if (radio.write(&data, sizeof(data))) {
        Serial.println(" delivery failed");
      }
      radio.stopListening();
      delay(200);
    }

RF24 #3

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    int lid = 2 , lod = 4;
    RF24 radio(7, 8); // CE, CSN
    const uint64_t raddress = 0xB00B1E50B1LL;
    struct package {
      float temperature, ph, Do, inch, cm1;
    };
    typedef struct package Package;
    Package data;

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

      radio.begin();
      radio.openReadingPipe(2, raddress);
      radio.setPALevel(RF24_PA_MIN);
      radio.startListening();
      pinMode(lid, OUTPUT);
      pinMode(lod, OUTPUT);
    }

    void loop() {
      unsigned long startTimer = millis();
      bool timeout = false;

      while (!radio.available() && !timeout) {
        if (millis() - startTimer > 500 )
        {
          timeout = true;
        }
        // radio.read(&temperature, sizeof(temperature));
        //radio.read(&Do, sizeof(Do));
      }
      if (timeout) {
        Serial.println("Failed to receive data");
      }
      else {
        radio.read(&data, sizeof(data));

        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);
      }
    }

The serial monitor for RF24 #2 displays:

     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
    6.92,28.25,7.20,15.00,38.00
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
     delivery failed
    6.91,28.25,7.20,15.00,38.00

RF24 #3 Serial Monitor:

    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00
    0.00,0.00,0.00,0.00,0.00

Sometimes RF24 #3 receives the data and prints it continuously. I don't know why. Most of the time it displays the above.

Edit: Revision

Update: It turns out that RF24 #3 continuous to print even if RF24 #2 is unplugged/not powered.

title: Having trouble passing data through RF24

Answers: 1

body:
You should always call `stopListening()` right before you `write()`. Also `write()` returns true when messages are delivered so your condition is wrong. Try changing the `loop()` in the second node to:

    void loop() {
      while (radio.available()) {
        radio.read(&data, sizeof(data));
        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);

        radio.stopListening();
        if (!radio.write(&data, sizeof(data))) {
          Serial.println("Delivery failed");
        }
        radio.startListening();
      }
    }

If a packet is available, it's read, printed and forwarded.
The third node's `loop()` should also be adjusted to something like:

    bool new_data = false;

    void loop() {
      if (radio.available()) {
        radio.read(&data, sizeof(data));

        Serial.print(data.ph);
        Serial.print(",");
        Serial.print(data.temperature);
        Serial.print(",");
        Serial.print(data.Do);
        Serial.print(",");
        Serial.print(data.inch);
        Serial.print(",");
        Serial.println(data.cm1);
        new_data = true;
      }
      if (new_data) {
        // do stuff
        new_data = false;
      }
    }

Data is sent in 32-byte payloads and your entire package is 20 bytes (without padding), assuming a float = 4 bytes. So a complete packet has either arrived or it hasn't; no point in waiting in one place. `new_data` lets you know when there's new stuff obviously and you clear the flag when you're done processing the data. This way, you can do other stuff while you wait for a packet to show.


body:
I was wondering the correct method to construct objects for use in the setup and loop scopes. I tried working constructing in the global scope, but I get garbage values printed to serial (probably from misusing pointers)? If I use the new keyword, then it works, but I heard that that is not best practice.

I is there a better way I should do this?

    // navigator.cpp

    #include "navigator.h"

    Navigator::begin(Waypoint* w, int count) {
      waypoints = w;
      pointCount = count;
      next = 0;          // start with first waypoint
      course = 90;       // Notice that initial course is due East

      Serial.println('here');
    }

-

    // navigator.h

    #define _navigator_h

    #if defined(ARDUINO) && ARDUINO >= 100
      #include "Arduino.h"
    #else
      #include "WProgram.h"
    #endif

    struct Waypoint {
      double lat, lon;
    };

    class Navigator {
    public:
      begin(Waypoint* w, int);
    };

    #endif

-

    // TransAt.ino

    #include "navigator.h"

    Waypoint w = { 43.36, -75.1 }; // These objects must be accessible in both setup() and loop(), but we can't use the new keyword
    Navigator nav();     // That means we have to do a lot of the heavy lifting here

    uint32_t timer = millis();

    void setup() {
      nav.begin(&w, 1);
    }

    void loop()
    {

    }

title: How to properly construct objects on ATmega2056?

Answers: 1

body:
>  I tried working constructing in the global scope, but I get garbage values printed to serial ...

Constructors in global scope are called before `init` and `setup` and thus are probably executing too soon for you. This would account for the garbage printed to serial, because your constructor is printing before the `Serial.begin()` call.

You can put constructors in global scope, however they should do fairly trivial things (eg. setting a counter to zero, or a pointer to NULL). Do not rely upon the system being initialized, thus do not call functions like `millis`, nor should you be using dynamic memory allocation at this point.

Most classes defer their "real" initialization to a `begin` function (eg. `Serial.begin`) because it is safe to do that, usually in the `setup` function.


body:
A few hours since I started messing with my first Arduino and I was trying to understand a small program and need some help. The program sends out the MAC address to the serial port. As it's little endian, the "printBufferReverse" reverses the buffer as shown below. But instead of sending this data to the serial port, how do I store the same data into a string variable? Thanks so much

    #include <bluefruit.h>
    void scan_callback(ble_gap_evt_adv_report_t* report)
    {
      uint8_t len = 0;
      uint8_t buffer[32];
      memset(buffer, 0, sizeof(buffer));

      // MAC is in little endian --> print reverse
      // NOTE: I want to store this into a string variable
      // NOTE: the reversing
      Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
      Serial.print("\n");

      /* TX Power Level */
      if (Bluefruit.Scanner.parseReportByType(report,
        BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
        {
          Serial.printf("s %i\n", "TX PWR LEVEL", buffer[0]);
          memset(buffer, 0, sizeof(buffer));
        }
    }

And the below line how do I store the data to a string instead of sending to serial port? It's adding a hypen to make the end result look like this:12-09-69-57-45-45-43-41-52-45-20

    Serial.printBuffer(report->data, report->dlen, '-');

I don't want to send this to serial port but to store in a string variable.

This is the board that I am using: https://www.adafruit.com/product/3406

## Complete code ##

    /*********************************************************************
     This is an example for our nRF52 based Bluefruit LE modules

     Pick one up today in the adafruit shop!

     Adafruit invests time and resources providing this open source code,
     please support Adafruit and open-source hardware by purchasing
     products from Adafruit!

     MIT license, check LICENSE for more information
     All text above, and the splash screen below must be included in
     any redistribution
    *********************************************************************/

    #include <bluefruit.h>

    /* For a list of EIR data types see:
     *    https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile
     *    Matching enum: cores/nRF5/SDK/components/softdevice/s132/headers/ble_gap.h */

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

      Serial.println("Scanning for beacons");
      Serial.println("------------------------------------\n");

      // Initialize Bluefruit with maximum connections as Peripheral = 0, Central = 1
      // SRAM usage required by SoftDevice will increase dramatically with number of connections
      Bluefruit.begin(0, 1);

      // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
      Bluefruit.setTxPower(4);

      /* Set the device name */
      Bluefruit.setName("Bluefruit52");

      /* Set the LED interval for blinky pattern on BLUE LED */
      Bluefruit.setConnLedInterval(250);

      /* Start Central Scanning
       * - Enable auto scan if disconnected
       * - Filter out packet with a min rssi
       * - Interval = 100 ms, window = 50 ms
       * - Use active scan (used to retrieve the optional scan response adv packet)
       * - Start(0) = will scan forever since no timeout is given
       */
      Bluefruit.Scanner.setRxCallback(scan_callback);
      Bluefruit.Scanner.restartOnDisconnect(true);
      Bluefruit.Scanner.filterRssi(-80);
      //Bluefruit.Scanner.filterUuid(BLEUART_UUID_SERVICE); // only invoke callback if detect bleuart service
      Bluefruit.Scanner.setInterval(160, 80);       // in units of 0.625 ms
      Bluefruit.Scanner.useActiveScan(true);        // Request scan response data
      Bluefruit.Scanner.start(0);                   // 0 = Don't stop scanning after n seconds

      Serial.println("Started ...");
    }

    void scan_callback(ble_gap_evt_adv_report_t* report)
    {
      uint8_t len = 0;
      uint8_t buffer[32];
      memset(buffer, 0, sizeof(buffer));
      boolean hasPayload;
      String bleDvcID;
      String advPayload;

      hasPayload = false;
      bleDvcID = "";
      advPayload = "";

      /* Display the timestamp and device address */
      /*
      if (report->scan_rsp)
      {
        Serial.printf("[SRd] Packet received from ", millis());
      }
      else
      {
        Serial.printf("[ADV�] Packet received from ", millis());
      }
      */
      // MAC is in little endian --> print reverse
      // bleDvcID = printBufferReverse(report->peer_addr.addr, 6, ':');
      // char buffer[18] = "";
      /*
        snprintf(buffer, "X-X-X-X-X-X", 18,
            report->peer_addr.addr[5],
            report->peer_addr.addr[4],
            report->peer_addr.addr[3],
            report->peer_addr.addr[2],
            report->peer_addr.addr[1],
            report->peer_addr.addr[0]
        );
       */
      Serial.printBufferReverse(report->peer_addr.addr, 6, ':');
      Serial.print("\n");

      /* Raw buffer contents */
      Serial.printf("s %d bytes\n", "PAYLOAD", report->dlen);
      if (report->dlen)
      {
        hasPayload = true;
        Serial.printf("s", " ");
        Serial.printBuffer(report->data, report->dlen, '-');
        Serial.println();
      }

      /* RSSI value */
      Serial.printf("s %d dBm\n", "RSSI", report->rssi);

      /* Complete Local Name */
      if(Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME, buffer, sizeof(buffer)))
      {
        Serial.printf("s %s\n", "COMPLETE NAME", buffer);
        if (strcmp((const char*)buffer, "Temperature Fren")==0)
        {
            Serial.println("Found beacon!");
        }
        memset(buffer, 0, sizeof(buffer));
      }

      /* TX Power Level */
      if (Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_TX_POWER_LEVEL, buffer, sizeof(buffer)))
      {
        Serial.printf("s %i\n", "TX PWR LEVEL", buffer[0]);
        memset(buffer, 0, sizeof(buffer));
      }

      /* Check for UUID16 Complete List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid16List(buffer, len);
      }

      /* Check for UUID16 More Available List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid16List(buffer, len);
      }

      /* Check for UUID128 Complete List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid128List(buffer, len);
      }

      /* Check for UUID128 More Available List */
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, buffer, sizeof(buffer));
      if ( len )
      {
        printUuid128List(buffer, len);
      }

      /* Check for BLE UART UUID */
      /*
      if ( Bluefruit.Scanner.checkReportForUuid(report, BLEUART_UUID_SERVICE) )
      {
        Serial.printf("s %s\n", "BLE UART", "UUID Found!");
      }
      */
      /* Check for DIS UUID */
      /*
      if ( Bluefruit.Scanner.checkReportForUuid(report, UUID16_SVC_DEVICE_INFORMATION) )
      {
        Serial.printf("s %s\n", "DIS", "UUID Found!");
      }
      */
      /* Check for Manufacturer Specific Data */
      /*
      len = Bluefruit.Scanner.parseReportByType(report, BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, buffer, sizeof(buffer));
      if (len)
      {
        Serial.printf("s ", "MAN SPEC DATA");
        Serial.printBuffer(buffer, len, '-');
        Serial.println();
        memset(buffer, 0, sizeof(buffer));
      }
      */
      Serial.println();
    }

    void printUuid16List(uint8_t* buffer, uint8_t len)
    {
      /* Serial.printf("s %s", "16-Bit UUID"); */
      for(int i=0; i<len; i+=2)
      {
        uint16_t uuid16;
        memcpy(&uuid16, buffer+i, 2);
        /* Serial.printf("X ", uuid16); */
      }
      /* Serial.println(); */
    }

    void printUuid128List(uint8_t* buffer, uint8_t len)
    {
      (void) len;
      /* Serial.printf("s %s", "128-Bit UUID"); */

      // Print reversed order
      for(int i=0; i<16; i++)
      {
        const char* fm = (i==4 || i==6 || i==8 || i==10) ? "-X" : "X";
        /* Serial.printf(fm, buffer[15-i]); */
      }

      /* Serial.println(); */
    }

    void loop()
    {
      // Toggle both LEDs every 1 second
      digitalToggle(LED_RED);

      delay(1000);
    }

title: Buffer reverse to string

Answers: 1

body:
You can do it with snprintf_P:

    char mac[18];

    snprintf_P(mac, 18, (PGM_P)F("X-X-X-X-X-X"),
        report->peer_addr.addr[5],
        report->peer_addr.addr[4],
        report->peer_addr.addr[3],
        report->peer_addr.addr[2],
        report->peer_addr.addr[1],
        report->peer_addr.addr[0]
    );

That is, assuming that `report->peer_addr.addr` is an array of 6 bytes.

If your strange board doesn't support the `_P` variants of string manipulation functions then you can drop that part along with the `(PGM_P)F(...)` bit:

    char mac[18];

    snprintf(mac, 18, "X-X-X-X-X-X",
        report->peer_addr.addr[5],
        report->peer_addr.addr[4],
        report->peer_addr.addr[3],
        report->peer_addr.addr[2],
        report->peer_addr.addr[1],
        report->peer_addr.addr[0]
    );

Doing so on an Ardunio, though, would waste RAM.


body:
I am reading an input from my Ohaus weighing scale using it's RS232 output using this code:

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

    #define HWSERIAL Serial1

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

    void loop() {
      int incomingByte;

      if (Serial.available() > 0) {
        incomingByte = Serial.read();
        Serial.print("USB received: ");
        Serial.println(incomingByte, DEC);
        //HWSERIAL.print("USB received:");
        //HWSERIAL.println(incomingByte, DEC);
      }
      if (HWSERIAL.available() > 0) {
        incomingByte = HWSERIAL.read();
        Serial.print("UART received: ");
        Serial.println(incomingByte);
        //HWSERIAL.print("UART received:");
        //HWSERIAL.println(incomingByte);
      }
    }

When pressing the print button on the scale, I was expecting data to come over in single burst with just the readings, but what I am getting is the expected data, but the scale keeps sending data afterwards (ES over and over). I need to parse out just what's needed. The below is the output from the console on my computer.

    UART received:
    UART received:
    UART received:
    UART received:
    UART received: 0
    UART received: .
    UART received: 0
    UART received: 0
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received: ?
    UART received: (This is a CR)

    UART received: (This is a LF)

    UART received:
    UART received:
    UART received:
    UART received:
    UART received: 0
    UART received: .
    UART received: 4
    UART received: 0
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received:
    UART received: ?
    UART received: G
    UART received:
    UART received:
    UART received: (CR)

    UART received: (LF)

    UART received: E
    UART received: S
    UART received: (CR)

    UART received: (LF)
    ... (The ES loops over and over until the print button is pressed again)

0.00 is the current scale reading and 0.40 is the tare weight. That's all I need and I can't figure out how to parse it. The blocks aren't the same length so how do I pull out the needed information and ignore the repetitive 'ES'? I'm not 100% sure if I'm even going about this the right way?

Output as DEC

    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 48
    UART received: 46
    UART received: 48
    UART received: 48
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 63
    UART received: 13
    UART received: 10
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 48
    UART received: 46
    UART received: 52
    UART received: 48
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 32
    UART received: 63
    UART received: 71
    UART received: 32
    UART received: 32
    UART received: 13
    UART received: 10
    UART received: 69
    UART received: 83
    UART received: 13
    UART received: 10
    UART received: 69
    UART received: 83
    ...

title: Reading Arduino Serial Input

Answers: 1

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

> The balance will return “ES” for invalid commands.

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


body:
I'm working on a small car (<1 kg) which will drive when there is light and stop when there isn't. Below is a plan with code drawn up (the only numbers I know for sure are the current gains for the TIP31C transistor and the rated load current of the 6 V motor I'm using). I'm going to map the analog voltages to a digital signal output.

I read that the maximum digital output was 40 mA and also that `analogWrite` gives a pulse width modulation (PWM) which can be set to 100% (255) [the code: `outputval/1`], 50% (127) [the code: `outputval/2`]. I'm concerned with the lack of control I have here over the current. Will Arduino by default draw 7.75 mA maximum if the input signal is high [giving the output signal also as high]? If not, can I control the current in this manner reliably? Also are there anything I should worry about if I added another 6 V motor in parallel? Coding and electrical suggestions greatly welcomed.

TIP31 transistor: http://www.hobbytronics.co.uk/datasheets/TIP31.pdf

6 V dc motor: http://www.kysanelectronics.com/graphics/RF-370CA-22170.pdf

maximum digital output: https://www.arduino.cc/en/Tutorial/DigitalPins

PWM: https://www.arduino.cc/en/Tutorial/PWM

[![the plan][1]][1]

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

The code:

    const int transistorbase = 9;
    void setup() {
      //set the base as digital output:
      pinMode(transistorbase, OUTPUT);
    }
    void loop() {
      //read voltage at divider:
      int inputval=analogRead(A0);
      //map voltage to digital
      int outputval=map(inputval,0,1023,0,255);
      //control transistor:
      analogWrite(transistorbase,outputval);
    }

tl;dr
Codewise, how do I control the digital output current to my needs? Am I seeing ghosts?

title: Light Powered Motor Troubles

Answers: 1

body:
I would take a simple n-channel MOSFET like [this one][1]. At 5V on the gate it can drive up to 8A (so you have plenty of space to connect other motors as long as your power source can handle this) and because it is a MOSFET you don't have to draw much current from the Arduino (only enough to load the gate of the MOSFET). You can also hold the current under the critical value for your motor with a simple resistor (fit for the resulting power dissipation) in series.

Yes, the output of the PWM is 5V - the operation voltage of the Arduino. The whole point in PWM is to use only the digital values (here 0V and 5V) and varying so fast, that slow systems as the motor cannot follow this motion, but summing over the impulses. So the motor gets only very fast kicks. And for a normal motor you don't need fast PWM. This only increases the frequency response from the MOSFET.

The code seems for to me.

  [1]: https://www.mouser.com/ds/2/308/BUZ11-1118746.pdf


body:
In the first program after removing hand from the button it keeps on, means it keeps applying what is in the loop:

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

    int led = 13;
    int button = 12;
    void setup() {
      pinMode(led, OUTPUT);
      pinMode(button, INPUT);
                 }
    void loop() {
      if (digitalRead(button) == HIGH)
      {
        digitalWrite(led, HIGH);
      }
                 }

while in the second one it needs to press the button every time in order to apply what is in the loop,means to flash in this case,

    int led = 13;
    int button = 12;
    void setup() {
      pinMode(led, OUTPUT);
      pinMode(button, INPUT);
                }
    void loop() {
      if (digitalRead(button) == HIGH)
      {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }
               }

Why different behavior although the same structure?

The problem is illustrated in this video :
https://www.youtube.com/watch?v=u5WGvKwJYFY&t=2s

title: Why the program keeps applying what is in loop in first case and stops in the second one?

Answers: 2

body:
You read `value` only once ... what do you expected?

In the first sketch, you put the LED ON and never turn it OFF, no matter what.

In the second sketch, you put the LED ON and one second later you turned it OFF. As the `value` doesn't change, it keeps repeating.

You mistake: you read the button in `setup`. You have to read in each `loop` iteration.

    void loop() {
      value = digitalRead(button);
      if (value == HIGH)
      {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }

body:
This iteration of your code is better.  Now, the difference in behavior is that nothing in the first code ever executes `digitalWrite(led, LOW);`, while each iteration though the second code does.  Therefore the LED remains on forever in code 1, and depends on the button press in code two.

If the behavior you desire is that the code remembers if the button has ever been pressed, latch that event in some state variable, and then in `loop()`, act on the value of the state variable:

    int led = 13;
    int button = 12;
    int everHit = 0;
    void setup() {
      pinMode(led, OUTPUT);
      pinMode(button, INPUT);
    }

    void loop() {
      if (digitalRead(button) == HIGH) everHit = 1;
      if (everHit) {
        digitalWrite(led, HIGH);
        delay(1000);
        digitalWrite(led, LOW);
        delay(1000);
      }
    }


body:
Good day! I seem to be having trouble creating multiple tables with EDB. I am using Arduino UNO and SD Card module to save my db.

Here is my Serial.

[![Here is my serial][1]][1]
[1]: https://i.stack.imgur.com/ip89i.png

Here is my table declaration.

    struct LogEvent {
      int id;
      String fname;
      float temperature;
    }
    logEvent;

    struct SecondEvent {
      int id;
      String lastname;
    }
    secondEvent;

Here is my db.create() code.

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

Now, when I try to retrieve, it is a whack. Here is my save and retrieve code.

    void createRecords(int num_recs, float correctTemperature)
    {
        Serial.print("Creating Records... ");
        for (int recno = 1; recno <= num_recs; recno++)
        {
          correctId++;
          logEvent.id = correctId;
          logEvent.fname = "Brix Nicholson";
          logEvent.temperature = correctTemperature;
          secondEvent.id = correctId;
          EDB_Status result = db.appendRec(EDB_REC logEvent);
          if (result != EDB_OK) printError(result);
        }
      Serial.println("DONE");
    }

    void createRecordSecondEvent()
     {
       correctId++;
       secondEvent.id = correctId;
       secondEvent.lastname = "Secretaria";
       EDB_Status result = db.appendRec(EDB_REC secondEvent);
       if (result != EDB_OK) printError(result);
     }

    void selectLastRecord()
    {
      int lastRecNum = db.count();
      EDB_Status result = db.readRec(lastRecNum, EDB_REC logEvent);
      if(result == EDB_OK)
       {
         Serial.print(" ID: ");
         Serial.print(logEvent.id);
         Serial.print(" Name: ");
         Serial.print(logEvent.fname);
         Serial.print(" Temp: ");
         Serial.println(logEvent.temperature);
       }
       else printError(result);
    }

    void selectLastSecondRecord()
    {
     int lastRecNum = db.count();
     EDB_Status result = db.readRec(lastRecNum, EDB_REC secondEvent);
     if(result == EDB_OK)
      {
       Serial.print("Second Event ID: ");
       Serial.print(secondEvent.id);
       Serial.print("Last Name: ");
       Serial.print(secondEvent.lastname);
      }
      else printError(result);
    }

title: EDB. Is it possible to create multiple tables with db.create()?

Answers: 2

body:
I think I have found the answer to my problem. I forgot to increase the address of the EDB_header.

I wrote:

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

Instead of:

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

body:
> I think I have found the answer to my problem. I forgot to increase
> the address of the EDB_header.

you're right about increasing the address of EDB_header.
But the address is the position from where the library starting reading/writing.

if you have a look at
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L66
and
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L34

the library writes a fixed size of the header in the binary format
which includes

 1. a magic byte to recognize the EDB header
 2. the number of records currently present in the table which is 0 at of this time
 3. size of your single record
 4. the size of the table (max amount of memory that the table is allowed to consume)

and to write a new record
https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L93

so in

    db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
    db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

the second statement will override the old header excluding the first byte (0'th position)

the solution to your problem will be

    unsigned int FIRST_TABLE_HEADER_POSITION = 0;
    db.create(FIRST_TABLE_HEADER_POSITION, FIRST_TABLE_SIZE, (unsigned int)sizeof(logEvent));

    unsigned int SECOND_TABLE_HEADER_POSITION = FIRST_TABLE_HEADER_POSITION + (unsigned int)sizeof(EDB_Header) + FIRST_TABLE_SIZE;

    db.create(SECOND_TABLE_HEADER_POSITION, SECOND_TABLE_SIZE, (unsigned int)sizeof(secondEvent));

now you can use

    EDB_Status result = db.open(FIRST_TABLE_HEADER_POSITION );
and

    db.close();
    EDB_Status result = db.open(SECOND_TABLE_HEADER_POSITION );