body:
> Is there a way to do that.

sure.

one way to do it is to use a pin to indicate which program you want to execute.

    uint8_t execution_switch=0;  //execution switch. 0->run setup0()/loop0(), 1->run setup1()/loop1()

    void setup(void) {
      pinMode(EXECUTION_SWITCH, INPUT_PULLUP); //execution switch as input + pullup
      execution_switch=(digitalRead(EXECUTION_SWITCH)==LOW)?0:1;
      if (execution_switch==0) setup0(); else setup1();
    }

    void loop(void) {
      if (execution_switch==0) loop0(); else loop1();
    }

you can easily change it to accommodate multiple programs / multiple switch pins, or real time switch, ....


sender: user

message:
How to skip the first line and output the second?

My question is related to my previous [question][1].
These encoder programs outputs two line per pule/tick.

Here is the part of the code I want to use:

    void loop()
    {
        // Read the status of the inputs
        debouncerA.update();
        debouncerB.update();

        int8_t EncVariation = 0;

        if (debouncerA.rose())
        { // if input A changed from low to high, it was CW if B is high too
            EncVariation = (debouncerB.read()) ? 1 : -1;
        }
        else if (debouncerA.fell())
        { // if input A changed from high to low, it was CW if B is low too
            EncVariation = (debouncerB.read()) ? -1 : 1;
        }
        else if (debouncerB.rose())
        { // if input B changed from low to high, it was CCW if A is high too
            EncVariation = (debouncerA.read()) ? -1 : 1;
        }
        else if (debouncerB.fell())
        { // if input B changed from high to low, it was CCW if B is low too
            EncVariation = (debouncerA.read()) ? 1 : -1;
        }
    //
      if (EncVariation != 0) {

            encoder0Pos = encoder0Pos + EncVariation;

            int degs = (encoder0Pos * 6) % 360 ;

            if(degs<0){ degs = 360 + degs; }

            Serial.println (degs);
       }
    }

For **three** inputs/ticks this outputs like:

6

12

18

24

30

36

But I only need the second ones like:

12

24

36

How can I do that?
(I need it to send the relevant data do a PC.)

I spend so long time on it couldnt find any solution.

  [1]: https://arduino.stackexchange.com/questions/33607/problem-to-convert-rotary-encoder-output-to-angle

sender: assistant

body:
*IF* and only IF you want exactly what you have asked for which is alternate lines not to be output then this is a very crude and quick solution.

Outside of `loop()` add this declaration:

    bool skipNextLine = true;  // true skips the odd lines, false skips even lines

And change the end of your code like this:

      if (EncVariation != 0) {
        encoder0Pos = encoder0Pos + EncVariation;
        int degrees = (encoder0Pos * 6) % 360 ;
        if(degrees<0){ deg = 360 + degs; }
        if (!skipNextLine)
        {  // This will skip alternate lines
            Serial.println (deg);
            skipNextLine = true;
        }
        else
        {
            skipNextLine = false;
        }
      }


body: Use a static variable to count loop execution and only prohibit the very first of every 3 counts.


message:
Define a string with single quotation marks?

This is kind of a short question. All I want to know is, if I can define a string using single quotation marks ('), instead of the regular ones("). I want to use it in a function like this:
print('Hello world');

I unfortunately do not have an Arduino nearby so I cannot test it myself.

body: **No**, you cannot. This rules comes from the basic C++ syntax on which the Arduino platform is built.


body:
No, you can't.  `'x'` defines a single character or integer (note: `'ab'` is a two-byte single value [integer] made up from the ASCII values of both characters).

To include `"` within a string you have two options:

1. Escape the `"` with `\`, as in: `char foo[] = "He said \"Hello there\".";`
2. Use "raw strings" if the compiler is configured to support it: `char foo[] = R"(He said "Hello there".)";`

Option 1 is the most portable since it doesn't require compiler support for modern C++ standards. However it's the hardest to read, especially when you get lots of escapes in the same string.

You can make it more readable by defining QUOTE:

    #define QUOTE "\""

    char foo[] = "He said " QUOTE "Hello there" QUOTE ".";


message:
MCP23017 and stepper motors

I am new to Arduino and programming and I am muddling along with some tutorials, I have a little project I am working on. It's basically an LCD screen with 5 buttons, a simple menu system that will control some stepper motors.

Now I have been able to both program and run the LCD from the Arduino and program and run the stepper motors. This was pretty straightforward due to the abundance of information. Now due to the small number of inputs on the Uno I knew I would need to expand on these so I bought some MCP23017 I/O expander chips.

Setting up the LCD on the MCP23017 was easy enough again due to the lots of tutorials and libraries, but I just cannot figure out how to work a stepper motor via the MCP23017. I am using 28BYJ-48 stepper motors and ULN2003 stepper driver boards. Yes I know cheap and nasty but they are fine for my task.

So I am basically looking for a little help on how to run stepper motors through the MCP23017 chips. I have the wiring and connections set up, just need some help on the programming.

body:
I couldn't understand what the problem is, since you already managed to connect an LCD to it... Anyway...

To run a stepper motor you have to first define the control technique. AFAIK there are a few, but the ones I know are

 - full step
 - rotated full step
 - half step
 - microstep

Your motor is a unipolar motor. You have to connect the common wire to +5V, the other ones to one transistor of the ULN2003, and each transistor should be directly controlled by one pin. These are called phases (and let's call these PH1, PH2, PH3 and PH4).

Now for the explanation I'll use some tables. In these tables, each row is a step, each column a pin, and if there is a X the transistor should be on during that step.

Now, the full step technique is the simplest one. It consists of four phases:

    Step PH1 PH2 PH3 PH4
      1   X
      2       X
      3           X
      4               X

As you can see, you just have to power each phase through each step. Cycling the steps as 1-2-3-4-1-2-3... will rotate in one sense, 4-3-2-1-4-3-2... in the other.

The rotated full step technique powers two phases at each step:

    Step PH1 PH2 PH3 PH4
      1   X   X
      2       X   X
      3           X   X
      4   X           X

This usually gives a higher current consumption, but also higher torque.

The half step is a mix of the two:

    Step PH1 PH2 PH3 PH4
      1   X
      2   X   X
      3       X
      4       X   X
      5           X
      6           X   X
      7               X
      8   X           X

As you can see, the number of steps per cycle is twice as much. This means that you can increase the accuracy (since a 32 steps/rev motor will now require 64 steps to perform a complete revolution).

The microstepping technique requires a different hardware, since it better controls the current in the phases to further divide each step in different steps.

Anyway, a basic implementation using the MCP23017 and the full step technique can be this one. I used Adafruit's library, but you can change using whatever library you chose or the direct calls you used for the LCD.

    #include <Wire.h>
    #include "Adafruit_MCP23017.h"
    Adafruit_MCP23017 mcp1;

    const byte PH1 = 0, PH2 = 1, PH2 = 3, PH3 = 4;

    const byte phasesTable[][] = {
     { HIGH, LOW,  LOW,  LOW  },
     { LOW,  HIGH, LOW,  LOW  },
     { LOW,  LOW,  HIGH, LOW  },
     { LOW,  LOW,  LOW,  HIGH }
     };

    int currentPosition, targetPosition;
    unsigned long previousMillis;
    const int StepDelayMs = 100; // delay between steps

    void setup()
    {
     mcp1.begin(0);
     mcp1.pinMode(PH1, OUTPUT);
     mcp1.pinMode(PH2, OUTPUT);
     mcp1.pinMode(PH3, OUTPUT);
     mcp1.pinMode(PH4, OUTPUT);
     currentPosition = -1; // force first update
     targetPosition = 0;
    }

    void loop()
    {
     void updatePosition(); // function prototype
     updatePosition(); // execute the update

     // ----------------------
     // Functional part
     // ----------------------
     // Edit this code according to your application
     // changing the targetPosition variable (DON'T CHANGE
     // the currentPosition variable

     if (currentPosition == targetPosition)
     {
      if (targetPosition == 50)
       targetPosition = 0;
      else
       targetPosition = 50;
     }
    }

    void updatePosition()
    {
     if ((millis() - previousMillis) > StepDelayMs)
     {
      previousMillis += StepDelayMs;

      if (targetPosition != currentPosition)
      {
       if (targetPosition < currentPosition)
        currentPosition--;
       else
        currentPosition++;

       byte phIdx = currentPosition % (sizeof(phasesTable) / sizeof(phasesTable[0]));

       mcp1.digitalWrite(PH1, phasesTable[phIdx][0]);
       mcp1.digitalWrite(PH2, phasesTable[phIdx][1]);
       mcp1.digitalWrite(PH3, phasesTable[phIdx][2]);
       mcp1.digitalWrite(PH4, phasesTable[phIdx][3]);
      }
     }
    }

NOTE: I did not test this code, but I'm pretty confident it should work. Maybe there are some bugs left, however, but you should be able to correct them yourself.

The program behaves this way: every 100ms (you can go a bit faster, but sometimes you can lose steps, so you have to test it) it checks if the motor has reached the final position he needs to reach (`targetPosition`). If it has, the program does nothing. Otherwise it moves one step towards the target. All this is managed in the `updatePosition` function.

You have to call this in the loop (and make a NON BLOCKING loop, otherwise also the motor will block). In the loop, modify the target position that you need to reach (the part I called `Functional part`). In the example, the program moves the motor 50 steps back and forth (so 50 steps in one direction, then back to the origin, then to 50 and so on).

The control technique used is the full step. If you want to use another, change the `phasesTable` constant variable.

If you need more functionalities, there are a lot of libraries for the steppers. Just use the proper commands to edit the pins on the MCP rather than the ones on the board.


message:
Melzi 2.0 Board Firmware Upload problem

I'm trying to flash the repetier Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. I uploaded it successfully 2 days ago with same settings  but now is failing always.

    @avrdude -p m1284p -b57600 -c arduino -P COM%x% -e -U flash:w:%filename%.hex
    avrdude: AVR device initialized and ready to accept instructions
    Reading | ################################################## | 100% 0.02s
    avrdude: Device signature = 0x1e9705 (probably m1284p)
    avrdude: erasing chip
    avrdude: reading input file "newa.hex"
    avrdude: input file newa.hex auto detected as Intel Hex
    avrdude: writing flash (114266 bytes):
    Writing |                                                    | 0% 0.00s
    avrdude: stk500_paged_write(): (a) protocol error, expect=0x14, resp=0x64
    avrdude: stk500_recv(): programmer is not responding

How do I solve this problem?

body:
The [Electronics Stackexchange](https://electronics.stackexchange.com/) question *[avrdude error - stk500_paged_write() protocol error](https://electronics.stackexchange.com/q/67945)* has answers that suggest three different tactics for protocol errors:

• Upgrade the Arduino IDE from 1.00 to 1.05, or install "AVR-GCC Toolchain" via Homebrew;
• Disconnect everything from TX / RX (Arduino digital pins 0 and 1);
• Use shorter or different USB cables, hooked to a USB port on computer instead of on a hub

I've seen dozens of answers here on arduino.stackexchange with such suggestions, as well as webpages elsewhere with ideas like those in [an answer to *AVRDUDE Error (Arduino Leonardo)*](https://forum.arduino.cc/index.php?topic=84566.0).

You could go through this list of programmer-is-not-responding arduino.stackexchange questions, and report back on what works and what doesn't:

• ["avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program](https://arduino.stackexchange.com/q/17),
• [How do I resolve "avrdude: stk500_recv(): programmer is not responding"?](https://arduino.stackexchange.com/q/17827),
• [avrdude: stk500_recv(): programmer is not responding after serial](https://arduino.stackexchange.com/q/33182),
• [avrdude: stk500_recv(): programmer is not responding + avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x47](https://arduino.stackexchange.com/q/18988),
• [avrdude: stk500_rcv :programmer is not responding](https://arduino.stackexchange.com/q/18172),
• [Arduino Nano Update failure - avrdude: stk500_recv(): programmer is not responding](https://arduino.stackexchange.com/q/25122),
• [avrdude: stk500_getsync(): not in sync: resp=0x00](https://arduino.stackexchange.com/q/1585),
• [Arduino Uno cannot upload any sketch: avrdude: stk500_recv(): programmer is not responding](https://arduino.stackexchange.com/q/17985),
• ["avrdude: stk500_recv(): programmer is not responding" when uploading sketch](https://arduino.stackexchange.com/q/28600),
• [Arduino not working / not uploading [duplicate]](https://arduino.stackexchange.com/q/18993),
• [Problems uploading sketch to Arduino Due](https://arduino.stackexchange.com/q/12540),
• [FTDI stdk 500k not responding](https://arduino.stackexchange.com/q/20656),
• [Arduino Prototype on Breadboard: "avrdude: stk500_recv(): programmer is not responding"](https://arduino.stackexchange.com/q/22304),
• [Arduino Nano - programmer is not responding](https://arduino.stackexchange.com/q/18194),
• [How do I resolve "avrdude: stk500_recv(): programmer is not responding"?](https://arduino.stackexchange.com/q/17827/how-do-i-resolve-avrdude-stk500-recv-programmer-is-not-responding),
• [Arduino not in sync unique error](https://arduino.stackexchange.com/q/23552),
• [Arduino nano stopped working](https://arduino.stackexchange.com/q/13620),
• [Not in sync: resp=0x00](https://arduino.stackexchange.com/q/5022),
• [How to troubleshoot the Arduino Mini and Arduino usb2serial?](https://arduino.stackexchange.com/q/15921),
• [Atmega328P-PU: Programmer is not responding](https://arduino.stackexchange.com/q/12104),

Note, click the “see more linked questions…” link in the sidebar to get a nice webpage with the above list and the opening lines of each question.


message:
Which timer does Arduino Nano use for each PWM pin?

I'm unable to find which Timer controls each PWM pin (3, 5, 6, 9, 10 and 11) in an Arduino Nano Board (ATmega328).
Any guesses?

Thanks in advance,

Eduardo

body:
This is a good pinmapping picture of the Nano : [www.pighixxx.com/test/portfolio-items/nano/][1]

A timer has sometimes two outputs, A and B. The pins with OC0A and OC0B are timer outputs of Timer0. OC1A and OC1B are Timer1, OC2 and OC2B are Timer2.

Everything is also in the datasheet of the ATmega328P, but that picture is a lot easier.

  [1]: http://www.pighixxx.com/test/portfolio-items/nano/


message:
Is there an advantage to set pinmodes via bitmask and register?

I'm working with the capacitive sensor library currently and the author does not use `digitalWrite()`, but instead sets the output of a pin via functions changing the bitmasks of certain registers:

https://github.com/PaulStoffregen/CapacitiveSensor/blob/master/CapacitiveSensor.h#L39

I looked into the [OneWire library description][1] those functions come from, but I still can't see any advantage over simply using the standard way Arduino proposes.

  [1]: http://playground.arduino.cc/Learning/OneWire

body:
With direct access to the pin registers, there is no need to call a function (since the `digitalWrite` function itself calls some functions), which is slower than manipulating the bits directly. You are also able to set the bits of several ports at the same time.

The manipulation of port registers is described [in the PortManipulation chapter](https://www.arduino.cc/en/Reference/PortManipulation). It states:

> Generally speaking, doing this sort of thing is not a good idea

However it could/should be used for time-sensitive applications. [This](http://jeelabs.org/2010/01/06/pin-io-performance/) is an interesting read on this topic.


body:
The reason for using direct port operations in capacitive-sensor code is that such code works ok, and slower code won't.  Here's an extract from [CapacitiveSensor.cpp](https://github.com/PaulStoffregen/CapacitiveSensor/blob/master/CapacitiveSensor.cpp) in Stoffregen's CapacitiveSensor code:

    int CapacitiveSensor::SenseOneCycle(void) {
        noInterrupts();
     DIRECT_WRITE_LOW(sReg, sBit); // sendPin Register low
     DIRECT_MODE_INPUT(rReg, rBit); // receivePin to input (pullups are off)
     DIRECT_MODE_OUTPUT(rReg, rBit); // receivePin to OUTPUT
     DIRECT_WRITE_LOW(rReg, rBit); // pin is now LOW AND OUTPUT
     delayMicroseconds(10);
     DIRECT_MODE_INPUT(rReg, rBit); // receivePin to input (pullups are off)
     DIRECT_WRITE_HIGH(sReg, sBit); // sendPin High
        interrupts();

     while ( !DIRECT_READ(rReg, rBit) && (total < CS_Timeout_Millis) ) {  // while receive pin is LOW AND total is positive value
      total++;
     }
    //...
    }

The general idea is that a source pin and receive pin are driven low, briefly, to discharge associated capacitance.  Immediately upon changing the receive pin to an input we want to change the source pin high, and begin counting the total number of cycles that elapse before the receive pin charges to above about 2.5 V.

Code using `digitalWrite()`, `digitalRead()`, and `pinMode()` calls at four to five microseconds each would take so long to switch from output to input, or to read the source pin and receive pin, that the charging event would be over before the count loop began.


body:
> Is there an advantage to set pinmodes via bitmask and register?

I can name a few:

1) speed - I benchmarked the arduino pin ops vs. direct register ops [here][1];

  [1]: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/
2) size - the code size is considerably bigger with the arduino library;

3) portability - the bitmark approach is supported by any C-compiler;

4) convention - i'm used to the bitmask approach and wrote all of my libraries around it;
...

as i'm sure others have their reasons to use the bitmasks.


body:
> I still can't see any advantage over simply using the standard way Arduino proposes.

The standard functions are slower.

---

There is a very good reason that the Arduino "standard" functions `digitalRead`, `digitalWrite` and `pinMode` are slower than direct port manipulation: They take **a variable** as the pin number and value to set it to.

This means that the functions in question then have to do a table lookup to translate the pin number to a port number and a bit position. The advantage is you can write code like this:

    for (int i = 0; i < 20; i++)
      {
      pinMode (i, OUTPUT);
      digitalWrite (i, LOW);
      }

That's quite handy!

However if you have timing-critical code, and you happen to know the pin number in advance, and it won't change, then you can use a library [digitalWriteFast](https://github.com/NicksonYap/digitalWriteFast) which can optimize that for you. The library cleverly detects if a particular call is given a variable or constant. If a constant then it does the faster port manipulation method (this can now be done at compile-time to find the port and bit number).

There seem to be a few different versions of this library around. The one I linked above fails if you don't pass a constant, others fall back to just doing a `digitalWrite` (etc).

Inside the library there is code like this:

    if (__builtin_constant_p(P) && __builtin_constant_p(V)) { \

In other words it uses a compiler directive to detect if the argument (P = pin, and V = value) are constants or not.

---

You can also, of course, do direct port manipulation but be warned that if you do then your code becomes pretty non-portable. Try going from an Atmega328 to an Atmega16U4 and the ports and bit positions will change.

---

Another library: <https://code.google.com/archive/p/digitalwritefast/downloads>


message:
Absolute encoder vs Accelerometer for calculating angles

I've been toying with this idea for a while and after some thorough research I'm more than happy that the project is realistic. However I'm in need of some direction in terms of the sensors I should be using.

There will be 3 arms all connected together (Like a poor mans Microscribe). I want to read the angle between each arm and use that info to calculate the final X and Y coordinates of the final end point on the arm.

I've looked closely into forward kinematics in robot arms and understand the principles are very much the same.

I've narrowed it down to Absolute encoders or accelerometers. Unfortunately I just can't find enough documentation about how to use the encoder with Arduino. There's plenty on using an accelerometer but I can't imagine the accuracy would be as good as the encoder.

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

The diagram attached shows the basic principle and formula I will use.

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

------EDIT-----

Thanks for the info everyone! Seems like this is going to be a little trickier than I originally thought. I've found a project achieving something very similar, however there's no mention of it's accuracy. [http://fablab.ruc.dk/diy-digitizer/][2]

Any ideas as to what sort of accuracy he could be achieving? I understand the length of the arms are considerably shorter than mine which must help a huge deal.

  [1]: https://i.stack.imgur.com/DAcnH.jpg
  [2]: http://fablab.ruc.dk/diy-digitizer/
  [3]: http://www.ebay.co.uk/itm/181575153048?_trksid=p2059210.m2749.l2649&ssPageName=STRK:MEBIDX:IT

body:
An accelerometer is not a suitable sensor for this, unless you are working in a vertical orientation (drawing on a wall), in which case you can use the pull of gravity.

It would, though, be overly complex for what is actually a very simple requirement.

Absolute encoders in the traditional (digital) sense are also not good since they don't give great resolution without an overly complex (large number of bits) interface.

The simplest option is to use simple potentiometers. They give around 270° of rotation, which should be more than enough for most uses, and are incredibly simple to interface. They give the resolution of the ADC (10 bit) and are very very simple to read (just use `analogRead()`).

They are also very cheap.


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

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

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

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

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

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

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

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

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


body:
> Is this accuracy feasible?

possible with high accuracy encoders but unlikely with accelerometers - they also drift too much.

Also, cos(x+y) can be decomposed into cos/sin(x) and (y), making a recursive calculation possible. that can be handy if you are using a lut to calculate sin/cos.


message:
Does anyone know how to connect 2 digipots to Arduino? (MCP4141)

I'm struggling with getting the code right. I'm trying to connect 2 digipots (MCP 4141) to Arduino to work separately over SPI. Has anyone got any experience with that?

body:
Try to read the datasheet and get a basic understanding of how the device works. in this case, it consists of 16 bits transfer (2 bytes).

Try to write a set of routines that communicates with the chip over the spi.

After that, it is all about using the _CS pin to select a particular chip.

edit: if this helps you, here is my code driving two mcp41010 - slight different from your digit pot but very similar.

    //write to the device wiper0
    void mcp41xxx_write0(uint8_t dat) {
     spi_write(MCP41XXX_P0 | MCP41XXX_CMD_WRITE); //send the command byte
     spi_write(dat);         //send the data byte
    }

    //write to the device wiper1
    void mcp41xxx_write1(uint8_t dat) {
     spi_write(MCP41XXX_P1 | MCP41XXX_CMD_WRITE); //send the command byte
     spi_write(dat);         //send the data byte
    }

the actual writes to the devices will differ -> mine is specific to the mcp41010 devices. It supports two wipers, P0 and P1. No increment or decrement on my digit pots.

the way to drive two digit pots are below:

 //first pot
 spi_select(MCP41XXX_CS1);   //deselect cs1 -> idles high
 mcp41xxx_write0(i + i);    //send the data
 spi_deselect(MCP41XXX_CS1);   //select hte device

 //second pot
 spi_select(MCP41XXX_CS2);   //deselect cs1 -> idles high
 mcp41xxx_write0(i++);    //send the data
 spi_deselect(MCP41XXX_CS2);   //select the device

as i'm using a single pot device, writing to the 2nd pot means writing to its wiper0.

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

I looked at your digit pot and the only thing you need to change are the wiper-specific routine(s), as your transmission is slightly different in the msb.

the spi_write() routine can be replaced / mapped to the shiftOut() routine under arduino.

here is the above code, without any change, running on an arduino:

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

  [1]: https://i.stack.imgur.com/7jSUT.png
  [2]: https://i.stack.imgur.com/96gwi.png

I also took a brief look at your device's datasheet (mcp4141) and I think this is all you need to change:

    //send data on wiper0 of mcp4141
    void mcp41xx_write0(uint16_t dat) {
     dat = dat & 0x03ff;        //10-bit data
     spi_write(MCP41XX_CMD_WRITE | MCP41XX_WIPER0 | (dat >>  8)); //write the msb
     spi_write(dat);         //write the lsb
    }


message:
Using strings inside mBlock extensions code

The following question is about a 3rd party Arduino programming enviroment mBlock and creating extensions for it. I hope that there are some of you out there, who are fammiliar with it.

I was recently making an extensions for mBlock that can be used to write code for Arduino, when I came over this obstacle. I tried to write a function inside the "work":"" statement.

It looked like this:

"work":"Serial.print("Hello world");"

The extensions could not be imported, due to the quotation marks around the Hello world string. I tried removing the quotation marks, the extension was sucessfully added, but the program did not work, beacause quotation marks are needed inside C++ code to define a string.

Is there a way to add them in the extensions, without screwing up the code?

body:
If that is a JSON format you could try using single quotes instead of double quotes:

    "work":'Serial.print("Hello world");'

Alternatively you could escape the internal quotes:

    "work":"Serial.print(\"Hello world\");"


message:
Using StringStream in Arduino sketch

I learned about StringStream today at work.

    #include <iostream>
    #include <sstream>
    #include <stdio.h>
    #include <string.h>

    using namespace std;

    char* getSql() {
        float outdoorTempInC = 15;
        int outoorHumidity = 23;
        float indorTempinC = 20;
        int humidity = 22;
        int val = 400; // soil sensor reading
        int avgVal = 38; // avaerage of 10 values of soils sensor
        char statusMsg[50] = {"Hello World"} ;
        std::stringstream sqlQuery;
        sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
            << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
            << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
            << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
            << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
            << statusMsg << "');";

        char *mychar = new char[sqlQuery.str().length() + 1];
        strcpy(mychar, sqlQuery.str().c_str());
        return mychar;
    }

    string getSqlStream() {
        float outdoorTempInC = 15;
        int outoorHumidity = 23;
        float indorTempinC = 20;
        int humidity = 22;
        int val = 400; // soil sensor reading
        int avgVal = 38; // avaerage of 10 values of soils sensor
        char statusMsg[50] = {"Hello World"} ;
        std::stringstream sqlQuery;
        sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
            << "out_humidity,  drwngRoom_temperature, drwngRoom_humidity, "
            << "pot1_soilMoisture, pot1_avg_SoilMoisture, wateringPot1) VALUES ('"
            << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
            << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
            << statusMsg << "');";
        return sqlQuery.str();
    }

    int main() {
        string sql = getSqlStream();
        cout << getSql() << "\n";
        cout << sql.c_str() << "\n";
        return  0;
    }

I was very happy until I discovered I cannot use StringStream in Arduino, so I dug in the internet and came across with [this][1].

So if I try to use the above linked gist StringSteam like I have used in my example code, I am getting this error:

    error: no match for 'operator<<' (operand types are 'StringStream' and 'const char [60]')
         sqlQuery  << "INSERT INTO arduinoSensorData.sensorLog (out_temperature,  "
                   ^
    webServer_Displaying_everything_v01:24: error: 'outdoorTempInC' was not declared in this scope
             << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                ^
    webServer_Displaying_everything_v01:24: error: 'outoorHumidity' was not declared in this scope
             << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                            ^
    webServer_Displaying_everything_v01:24: error: 'indorTempinC' was not declared in this scope
             << outdoorTempInC << "', '" << outoorHumidity << "', '" << indorTempinC
                                                                        ^
    webServer_Displaying_everything_v01:25: error: 'humidity' was not declared in this scope
             << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                          ^
    webServer_Displaying_everything_v01:25: error: 'val' was not declared in this scope
             << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                                ^
    webServer_Displaying_everything_v01:25: error: 'avgVal' was not declared in this scope
             << "', '" << humidity << "', '" << val << "', '" << avgVal << "', '"
                                                                 ^
    webServer_Displaying_everything_v01:28: error: 'class StringStream' has no member named 'str'
         char *mychar = new char[sqlQuery.str().length() + 1];
                                          ^
    webServer_Displaying_everything_v01:29: error: 'class StringStream' has no member named 'str'
         strcpy(mychar, sqlQuery.str().c_str());

Or I am doing it completely the wrong way? It feels I still cannot use it the way I have done in the example. Please help.

  [1]: https://gist.github.com/cmaglie/5883185

body:
**Direct Answer**

Program in C++ and cross compile to the Arduino Yún.  The Arduino Sketch language is a thin layer over C++, but the std:: namespace is not light weight to the degree it would need to be to fit the things you are appreciating from the standard C++ library into the memory footprint of a small embedded CPU board.  See https://arduino.stackexchange.com/questions/3055/arduino-yun-c-environment-bridge-cross-compiler.

**Serious Programming on Arduino**

If you wish to open the door to C++ elegance on smaller embedded CPU boards like the simpler Arduinos, you will need to move beyond the Arduino sketch language.  You may find it both fun and useful to learn how to cross compile and link using the GNU tool set that targets the Atmel CPU you have on your board.

This more professional approach is not for the faint at heart, but it is done all the time.   We do it here in TranSeed Labs every day.

To get started, you don't need to download or install anything other than the Arduino software.  The tool set that targets Atmel's AVR architecture (used by several Arduino boards) is in a sub-directory under the Arduino IDE's home directory.  The tool set that targets Atmel's SAM Architecture for the Arduino Due is placed in a sub-directory of your home directory when you [set up the IDE to upload sketches to the Due](https://www.arduino.cc/en/Guide/ArduinoDue).

**Returning to the Question in This C++ Context**

Once you learn how to compile and link using g++ from the GNU tool chain1 and use the upload tools2 your program via the USB port, you can create a template class to get the elegance available in C++ like the operator overloading that you like.

The issue with trying to employ the C++ library with embedded targets is that the allocation system and other dependencies will probably exhaust much if not all of your program memory.  The ostringstream class from the C++ library, with all its dependencies included, is not extremely lean.

An approach that consumes very little memory and does not require the CPU cycles of dynamic allocation is to create a C++ template that wraps a static array.  Its buffer size can be one of the template parameters.

Then you can overload the << operator of the class [using these examples as a guide](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=overload+operator+c+++example).  You get your elegance and drastically reduce your computing resource requirements.

---

*[1] Both cross compiling and cross linking are done with g++ (gcc for the Aruino and Atmel C files in the library).  For Arduino boards using the AVR based Atmel CPUs, use the [AVR GNU Tool Chain](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=avr+gnu+toolchain).  For the Due, which uses the SAM based Atmel CPUs, use the [SAM5X GNU Tool Chain](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=sam+gnu+toolchain).*

*[2] The program bossac is used to upload to the Due.  The program avrdude is used to upload to the Mega 2560.*


body:
It has nothing to do with cross compiling or linkage using the GNU tool. IO streams do present on Arduino but attempt to include it result in too big binary. It simply does not fit on chip's memory.

There are a couple of solutions to this problem. One is to use a library called [ard-streams](https://github.com/talybin/ard-streams). Another one is to use a lightweight, simplified version of `stringstream` just enough to compile your code.

    #include <string>

    namespace ard
    {
        struct ostringstream
        {
            ostringstream() = default;
            ostringstream(std::string arg) : s(std::move(arg)) {}

            const std::string& str() const {
                return s;
            }

            // Arithmetic types: int, float, ...
            template <class T>
            auto operator<<(T arg) -> decltype(std::to_string(arg), *this) {
                s.append(std::to_string(arg));
                return *this;
            }

            // String types: std::string, const char*
            template <class T>
            auto operator<<(const T& arg) -> decltype(std::string().append(arg), *this) {
                s.append(arg);
                return *this;
            }

            // Single char: 'a', '\n', ...
            ostringstream& operator<<(char arg) {
                s.append(1, arg);
                return *this;
            }

        private:
            std::string s;
        };
    }

Now just replace `std::stringstream` with `ard::ostringstream` and it will work as expected.


message:
Lighting LED with Arduino Uno from PC keyboard

I tried to turn on a LED with my PC keyboard and an Arduino Uno with the letter A.
I get the message

> exit status 1
> 'keypressed' was not declared in this scope

My code:

    int led1 = 10;

    void setup()
    {

    pinMode(led1, OUTPUT);
    }
    void loop()
    {

     if(keypressed == 'a'){
                   digitalWrite(led1, HIGH);
                   delay(500);
    }
    }

What is the problem?

body:
Firstly, you can't just make up the term "keypressed" because the programming language is unable to understand it (unless you assign it as a variable but it's purpose then would just be to store and retrieve values). Secondly the arduino itself is unable to detect keystrokes from the computer by itself. It needs a program on the computer to be able to detect keystrokes from the keyboard then send it to the arduino.

So how would one do this?

Assuming you use Windows, learn [Python][1] (A not-so-hard programming language on the computer), then look up the [msvcrt][2] library and from there learn how to get key strokes (this only works if you are currently selecting the running program). Then in arduino and python, learn how to use serial. For Python, you need to download [this library][3] and learn how to use it. For Arduino it's already in there you just have to [learn how to use it][4]. Then you can do the rest and make it turn on your LED.

I hope this helps.

  [1]: https://www.python.org
  [2]: https://docs.python.org/2/library/msvcrt.html
  [3]: https://pypi.python.org/pypi/pyserial
  [4]: https://www.arduino.cc/en/reference/serial


body:
Here you declared keypressed as a variable, so you need to assign an input to it using

'keypressed = serial.read()'
without quotes before if statement in void loop. Note make make use of serial monitor for input and also assign
'serial.begin(9600)'
without quotes in void setup function before pinmode statement.


message:
Ethernet Shield 2 data to PHP server doesn't work

I am trying to send data via GET to my PHP server from my Ethernet Shield2.
This is part of my sketch:

    char myserver[] = "www.myserver.com/";
    if (client.connect(myserver, 80)) {
      Serial.print("Connected to ");
      Serial.println(myserver);
      client.print("GET /arduino/controller.php?");
      client.print("air_temp=");
      client.print(DS18B20_temperature);
      client.println(" HTTP/1.1");
      client.print("Host: ");
      client.println(myserver);
      client.println("Connection: close");
      client.println();
      client.println();
    } else {
      // if you didn't get a connection to the server:
      Serial.println("Connection failed to Server");
    }

The serial monitor displays "Connect to myserver.com" but my PHP code doesn't seem to receive the `air_temp` value from DS18B20_temperature. I checked this value and it's true.

However, when I try `myserver.com/arduino/controller.php?air_temp=25` in my browser, the PHP code is running well.

What's going wrong with my code?

body:
I just removed the line server.begin() and it's works !!!
Thanks.


message:
Powering Arduino Uno from 5V pin, what exactly is the voltage range/tolerance?

I want to bypass the onboard regulator and use the 5V pin to feed arduino with external, regulated source.

Everybody just keeps saying [regulated 5V](https://electronics.stackexchange.com/questions/123418/connecting-power-source-to-arduinos-5v-pin), **but how precise does the regulation need to be exactly?** Can you state a voltage range and what makes you think so?

[10 ways to destroy arduino, Method #5: Apply >5V to the 5V Connector Pin](https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/) mentions "applying more than 6V", can anyone elaborate how it can be calculated?

**Is there a higher spike that arduino can handle for a short period of time?**
My concern is that the current draw from arduino might be under 60mA (right after switching power on and before the program initilizes and starts running), which is the lowest draw at which my source guarantees the 5V regulation --- when unloaded it gives out 6.5V. How could I resolve this better than putting a 60mA dummy load between the regulator and arduino itself?

body:
Unfortunately there is no one "clear cut" answer for all you ask.

There are some hard limits, though, which you can get from the main chip's datasheet:
> Operating Voltage: 1.8 - 5.5V

But that's not the whole story. The minimum voltage depends on the clock speed of the chip, as shown in this graph:

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

But wait, there's more. The Arduino also contains a 3.3V regulator which is fed from the 5V supply. That will have a minimum voltage above 3.3V that it needs to maintain a 3.3V output. So if you want to use the 3.3V regulator then, according to the datasheet for the regulator (`LP2985-33DVBR`):

>**3 Description**<br>
>The LP2985-N low noise linear (LDO) regulator delivers up to 150mA output current and only requires 300mV dropout voltage of input to output.

So a minimum of 3.3 + 0.3V, or 3.6V.

That gives you a usable range, clock frequency permitting, of **3.6V to 5.5V**.

As to how to protect the Arduino from a power-on spike like you describe - you could:

* Add your own extra [regulation in the form of a 5.1V zener diode][2].
* Add a dummy load which the Arduino can switch out of the circuit once booted up
* Change your source to something with better regulation
* Ignore it - the regulation with even a light load will be considerably better than open circuit.  Add a resistor across your supply that would draw much less than 60mA and measure the voltage. See how bad the regulation at low load is.

  [1]: https://i.stack.imgur.com/oLr4W.png
  [2]: http://www.electronics-tutorials.ws/diode/diode_7.html


body:
The 6.5V is too much. I have had an ATtiny chip which seems to run fine after applying 8V to it. But how can I be sure that it is okay ? There are so many parts in the chip die that can be damaged.

There has been a few broken voltage regulators reported, when applying 5V to the 5V pin of an Arduino Uno. The reverse diode inside the voltage regulator might not keep up with a large current peak. In some of my projects I power an Arduino via the 5V pin. I have added an extra diode 1N4007 from 5V to VIN, to save the voltage regulator, and my 5V power is not very strong.

I also don't apply that 5V while it is on. It is from a DC/DC converter that is part of the project. So when I turn on the power, the 5V raises not too fast, and there is no high current peak.

When applying 5V to the 5V pin, the current can flow into the computer via the usb cable. The polyfuse of 500mA on the Arduino board will prevent most troubles, but it could damage the computer. When I turn off my computer with that project connected, I do indeed see an increase of the current to my project. My computer is luckely not broken (yet).


body: Most decent 5V supplies (e.g. USB chargers) are within 5% of 5V. I use these all the time to power directly to the 5V pin. There has never been an issue with this. I don't use supplies outside 5% for this. Check with your multimeter first.


body:
You don't say why you want this information, but there are others who are trying to do similar.  (Starting with NOT destroying their Arduino)

For instance, at the end of the article

[10 Ways to Destroy An Arduino][1]

is a reference (broken link in the article) to

[The Ruggeduino][2]

which might be more suitable to your requirements.

Here is an excerpt of its specs:

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

  [1]: https://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/
  [2]: https://www.rugged-circuits.com/ruggeduino/
  [3]: https://i.stack.imgur.com/5p0zL.png


message:
Why do the LEDs visibly flicker?

The aim of the project was to be able to show two "kinds" of LEDs in a 8x8 single color LED matrix. I used a [MAX7219][1] chip to drive the LEDs using my Arduino UNO R3 as the driver (with the usual connections).

Despite the frequency of the `blackupdate()` function being near to a 100Hz, why do I see the LEDs corresponding to `currentblack()` flickering? 100Hz is much beyond the resolution of the eye, as I understand it. The [multiplexing frequency of the MAX7219 chip][2] is also much beyond resolution (800Hz). Why do the "white" LEDs not flicker?

Here's the code with `Serial.println()` added for debugging:

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

    int DataPin = 2; // Pin 1 on MAX
    int LoadPin = 3; // Pin 12 on MAX
    int ClockPin = 4; // Pin 13 on MAX
    int currentwhite[8]={B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000};
    int currentblack[8]={B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000,B00000000};

    #define SCAN_LIMIT_REG 0x0B
    #define DECODE_MODE_REG 0x09
    #define SHUTDOWN_REG 0x0C
    #define INTENSITY_REG 0x0A
    #define DISPLAY_CHECK_REG 0x0F

    void setup() {
      pinMode(DataPin, OUTPUT);
      pinMode(LoadPin, OUTPUT);
      pinMode(ClockPin, OUTPUT);
      digitalWrite(LoadPin, LOW);
      shiftOut(DataPin, ClockPin, MSBFIRST, SCAN_LIMIT_REG); // scan limit set to 0:7
      shiftOut(DataPin, ClockPin, MSBFIRST, B00000111);
      digitalWrite(LoadPin, HIGH);
      digitalWrite(LoadPin, LOW);
      shiftOut(DataPin, ClockPin, MSBFIRST, DECODE_MODE_REG);
      shiftOut(DataPin, ClockPin, MSBFIRST, B00000000);
      digitalWrite(LoadPin, HIGH);
      digitalWrite(LoadPin, LOW);
      shiftOut(DataPin, ClockPin, MSBFIRST, SHUTDOWN_REG);
      shiftOut(DataPin, ClockPin, MSBFIRST,  B00000001);
      digitalWrite(LoadPin, HIGH);
      digitalWrite(LoadPin, LOW);
      shiftOut(DataPin, ClockPin, MSBFIRST, DISPLAY_CHECK_REG);
      shiftOut(DataPin, ClockPin, MSBFIRST, B00000000);
      digitalWrite(LoadPin, HIGH);
      digitalWrite(LoadPin, LOW);
      shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
      shiftOut(DataPin, ClockPin, MSBFIRST, 0);
      digitalWrite(LoadPin, HIGH);
      Serial.begin(9600);

      currentblack[3]=B00001000;
      currentblack[4]=B00010000;
      currentwhite[3]=B00010000;
      currentwhite[4]=B00001000;
    }

    void blackupdate() {
      digitalWrite(LoadPin, LOW);
        shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
        shiftOut(DataPin, ClockPin, MSBFIRST, 0);
        digitalWrite(LoadPin, HIGH);
      for (byte row=0; row<8; row++){
        digitalWrite(LoadPin, LOW);
        shiftOut(DataPin, ClockPin, MSBFIRST, row+1);
        shiftOut(DataPin, ClockPin, MSBFIRST, (currentblack[row]));
        digitalWrite(LoadPin, HIGH);
      }
    }

    void whiteupdate() {
      digitalWrite(LoadPin, LOW);
        shiftOut(DataPin, ClockPin, MSBFIRST, INTENSITY_REG);
        shiftOut(DataPin, ClockPin, MSBFIRST, 15);
        digitalWrite(LoadPin, HIGH);
      for (byte row=0; row<8; row++){
        digitalWrite(LoadPin, LOW);
        shiftOut(DataPin, ClockPin, MSBFIRST, row+1);
        shiftOut(DataPin, ClockPin, MSBFIRST, (currentwhite[row]));
        digitalWrite(LoadPin, HIGH);
      }
    }

    void loop() {
      Serial.print("A");
      Serial.println(millis());
      blackupdate();
      Serial.print("B");
      Serial.println(millis());
      whiteupdate();
      delay(5);
      Serial.print("C");
      Serial.println(millis());
    }

And the Serial output was as follows:

    A1
    B3
    C10
    A10
    B12
    C19
    A19
    B21
    C28
    A28
    B30
    C37
    A37
    B39
    C47
    A47
    B49
    C56
    A56
    B59
    C65
    A66
    B68
    C75
    A75
    B77
    C84
    A84
    B87
    C94
    A94
    B96
    C105
    A105
    B112
    C123
    A123
    B131
    C142
    A143
    B150
    C161
    A161
    B168
    C180
    A180
    B187
    C198
    A198
    B205
    C217
    A218
    B225
    C236
    A236
    B243
    C254
    A254
    B262
    C273
    A274
    B281
    C292
    A292
    B300
    C311
    A311
    B318
    C329
    A329
    B336
    C348
    A349
    B356
    C367
    A367
    B374
    C386
    A386
    B393
    C404
    A404
    B412
    C422
    A423
    B431
    C442
    A442
    B449
    C460
    A460
    B467
    C479
    A480
    B487
    C498
    A498
    B505
    C517
    A517
    B524
    C535
    A535
    B542
    C553
    A555
    B562
    C573
    A573
    B580
    C591
    A591
    B599
    C610
    A611
    B618
    C629
    A629
    B636
    C648
    A648
    B655
    C666
    A666
    B673
    C685
    A686
    B693
    C704
    A704
    B711
    C722
    A722
    B730
    C741

  [1]: https://www.maximintegrated.com/en/products/power/display-power-control/MAX7219.html
  [2]: https://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf

body: The hardware setup isn't clear. For example, do you have two matrix's or one? In any event, the effect of black update() stays on much shorter than the effect of white update() due to the delay inserted in the main loop.


body:
You are correct that this is updating at about 100 Hz. The clue is in the serial output:

    A1
    B3  <<
    C10 <<
    A10
    B12 <<
    C19 <<
    A19
    B21 <<
    C28 <<
    A28
    B30 <<
    C37 <<
    A37

There is always a big gap between the ms reading between `B` and `C`. This is due to the delay in after the `whiteupdate()`.

    void loop() {
        Serial.print("A");
        Serial.println(millis());
        blackupdate();
        Serial.print("B");
        Serial.println(millis());
        whiteupdate();
        delay(5);    // <-- DELAY HERE
        Serial.print("C");
        Serial.println(millis());
    }

There is no update between the `blackupdate()` and the `whiteupdate()`, so even though 5ms is just on the border of what your eyes can determine, due to the repeating pattern and persistence of vision, your eyes do notice it.

You will find that your flicker will dissapear if you split the delay so you have an equal delay between your `blackupdate()`->`whiteupdate()` and `whiteupdate()`->`blackupdate()`.

    void loop() {
        Serial.print("A");
        Serial.println(millis());
        blackupdate();
        delay(2);    // <-- DELAY HERE
        Serial.print("B");
        Serial.println(millis());
        whiteupdate();
        delay(2);    // <-- DELAY HERE
        Serial.print("C");
        Serial.println(millis());
    }

Removing the serial debug lines give you:

    void loop() {
        blackupdate();
        delay(2);
        whiteupdate();
        delay(2);
    }


body: There may be some more physiology at work here, too. Did you notice the flickering while staring fixedly at one LED, or while looking around your project area ("scanning" as it were, with your eyes)? If you scan your vision past a flickering LED, even one that flickers at a rate beyond our perception, you can see a streak of dots cross your vision, where a steadily lit one would make a solid streak. I noticed it driving at night, when LED tail-lights were still new and unusual. Those cars stood out because their tail-lights left the same trail of dots across my vision (although some people have told me they do not see this phenomenon or aren't aware of it...).


message:
Delaying an action inside a function

My current function is supposed to play a sound effect, then after the sound effect is done (14 seconds), perform the next action (`digitalWrite(CONTROLLINO_R1, LOW)`).

    if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch) {
      skeleLatch = 1;
      wTrig.trackPlayPoly(2);
      unsigned long currentMillis = millis();
      if((currentMillis-previousMillis) >= 14000) {
        digitalWrite(CONTROLLINO_R1, LOW);
        previousMillis = millis();
      }
    }

As it is, it performs both at the same time. I do not know how to correctly implement the delay so that it waits.

Any help would be appreciated. Thank you.

body:
      unsigned long triggerMillis = 0;

      if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch)
      {
        skeleLatch = 1;
        wTrig.trackPlayPoly(2);
        triggerMillis = millis();
      }

      if (millis() - triggerMillis >=14000 && skeleLatch)
      {
        digitalWrite(CONTROLLINO_R1, LOW);
        skeleLatch = 0;
      }
  This should work, depending on how long your CONTROLLINO_A8 is staying high you might want to invest some more time to set up an interrupt on that pin, to make sure you don't miss a trigger.


body:
If your code does not need to be re-entrant (work within a multitasking environment), the simpler solution is [Arduino's delay function](https://www.arduino.cc/en/Reference/Delay), designed specifically for waiting a specific number of milliseconds.

    delay(14000)


message:
Analog inputs on ATtiny85 don't work

I want to use a ATtiny85 to check the voltage of two 12 V batteries (later to control a relay). Therefore I'm using the `analogRead()` function. For programming I'm using an Arduino Mega 2560 board.

    //                           +-\/-+
    //  Ain0       (D  5)  PB5  1|    |8   VCC
    //  Ain3       (D  3)  PB3  2|    |7   PB2  (D  2)  INT0  Ain1
    //  Ain2       (D  4)  PB4  3|    |6   PB1  (D  1)        pwm1
    //                     GND  4|    |5   PB0  (D  0)        pwm0
    //                           +----+

For A1 this works perfectly fine. But for A2 or A3 I'm getting always a value of 15 V (thus the analog input gives 1023 respectively it thinks there is 5 V on the pin, which is not the case). I tried A0 as well, but it's the same.

For seeing the current value I put a serial - USB converter on RX, TX on PB3, PB4. So I guess they cannot work properly as analog inputs then. But still A0 does not work and without serial my LED is always on without having a voltage over 12 V.

At the moment I don't know what to do about it. No matter which of the analog pins I choose, I'm getting always a wrong value (except A1).

I'm not a hundred percent sure about A0. On some diagrams there is an A0 pin, on some not. But I tried to remove all the serial communication code and still having the LED 0 on high.

Thanks in advance!

    void setup() {
      pinMode(0, OUTPUT);
      pinMode(1, OUTPUT);
      digitalWrite(0, LOW); // led for displaying the voltage
      digitalWrite(1, LOW); // blinking status led
      int sensorValue1 = 0;
      int sensorValue2 = 0;
      Serial.begin(9600);
    }

    void loop() {
      int sensorValue1 = analogRead(A1);
      int sensorValue2 = analogRead(A0);
      // <- the problem, A2, A3 do not work as well
      float voltage1 = sensorValue1 * (5 / 1023.00) * 3;
      float voltage2 = sensorValue2 * (5 / 1023.00) * 3;
      Serial.print(voltage1);
      Serial.print("--");
      Serial.print(voltage2);
      Serial.println();
      if ((voltage1 > 12) || (voltage2 > 12)) {
        digitalWrite(0, HIGH);
      } else {
        digitalWrite(0, LOW);
      }
      digitalWrite(1, HIGH);
      delay(1000);
      digitalWrite(1, LOW);
      delay(1000);
    }

SOLUTION:
As suggested by Andrei Dragan the problem was the serial communication, which uses just the same pins as the analog inputs A2 and A3. When turned off, the problem disappeared.

As the serial communication is quite useful for me, right now I'm still using the serial communication but only with the pin for sending data. The pin for receiving data is turned off. It looks like this:

    #include <SoftwareSerial.h>

    #define RX    -1   // *** turned off
    #define TX    4   // *** D4, Pin 3

    SoftwareSerial Serial1  (RX, TX);

(I don't know if this is the best way, but it works for me.)

Once again, thanks for the help!

body: Any type of communication protocol uses pull-up resistors (not 100% sure that all of them do but still, it's a rule of thumb) so using the serial trick on the attiny enables the internal pull-up resistors on PB3 and PB4. I can bet the ADC value is near 1023 isn't it? Disabling the serial communication should in theory fix your problem.


message:
Arduino Uno Wunderground weather station - Ethernet connection failed

I'm new to Arduino. For my first project, I've decided to build a weather station where data is collected via sensors and is then sent to Wunderground. I'm using an arduino uno, an ethernet shield as well as a DHT22 sensor for temperature and humidity.

Everything worked for an hour and then I'm getting "connection Failed" constantly.

I would really appreciate it if you could look into my code. I've tried everything and it doesn't explain the sudden failure of the project. I occasionally get a successful upload after dozens of connection failed messages.

Here's my code. I've removed my weather station password for security reasons.

    #include <Wire.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include "DHT.h"

    // Sensor Pins
    #define DHTPIN 7
    #define DHTTYPE DHT22
    // Variables
    float temp;
    float hum;

    byte mac[] = {
      "de,ad,be,ef,fe,ed"
    };
    EthernetClient ethernetClient;
    unsigned int localPort = 8888;
    // Wunderground server details
    char SERVER[] = "rtupdate.wunderground.com";
    char WEBPAGE[] = "GET /weatherstation/updateweatherstation.php?";
    char ID[] = "ICHESTER24";
    char PASSWORD[] = "iwqnrlex";

    DHT dht(DHTPIN, DHTTYPE);
    unsigned int connections = 1;
    unsigned int timeout = 30000;

    void setup(void) {
      Serial.begin(38400);
      Wire.begin();
      dht.begin();

      // Connect to internet
      Serial.print(F("\nInitialising Ethernet module"));
      if (Ethernet.begin(mac)){

        Serial.println("Initialisation completed successfully!");
      }
      else {
        Serial.println("Something went wrong during ethernet module setup!");
      }
    } //END OF SETUP

    void loop(void) {
      hum = dht.readHumidity();
      temp = dht.readTemperature();
      float tempf = (temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
      float dewptf = (dewPoint(tempf, hum));
      Serial.println("++++++++++++++++++++++++++");
      Serial.println("temp = ");
      Serial.println(tempf);
      Serial.println("Humidity = ");
      Serial.println(hum);
      Serial.println("DewPoint = ");
      Serial.println(dewptf);
      // Send all data to WUNDERGROUND
      if (ethernetClient.connect(SERVER, 80)) {
        ethernetClient.print(WEBPAGE);
        ethernetClient.print("ID=");
        ethernetClient.print(ID);
        ethernetClient.print("&PASSWORD=");
        ethernetClient.print(PASSWORD);
        ethernetClient.print("&dateutc=");
        ethernetClient.print("now");
        ethernetClient.print("&tempf=");
        ethernetClient.print(tempf);
        ethernetClient.print("&humidity=");
        ethernetClient.print(hum);
        ethernetClient.print("&dewptf=");
        ethernetClient.print(dewptf);
           ethernetClient.print("&softwaretype=Arduino UNO version1&action=updateraw&realtime=1&rtfreq=2.5");//Rapid Fire
        ethernetClient.println();
        Serial.println("New data uploaded");
      }else{
        Serial.println("Connection Failed...");
      }
      delay(2500);

    }
    void resetEthernet() {
     ethernetClient.stop();
     delay(1000);
     Ethernet.begin(mac);
     delay(1000);
     ethernetClient.available();
    }
    double dewPoint(double tempf, double humidity)
    {
      double A0= 373.15/(273.15 + tempf);
      double SUM = -7.90298 * (A0-1);
      SUM += 5.02808 * log10(A0);
      SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
      SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
      SUM += log10(1013.246);
      double VP = pow(10, SUM-3) * humidity;
      double T = log(VP/0.61078);
      return (241.88 * T) / (17.558-T);
    }

body:
I assume u used a W5100 shield. This shield is capable of having 4 connections open. If the connections are not closed for some reason the chip is unable to make another connection.
This means after sending u need to close the connection. (else it will work 4 times).

```ethernetClient.stop()```

Just before or after

```Serial.println("New data uploaded");```

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


message:
How to have some code executed at a certain time of day with a DS3231 RTC?

I recently bought a DS3231 RTC, but I cannot seem to figure out how to get it to work. I have tried all different tutorials and example programs but I keep getting `2165.25.165 165:165:165` as the output.

I am using an Arduino Micro, with the RTC connected as follows:

 - GND > GND
 - VCC > 5V
 - SDA > A4
 - SCL > A5

**Project details:**

The project uses a 16x2 LCD to display the time of day, and a countdown to the next occurrence of 06:00. Then at 6 it will allow for a button to be pressed to open a servo and do other things. I got temporary test code to work using `millis()`, but it is only displaying a 12-hour countdown in seconds, and I would like to replace it with a more reliable RTC.

body:
If you are getting 165:165:165 that indicates usually a problem with your I2C bus. But it might also be a power problem in the RTC.

In any case, check your wiring.

Your processor is simply not properly communicating with the RTC. If the RTC's red light is on then check your wiring and make sure you haven't reversed SDA and SCL.

Also, the DS3231 has and most Arduinos have enough pull-up that you won't need external pull-up resistors in order to communicate directly with the DS3231.

Try plugging it straight into the Arduino - go minimalist and make that work before adding other devices to the I2C bus like a LCD display. Set the clock by code and watch it in the serial monitor.

Once you're sure the RTC is not a problem then you can go from there with the I2C bus. It is certainly possible for other devices on the bus to cause the RTC to be unable to respond correctly. For a short-range I2C bus that includes the DS3231 don't add any external pullups.

The most reliable RTC for Arduino is the DS3231, but if you bought it via the slow boat you might try a voltmeter to verify the battery so it keeps time even when powered down.

And of course, it is only as accurate as you program it to be. When I program my DS3231s, I always add a couple of minutes to the current time to allow for the time to fix forgotten semicolons and such before it gets around to actually programming the device.

One last note: The program will run when you open the serial monitor. So that will be when it sets the time then begins to display it.


body:
Your question doesn't match your title so I will go with your title.

> How to have some code executed at a certain time of day with a DS3231 RTC?

The typical approach is to set an alarm on the RTC (to the extent that it supports it), and process that interrupt from the RTC on the MCU side.

Alternatively, you can poll the time on the RTC periodically and once the time is up, do your thing.


body:
SDA and SDL pins on an Arduino Micro are on pins D2 and D3 as mentioned on the [official page](https://www.arduino.cc/en/Main/arduinoBoardMicro):

>TWI: 2 (SDA) and 3 (SCL). Support TWI communication using the Wire library.

and shown on this pinout reference:

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

  [1]: https://i.stack.imgur.com/VKnJN.png
  [2]: http://www.pighixxx.com/test/portfolio-items/micro/?portfolioID=314


message:
'MeDCMotor' does not name a type error inside mBlock

I was using a 3rd party programming enviroment, mBlock 3.4.5 for making C++ Arduino programmes with a graphical programming language. I was compiling a program and the following eroor came up.

    project_Untitled0_0.ino:65:1: error: 'MeDCMotor' does not name a type
    project_Untitled0_0.ino:66:1: error: 'MeDCMotor' does not name a type
    project_Untitled0_0.ino: In function 'void move(int, int)':
    project_Untitled0_0.ino:85:7: error: 'motor_9' was not declared in this scope
    project_Untitled0_0.ino:85:24: error: 'M1' was not declared in this scope
    project_Untitled0_0.ino:86:7: error: 'motor_10' was not declared in this scope
    'MeDCMotor' does not name a type

I took another look at the program and there were some lines of code that seem they are added in the program by deafult:

    MeDCMotor motor_9(9);
    MeDCMotor motor_10(10);
    void move(int direction, int speed)
    {
          int leftSpeed = 0;
          int rightSpeed = 0;
          if(direction == 1){
             leftSpeed = speed;
             rightSpeed = speed;
          }else if(direction == 2){
             leftSpeed = -speed;
             rightSpeed = -speed;
          }else if(direction == 3){
             leftSpeed = -speed;
             rightSpeed = speed;
          }else if(direction == 4){
             leftSpeed = speed;
             rightSpeed = -speed;
          }
          motor_9.run((9)==M1?-(leftSpeed):(leftSpeed));
          motor_10.run((10)==M1?-(rightSpeed):(rightSpeed));
    }

Since the program does not recognise the MeDCMotor class the program failed to upload.

I am running Windows 10 home edition on a 64-bit laptop.

Is there a way to remove the lines of code that prevent me from uploading the sketch or are there other ways to solve it?

body:
I looked at some entries in a google search for *[error: 'MeDCMotor' does not name a type](https://www.google.com/search?num=50&site=&source=hp&q=+error:+'MeDCMotor'+does+not+name+a+type&oq=+error:+'MeDCMotor'+does+not+name+a+type&gs_l=hp.3...1290.1290.0.3512.2.2.0.0.0.0.133.236.0j2.2.0....0...1..64.hp..0.0.0.0.Waru0ErKOcY)*, such as [1](http://forum.arduino.cc/index.php?topic=224697.0), [2](http://forum.makeblock.com/t/need-help-with-ir-control/402/1), [3](http://blog.makeblock.com/getting-started-with-ardublock-for-makeblock-electronic-modules/) and [4](http://forum.arduino.cc/index.php?topic=155921.0).  The first three of those latter four links directly address the question you ask, and none of them answer it clearly, except to suggest re-downloading or re-installing the makeblock library.  While the fourth link addresses a “does not name a type” error for another library, rather than for makeblock, it has a relatively clear explanation of the problem for that other library:

>So, as supplied, the ArduinoByteBuffer.zip file had a complex set of sub-directories, and the two files ByteBuffer.ccp and ByteBuffer.h were located one level down in: \ArduinoByteBuffers\ByteBuffer\

>When I 'installed' the library, it went into the directory:
>>  C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.ccp
   C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.h

>To solve the problem I moved them up a level to:
>>   C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.ccp
   C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.h

>That seemed to be the key - moving the two files (*.ccp and *.h) out of the subdirectory.

Instead of following ordinary C or C++ library-finding rules, the Arduino IDE copies sets of files into a temporary directory according to its own rules when compiling a sketch.  You'll need to move your makeblock library files around to match up with Arduino IDE conventions.


body:
In the MakeBlock, menu "choice of extensions", uncheck all the extensions, keeping only the one called "Makeblock" checked:

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

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


message:
How to do weigh scale zeroing (tare weight)?

I'm using the sketch below for a weighing scale. The sketch prints out the load-cell voltage just fine. I can't figure out how to let the scale run a couple seconds to stabilize, then use the current voltage reading (nothing on the scale) as the "Zero" voltage. Then subtract that "Zero" voltage from future readings to get the actual voltage for any weight placed on the scale. For example, let's say the nothing on the scale voltage is 0.5 volts. Then a 10 LB weight is added and the voltage goes up to 1.5 volts. So the actual voltage increase from the weight is 1.5 minus 0.5, or 1.0 volts.

    #include <ads1262.h>

    const float VREF = 2.50;  // Internal reference

    ads1262 PC_ADS1262;  // ADC object

    void setup() {
      // initialize the  data ready and chip select pins:
      pinMode(ADS1262_DRDY_PIN,  INPUT);   // data ready input line
      pinMode(ADS1262_CS_PIN,    OUTPUT);  // chip enable output line
      pinMode(ADS1262_START_PIN, OUTPUT);  // start
      pinMode(ADS1262_PWDN_PIN,  OUTPUT);  // power down output
      Serial.begin(9600);

      // initialize ADS1292 slave
      PC_ADS1262.ads1262_Init();
      Serial.println("ads1262 Initialised successfully....");
    }

    void loop() {
      // Nothing to do unless data ready is asserted.
      if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;

      // Get a reading and convert to voltage.
      uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
      signed long reading = (uint32_t) buffer[1] << 24
                      | (uint32_t) buffer[2] << 16
                      | (uint32_t) buffer[3] <<  8
                      | (uint32_t) buffer[4] <<  0;
      float voltage = VREF / (1UL<<31) * reading;

      // Report a smoothed-out reading.
      Serial.println(voltage, 8);
    }

body:
The direct answer to your question is to wait for the scale to settle and store the Tare voltage; then subtract it from future readings.

But that only works if the scale's transfer function (Voltage as a function of weight, or V(f)) is linear (weight = Voltage * CONSTANT). Otherwise you need to keep the Tare in weight units, do the full conversion of voltage to weight on subsequent readings, and subtract the Tare weight from that.


body:
You start out with a variable named Tare initialized to zero `float Tare = 0.0;` put in a conditional like `if (millis() > 2000 & Tare == 0.0) Tare = voltage;` and always report `voltage - Tare`.

    float Tare = 0;

    void loop() {
      // Nothing to do unless data ready is asserted.
      if (digitalRead(ADS1262_DRDY_PIN) == HIGH) return;
      // Get a reading and convert to voltage.
      uint8_t *buffer = (uint8_t *) PC_ADS1262.ads1262_Read_Data();
      signed long reading = (uint32_t) buffer[1] << 24
        | (uint32_t) buffer[2] << 16
        | (uint32_t) buffer[3] <<  8
        | (uint32_t) buffer[4] <<  0;
      float voltage = VREF / (1UL<<31) * reading;
      if (millis() > 2000 & Tare == 0.0) Tare = voltage;
      // Report a smoothed-out reading.
      Serial.println(voltage-Tare, 8);
    }

If you want to make it smarter, add a button for tare and maybe if you have a calibration weight, add a button for calibrating.

    float scale= 1.0;
    const float calib_weight = 500.0; // grams?
    ...
    if(tareButton | (millis() > 2000 & Tare == 0.0)) Tare = voltage;
    if(calibrateButton) scale = calib_weight / (voltage-Tare) ;
    ...
    Serial.println((voltage - Tare)*scale,8);
    ...


message:
Using millis() function to start at potentiometer reading

I am trying to use the `millis()` function to start a countdown of 3 seconds when I turn my potentiometer to high travel. My code so far starts the timer at the beginning of the loop or when reset is hit or when the sketch is uploaded to the board. I need the countdown to start when the potentiometer reaches high travel.

The goal of the program is that when the potentiometer reaches high travel, PumpOne starts (HIGH) and if the potentiometer does not reach low travel before 3 seconds, PumpTwo will come on (HIGH). I am trying to simulate a water tank with two pumps (LEDs in this case) and the potentiometer high and low travel representing the high and low levels of the tank respectively.

**I've updated the code since the original post but the timer still starts from the beginning of the program and not when L > Plim1.**

Here's the code:

    int Pump1 = 3; // Declare Blue LED in pin 3 to simulate Pump 1
    int Pump2 = 4; // Declare Green LED in pin 4 to simulate Pump 2
    int Alarm = 2; //Delcare Red LED in pin 2 to simulate Alarm
    int TDCRPot = A0; // Declare Potentiometer(TDCRPot) an int and assign to pin A0

    int L; //Declare L a variable to read the High and Low
    //travel of the potentiometer

    float Plim1 = 1000; // pot reading for pump 1 turn on
    float Plim2 = 1000; // pot reading for pump 2 turn on
    float Llim = 100; //pot reading to turn both pumps off
    unsigned long T; // current time
    unsigned long T1 = 0; // P1  on time
    boolean P1 = false;
    boolean P2 = false;
    boolean Alarmstate = false;
    unsigned long Tlim = 3000;

    void setup() {
      Serial.begin(9600); //Turn on Serial monitor for troubleshooting
      //purposes and set to 9600 baud
      pinMode(Pump1, OUTPUT); //Declare Blue LED(PumpOne) an output
      pinMode(Pump2, OUTPUT); //Declare Green LED(PumpTwo) an output
      pinMode(Alarm, OUTPUT); //Declare Red LED(Alarm) an output
      pinMode(TDCRPot, INPUT); //Declare Potentiometer(TDCRPot) an input
    }

    void loop() {
      L = analogRead(TDCRPot); //Read the voltage from the Potentiometer pin
      if (!P1 && L > Plim1) {
        T = millis();
        digitalWrite(Pump1, !P1);
      }
      if (Pump1 != P1 && T - T1 > Tlim && L > Plim2) {
        digitalWrite(Pump2, !P2);
      }
      if (Pump1 != P1 && L < Llim ) {
        digitalWrite(Pump1, P1);
        digitalWrite(Pump2, P2);
      }
    }

body:
The statement `TDCRLevel = analogRead(TDCRPot);` will almost always set `TDCRLevel` to a non-zero value; hence the `&& TDCRLevel` term of your last `if` statement almost always is satisfied.  The only time it won't be satisfied is when `TDCRLevel` is exactly zero.

When `TDCRLevel >= 1000` is first satisfied, it's likely to be true for some while; during that time, each pass through `loop()` will toggle `Bluestate` and set `previousMillisBlue = currentMillis`.  This happens many times per millisecond while `TDCRLevel` has a high value.  Whether `Bluestate` is on or off when  `TDCRLevel` goes below 1000 is a fairly random outcome.

To handle the process properly, set up a [state machine](https://en.wikipedia.org/wiki/Finite-state_machine), using either one state-number variable or several variables to maintain state.  Change states when conditions tied to state, `TDCRLevel`, and time are met.

More simply, something like the following might work.

    loop:
      if !P1 and L > Plim1:
        Set P1; record T1
      if P1 and T-T1 > Tlim and L > Plim2:
        Set P2
      if (P1 or P2) and L < Llim:
        Turn off pumps, clear P1 and P2

where P1, P2 represent pump states; T represents current time and T1 represents time that P1 most recently turned on; L = analogRead(TDCRPot); Plim1 and 2 are pot levels for pump turnons; Llim = low level for pump turnoffs; Tlim = desired time delay before pump 2 comes on.

---

*Edit 1:*  The above is pseudocode, rather than any simulacrum of valid C or C++.  As such, you may need to add sets of parentheses and brackets, substitute meaningful variable names, etc.

Note that the constants `Plim1, Plim2, Tlim, Llim` should be declared via either `const int` declarations, or via `enum {}` constructs (`enum` declares only integer constants), if they are integers rather than floats.  For example, do like either of

    const int Plim1 = 1000; // level for pump1 turnon
    const int Plim2 = 1000; // level for pump2 turnon
    //etc

or

    enum { Plim1=1000, Plim2=1000, Tlim=3000, Llim=100};

The phrase “Set P1; record T1” corresponds to code like

    P1 = true;
    digitalWrite(Pump1, HIGH);
    T1 = millis();

in braces.  If you don't set P1 and record T1 as current time, the process won't work.  P1 and P2 represent state variables, not constants.

The phrase “if P1 and T-T1 > Tlim and L > Plim2: Set P2” corresponds to code like

    if (P1 && (T - T1 > Tlim) && (L > Plim2)) {
      P2 = true;
      digitalWrite(Pump2, HIGH);
    }

The phrase “if (P1 or P2) and L < Llim: Turn off pumps, clear P1 and P2” corresponds to code like

    if((P1 || P2) && (L < Llim)) {
      P1 = P2 = false;
      digitalWrite(Pump1, LOW);
      digitalWrite(Pump2, LOW);
    }


message:
How can I use my Arduino sketches on my Raspberry Pi IDE?

I have installed the Arduino IDE 2:1.0.5 on my Raspberry Pi3 under Raspbian and am using a cobbler breakout which provides a nice breadboard.  On that breadboard I have installed an Arduino Nano to do analog voltage readings, which it then communicates back to the Rpi3 via the USB serial port which shows up as /dev/ttyUSB0 on the Rpi3.

This port opens as a regular file in Python for further processing such as adding a date & time stamp (obtained by an NTP server) and saving the results to a data file that is displayed in gnuplot 4.6.

[![PiBerry][1]][1]

*You'll notice I am using 3.3 Volts for the fan to keep it quiet, and the two wires heading up to the top go to the voltage source I am monitoring.  If you look closely you can see the voltage divider circuit.*

Here is today's solar plant voltages which this thing tracks.  The block at the bottom means the inverter was on.  Green means the battery bank is full.

[![PV Battery Bank][2]][2]

**Anyway, it turns out that the same serial connection is supported by the Rpi Arduino IDE for programming.**

Rather than programming the Nano on a laptop and constantly having to unplug/replug it on the breadboard my goal is to use Rpi Arduino IDE for programming.

So I moved all my sketches over from the Arduino IDE on the laptop to the Rpi.

But
-
   .... then every time I start the Rpi IDE it throws error messages for all the sketches that have underscores in their names.  Turns out the Rpi version will only allow alphanumeric directory names.  I have a couple dozen sketches and this is not productive.  It requires clicking OK for every directory it skips - which turns out to be all of them.

So my question is:  What can I do about this?

  [1]: https://i.stack.imgur.com/yVo1g.jpg
  [2]: https://i.stack.imgur.com/67hLV.png

body:
To fix this problem I came up with the following procedure which takes out all the underscores from the directories & filenames and capitalizes each word instead.

First, I copied all my sketches and libraries (from my documents/arduino directory) to a USB flash drive.

The Rpi Arduino IDE creates a sketchbook directory upon install, so I

  Copied the libraries folder to ~/sketchbook/libraries

  Copied the sketches folder to ~/sketchbook/AMSsketches

Then I wrote a custom script that is copied to my home directory on the Rpi, which can be obtained here as a text file (use Chromium or wget to copy it to the file ~/AMS2Rpi)  - Here is the link:  http://calttc.net/AMS2Rpi

which contains this code:

    #! /bin/bash
    #
    #  AMS2Rpi - Converts MS Arduino IDE Sketch names to RPI Arduino IDE Sketch names
    #
    #                  SDsolar      2017-01-29
    #
    #  Reason:    Arduino IDE on MS inserts underscore characters in file & directory names
    #             Arduino IDE on Rpi rejects all but alphanumeric characters
    #
    #  Solution:  Remove all but alphanumeric characters
    #             and capitalize each word in the names
    #
    #  Usage:
    #    Install Raspbian Arduino IDE 2:1.0.5 on the Raspberry Pi 3
    #    Use a USB flash drive to copy sketches and libraries from the MS-based Arduino IDE
    #      On the Rpi, copy the libraries directory to ~/sketchbook/libraries
    #      On the Rpi, copy the sketches directory to ~sketchbook/AMSsketches
    #    Copy this script to your home directory as AMS2Rpi using Chromium
    #    cd
    #    chmod +x AMS2Rpi
    #    ./AMS2Rpi    (This will take some time)
    #    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMSRpiQ
    #    chmod +x ~/AMS2RpiQ
    #    ~/AMS2RpiQ
    #    Open the Rpi Arduino IDE
    #
    #  Alternatively, if you have a lot of sketches you might want to
    #    change the "mv -i" below to "mv"
    #    and cat it into AM2SRpiX above
    #    so you don't need to answer "y" for every rename.
    #
    #  Props to Marco Fioretti for his article at http://www.techrepublic.com/blog/linux-and-open-source/how-to-remove-weird-characters-from-file-and-directory-names-automatically/
    # ---------------------------------------------------------------------
    rm -f /tmp/AMS2R*
    cd $1
    find .  | awk '{ print length(), $0 | "sort -n -r" }' | \
            grep -v '^1 \.$' | cut -d/ -f2- > /tmp/AMS2Rpi_1
    touch /tmp/AMS2Rpi_2
    while read line
      do
      BASE=`basename "$line"`
      NEWBASE=`basename "$line" | perl -e '$N = <>; chomp ($N); $N =~ s/[^a-zA-Z0-9.]//g; $N =~ s/_+/_/g; $N= lc($N); $N =~ s/_([a-z])/_.uc($1)/eg; print ucfirst($N);' `
      if [ "$BASE" != "$NEWBASE" ]
      then
      OLDPATH=$(echo "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
      DIR=$(dirname "$line" | sed -r 's/([^a-zA-Z0-9./_-])/\\\1/g')
      echo "mv -i $OLDPATH $DIR/$NEWBASE" >> /tmp/AMS2Rpi_2
      fi
    done </tmp/AMS2Rpi_1
    rm -f /tmp/AMS2Rpi_1
    mv /tmp/AMS2Rpi_2 /tmp/AMS2Rpi
    exit

Then set it to executable and run it:

    cd
    chmod +x AMS2Rpi
    ./AMS2Rpi

When it is finished, I filter out just the directory I want (VERY IMPORTANT):

    cat /tmp/AMS2Rpi | grep "AMSsketches" >~/AMS2RpiQ

(You can look at that file to verify it before running it)

    chmod +x ~/AMS2RpiQ
    ~/AMS2RpiQ

Cleanup if you wish:

    rm /tmp/AMS2R*
    rm ~/AMS2RpiQ

Now the Arduino IDE on the Rpi opens cleanly and all my sketches are there.

Problem solved.   It works great.


body:
Turns out there are two easier answers if you are willing to do it manually.

You can use the Windows-based IDE to load each sketch then save them with an allowable name, before transferring them.

So, instead of going through the program, just do it by hand - this is best if you don't have too many, or if you are very patient.

Or jump in with both feet:  use your USB flash drive to just move your libraries and sketches to the appropriate directories under sketchbook.

    libraries go to ~/sketchbook/libraries
    sketches go to ~/sketchbook/sketches
    Go into the IDE preferences and tell it to look into ~/sketchbook/sketches

Manually rename any directories in both directories so they only have alphanumeric characters in the subdirectory names

The Rpi version of the Arduino IDE has no problem with filenames with underscores.  It is just the directories it rejects if they are not strictly alphanumeric.  But it really prefers that the files have the same names as the directories.

    Each library must be added to the IDE using the
    IDE menu Sketch..Import Library..Add Library

It stores them somewhere else in the IDE's guts.


body:
here's an expression that strips every character that is not ( alpha numeric or space character, or period character) that is also Followed by an alpha numeric or space or period and replaces it by capitalising the following character.
```

find  ./ -depth | perl -wan -F'/' -e ' chomp; chomp($F[-1]);$x=$_; if ($F[-1]=~m/[^\p{Alnum}\d \.]/ and substr($F[-1],0,1) ne ".") {  $F[-1]=~s/[^\p{Alnum}\d \.]+([\p{Alnum}\d \.]{1})/uc($1)/eg; $y = join "\\",@F; system("mv",$x,$y);print "mv \"$x\" \"$y\"\n";}'
```
it ignores unix hidden file starting with "." And it also renames directories.

This will fail on edge cases where the last character in the name is a non alpha character.


message:
Arduino ATmega 2560 frequency measurement

I would like to measure frequency with an Arduino 2560 board. The approach is to use a timer interrupt set to one second and pin interrupt to count interrupts in one second.

The problem I have is that I get the wrong frequency. On my frequency generator I set up a frequency of 1000 Hz in my program I get 1006 Hz instead of 1000 Hz.

What am I doing wrong?

Here is my program. In the stup method I have declared a timer. When the signal comes on pin 2, the counter is increased by 1. After one second passed the flag bData is raised. If the flag is true then I print out a frequency on serial port.

    #include <SPI.h>
    #include <Ethernet.h>
    #include <Math.h>

    byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
    IPAddress ip(192, 168, 1, 177);
    EthernetServer server(80);
    const byte interruptPinTemp = 2;
    const byte interruptPinSlanost = 3;
    //konstante za SBE-3
    const double g = 4.85442486e-003;
    const double h = 6.77300393e-004;
    const double i = 2.65502731e-005;
    const double j = 2.06782794e-006;
    const double f = 1000.0;
    volatile int cnt = 0;
    volatile int cnt1 = 0;
    volatile double slanost = 0;
    volatile double slanost1 = 0;
    int timer1_counter;
    boolean bData = false;
    volatile int dvesek = 1;

    void beriTemperatura() {
      cnt++;
    }

    void beriSlanost() {
      slanost++;
    }

    double calcTemp(double frekvenca) {
      double logRes = log(f / frekvenca);
      return 1.0 / (g + (h * logRes) + (i * pow(logRes, 2.0)) + (j * pow(logRes, 3.0))) - 273.15;
    }

    void setup() {
      Serial.begin(9600);       // inicializacija serijskega porta
      noInterrupts();           // disable all interrupts
      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
      pinMode(interruptPinTemp, INPUT_PULLUP);
      pinMode(interruptPinSlanost, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPinTemp), beriTemperatura, CHANGE);
      attachInterrupt(digitalPinToInterrupt(interruptPinSlanost), beriSlanost, CHANGE);
      TCCR1A = 0;
      TCCR1B = 0;
      timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
      TCNT1 = timer1_counter;   // preload timer
      TCCR1B |= (1 << CS12);    // 256 prescaler
      TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
      interrupts();
    }

    //Timer interrupt na 1 sekundo
    ISR(TIMER1_OVF_vect) {
      // interrupt service routine
      TCNT1 = timer1_counter;   // preload timer
      cnt1 = cnt ;               // prepisemo vrednost v cnt1
      bData = true;             // postavimo flag
      cnt = 0;  // resetiramo counter
    }

    void loop() {
      // če je postavljen flag, da so podatki jih izpišemo ali naredimo karkoli drugega
      if (bData == true) {
        bData = false;
        Serial.println(calcTemp(cnt1), 3);
        Serial.println(cnt1);
      }
    }

Here is the frequency from my generator:

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

And here is a frequency measured with my board:

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

  [1]: https://i.stack.imgur.com/JHtkL.jpg
  [2]: https://i.stack.imgur.com/TsJLC.jpg

What is wrong that I get 1006 Hz instead of 1000 Hz?

If I raise the frequency for example to 5 kHz then I get 5032 Hz in my program (32 Hz to0 much).

Thank you for any advice.

body:
>   TCNT1 = timer1_counter;   // preload timer

When you load the offset (timer1_counter), there are some values in the timer1 prescaler (and potentially TCNT1 if the prescaler isn't sufficient large, or the input pulse train is fast). By assigning a value to TCNT1, you would have written over the values in the prescaler / TCNT1 -> read the datasheet on that.

The solution?

1. Optimal: use a timer with auto-reload function. a timer with output compare can be adopted here as well.

2. Increment the counter: `TCNT1 += timer1_counter; // preload timer`, if timer has a 1:1 prescaler.

Or to use the timer to count the pulse and another to provide the time base.


body:
The Arduino Mega 2560 is clocked off a [ceramic
resonator](https://en.wikipedia.org/wiki/Ceramic_resonator), which
should typically have about 0.5% frequency tolerance. Your readings are
off by 0.6%, which is slightly more than the typical resonator
tolerance. I would them assume there is something wrong with your code,
check dannyf's answer.

Now, if you want significantly better accuracy, I would argue than
relying on the Arduino's internal clock is not a good idea. Even if your
code is perfect you cannot expect good accuracy. You could have better
results if you calibrate that clock instead of just assuming it runs at
16 MHz. But even then, ceramic resonators are notorious for having
a very significant frequency drift. Or you may get an Arduino clocked
off a quartz crystal instead, as these are far more stable.


message:
Using 8-bit instead of 16-bit in Adafruit library

I tried to modify the Adafruit_GFX and Adafruit_ST7735 libraries to make the color variable( as shown in code below) to use 8-bit instead of 16-bit for displaying 8-bit color on LCD screen.

    void Adafruit_ST7735::pushColor(uint16_t color) {
     #if defined (SPI_HAS_TRANSACTION)
       SPI.beginTransaction(mySPISettings);
     #endif
      *rsport |=  rspinmask;
      *csport &= ~cspinmask;

       spiwrite(color >> 8);
       spiwrite(color);

       *csport |= cspinmask;
     #if defined (SPI_HAS_TRANSACTION)
       SPI.endTransaction();
     #endif
    }
I changed it to the below

    void Adafruit_ST7735::pushColor(uint8_t color) {
      #if defined (SPI_HAS_TRANSACTION)
       SPI.beginTransaction(mySPISettings);
      #endif
       *rsport |=  rspinmask;
       *csport &= ~cspinmask;

       //spiwrite(color);
       spiwrite(color);

       *csport |= cspinmask;
    #if defined (SPI_HAS_TRANSACTION)
      SPI.endTransaction();
    #endif
    }
I have made similar changes in other portions of the code. This time nothing was displayed in the LCD(it was blank). However, when the spiwrite(color) is written twice i.e. the comment is removed, the code works fine.
Why is there a need to write 'spiwrite' function twice even in case of 8-bit color?

The original Adafruit library files are also attached.
[drive.google.com/open?id=0B3x_NfKXnhtHR0VBcTNZbk5WT0E][1]

  [1]: http://drive.google.com/open?id=0B3x_NfKXnhtHR0VBcTNZbk5WT0E

body:
I think you / someone asked an identical question here recently.

you didn't say a reason why you want to change a 16-bit type to 8-bit type.

with that said, this should work:

    void Adafruit_ST7735::pushColor(uint8_t color_msb, uint8_t color_lsb) {
       ...
       spiwrite(color_msb);
       spiwrite(color_lsb);
       ...

basically, the original code.


body:
Did you read the datasheet of the LCD screen? The LCD expects you to
send the data in a specific format, and you should comply with that
format rather than invent your own and expect it to magically understand
it. If the LCD expects you to send 16 bits, you should do so. Or maybe
it has a 8 bit mode and there is a way for you to tell it “I'm switching
to 8-bit mode”. Read the datasheet to be sure.

If you want to display 8-bit color on an LCD expecting 16-bit, you
should find a way to map the 8-bit values into 16-bit values. The most
obvious way to map the range [0, 255] to [0, 65535] is to multiply the
8-bit numbers by 65535/255 = 257. Which is the same as sending the byte
twice.


message:
Figuring out IR sensor PWM frequency with Arduino

I'm trying to verify the pulse width of an IR receiver I "borrowed" from one of those cheap RGB controllers (like [thisone][1]) with an arduino nano. But the data I'm getting right now is about 3.4KHz and not the 38KHz I expected.

I'm trying to measure it by connecting the data pin of the IR on INT0 and listening for any change, if the pin goes low I start a measurement, if it goes high I stop the measurement and read out the value.

I'm using Timer1 and no prescaling

My code is as followes

    #include <util/delay.h>

    #define inpin 1 << PIND2
    #define timeron 1 << CS10 //timer no prescale

    bool wasTiming = false;
    short i = 0;

    volatile short timings[20];
    volatile bool print = false;

    volatile short seconds = 0;

    int main()
    {
     USART.begin();

     _delay_ms(500);
     USART.writeln("Arduino online");

     DDRD = 0;

     TCCR1A = 0; //no compares, normal counter mode
     TCCR1B = 0; //clock off

     EICRA = 1 << ISC00; // Any change INT0 (PD2)
     EIMSK = 1 << INT0; // INT0 interrupt enable

     sei();

     char buff[20];
     for (;;)
     {
      if (print)
      {
       print = false;

       for (short j = 0; j < 20; j++)
       {
        sprintf(buff, "% 6d ticks", timings[j]);
        USART.writeln(buff);
       }
      }
     }
     USART.end();

     return 0;
    }

    ISR(INT0_vect)
    {
     if (PIND & inpin) //pin high
     {
      if (wasTiming)//
      {
       TCCR1B = 0; //timer clock off
       timings[i] = TCNT1;
       TCNT1 = 0; //empty timer register
       wasTiming = false;

       i++;
       if (i == 20)
       {
        print = true;
        i = 0;
       }
      }
     }
     else // pin low
     {
      if (!wasTiming)
      {
       TCCR1B = timeron; //timer clock on
       wasTiming = true;
      }
     }
    }

and the output data is

     13902 ticks
      8865 ticks
      9961 ticks
      8877 ticks
      9968 ticks
      9842 ticks
      8506 ticks
      9896 ticks
      9585 ticks
      9865 ticks
      9541 ticks
      8853 ticks
      9545 ticks
      8888 ticks
      9885 ticks
      9954 ticks
      8515 ticks
      9885 ticks
      8909 ticks
      9874 ticks

on average that looks like about 9500 ticks, which leads me to the following calculation: `(16,000,000 / 9,500) * 2 = 3,368.4Hz`

Am I doing something wrong here? Or is the data that I'm getting correct, in which case, how would I go about turning that into 1's and 0's?

I'm not really looking for off-the-shelf solutions, half the fun of doing this is figuring it out myself. Eventually I'm gonna build my own RGB controller with this to replace that cheapo thing I already have (it has a few flaws I would like to correct).

  [1]: https://lh5.ggpht.com/1ZM32b8_tK1xyMdDd_oZdmRj1xEWlM4Mp4R3l3MFnY6eurJPUpf0semo3eMgMCFoPjI=h900

body:
You mistakenly believe that the *carrier frequency* of 38 kHz should be available at the data output pin of the infrared detector chip. These chips provide a logic output indicating *the presence of 38 kHz*. Most are frequency-selective, being more sensitive at **one frequency** somewhere between 35 kHz - 60 kHz.

A data sheet pulled at random specifies typical pulse bursts that might be used to encode digital data (pulse burst timing highlighted in red):

[![infrared remote receiver pulse burst timing][1]][1]

In your case, \$f_o\$ might be close to 38 kHz. No fewer than six cycles \$t_{pi}\$ are recommended for the length of one *baud*. Perhaps your transmitter includes a few more cycles (ten or eleven?) to be safe. The receiver circuitry requires about five cycles before commit, \$t_d\$. Hopefully, a similar delay at end-of-pulse occurs, but the graph at right suggests the end-of-pulse extends a little longer than \$t_d\$. However, pulse width is impressively constant over five magnitudes of infrared intensity.

Note that the presence of a burst of 38 kHz from the transmitter most often sends the output of the receiver to a logic low. No optical signal yields a logic high at receiver output, sometimes with a fast false-detect glitch (which should be rejected if its length is short). A large-value pull-up resistor added between output pin and Vdd may be required to ensure that an idle receiver goes to logic high.

You will still have to determine how these pulse bursts are encoded into logical bits. Many protocols exist, some use pulse position, others use pulse length encoding.

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


message:
How do I specify a particular pin to use as output for the Print class?

all.

I'm attempting to write a class that inherits from the Print class.  I only need serial output.

However, I'm having difficulty locating any reference on how to specify which pin on the ATMega my class will use as output of the write(...) functions.

How does the Print class know where to send output to ??

Thanks in advance.

body: The parent class (your class, in this case) provides read() and write() functions which in turn, know what ports to use. Presumably those were provided to the parent class' constructor. Now the Print class just has to know the standard function names.


body:
You need to do far more than just "specify a pin". You need to write the software that transmits data through that pin in your chosen format.

You cannot send data through a pin. You can only set a pin HIGH or set a pin LOW. It is the sequence (and most importantly the *timing*) of setting a pin HIGH and LOW that constitutes sending data.

So you have to write the software that sets the pin HIGH and LOW in the right way and at the right time.

Fortunately sending is far simpler than receiving, as you can see if you look at the source code to SoftwareSerial.

Specifying the pin itself though is simple:

    class MyClass : public Print {
        private:
            uint8_t _pin;

        public:
            MyClass(uint8_t pin);
            size_t write(uint8_t data);
    };

    MyClass::MyClass(uint8_t pin) {
        _pin = pin;
    }

    size_t MyClass::write(uint8_t data) {
        // In here you do whatever you have to in order
        // to manipulate _pin in the right way to send your data.

        // Don't forget to return the number of bytes written (there
        // is only one, so either 1 for "it got sent" or 0 for "it
        // didn't get sent".
        return 1;
    }

It can be quite useful to have a `begin()` function for setting things up, such as configuring the right `pinMode()` for `_pin`, and maybe setting a baud rate like `Serial` does (although for simplicity you may choose to just have a single fixed baud rate, which means you can pre-calculate delay loops etc).