message:
Arduino controlled light dimmer software

I found this software:

    /*

    AC Voltage dimmer with Zero cross detection
    Author: Charith Fernanado   http://www.inmojo.com

    Adapted by DIY_bloke
    License: Creative Commons Attribution Share-Alike 3.0 License.
    Attach the Zero cross pin of the module to Arduino External Interrupt pin
    Select the correct Interrupt # from the below table
    (the Pin numbers are digital pins, NOT physical pins:
    digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)
    check:   http://www.inmojo.com

    Pin    |  Interrrupt # | Arduino Platform
    ---------------------------------------
    2      |  0            |  All -But it is INT1 on the Leonardo
    3      |  1            |  All -But it is INT0 on the Leonardo
    18     |  5            |  Arduino Mega Only
    19     |  4            |  Arduino Mega Only
    20     |  3            |  Arduino Mega Only
    21     |  2            |  Arduino Mega Only
    0      |  0            |  Leonardo
    1      |  3            |  Leonardo
    7      |  4            |  Leonardo
    The Arduino Due has no standard interrupt pins as an iterrupt can be attached to almosty any pin.

    In the program pin 2 is chosen
    */
    int AC_LOAD = 3;    // Output to Opto Triac pin
    int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

    void setup()
    {
      pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
      attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
    }

    //the interrupt function must take no parameters and return nothing
    void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
    {
      // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
      // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
      // For 60Hz => 8.33ms (10.000/120)
      // 10ms=10000us
      // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

      int dimtime = (75*dimming);    // For 60Hz =>65
      delayMicroseconds(dimtime);    // Wait till firing the TRIAC
      digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
      delayMicroseconds(10);         // triac On propogation delay
         // (for 60Hz use 8.33) Some Triacs need a longer period
      digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
    }

    void loop()  {
      for (int i=5; i <= 128; i++){
        dimming=i;
        delay(10);
       }
    }

But don't uderstand this part:

> (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

I know 10000us is 10ms, and we need to wait less then 10ms to dim light.

But don't understand why here we has -10us and /128.

Anyone know why is that?

body: -10uS because of the 10uS delay at the end of the loop, and /128 because he has decided there will be 128 possible dimming levels.


sender: user

message:
How to wire and use a B10K linear LED potentiometer?

I've bought some nice looking LED potentiometers from Ebay. They look like [this][1].
I'm very new to low level electronics/hardware and I don't know how to wire it. It has 4+2 pins.
Also, how to use it in the Arduino?

  [1]: https://www.google.co.uk/search?q=b10k potentiometer&espv=2&biw=1270&bih=701&site=webhp&source=lnms&tbm=isch&sa=X&ved=0ahUKEwjM7-TM26DLAhUBOJoKHT3hAAUQ_AUIBygC#tbm=isch&q=b10k potentiometer linear led&imgrc=XY_E0nFmWPaxzM:

sender: assistant

body:
The Taiwan Alpha [spec sheet page 2](http://www.taiwanalpha.com.tw/english2014/p_e_086.htm) for this type of pot shows a little information about the pinout.  Refer to the second “P.C.B. MOUNTING HOLE DETAIL” diagram, which apparently shows the top side PCB layout.  The LED's anode is at lower right, marked B; its cathode is lower left, marked E.  It doesn't say what L (the pin next to E) is.  The three numbered pins most probably are: 1 and 3, ends of the resistive element.  2, wiper.

If that is correct, you could attach pin 1 to 5V, pin 3 to ground, and pin 2 to an analog input.  Before hooking it up like that, however, take ohmmeter readings from pin 1 to pin 2 as you move the slider from one end to the other and see if readings change proportionately to position.

Note, the phrase “Center Dent” on the ebay page probably should instead be “Center Detent” or  “Center Click”.


message:
How to stop uno from running program when powered on?

Does anyone know how to prevent the Uno from running the last program when it's powered on?

Many times I have changed hardware and wiring without clearing the program first.  Then when I power it on to upload the new program it will run the old program until it's uploaded.  This has many potential unwanted effects when the old program is running with the new hardware installed.

body:
The simplest thing is to upload the new program before connecting the hardware.

If this isn't practical, connect a jumper wire from the Reset pin to ground (Gnd) before powering it on. This will hold in a reset state, and the program won't run.

Then, compile and upload your program. As it starts to upload remove the reset wire. That should upload it without running any existing program.


message:
Return value of 0 if value is less than zero

Background: I am using an analog pressure sensor with a range from 0-100PSI returning voltage values .44v to 4.44v. It's open air (or 0 PSI) voltage on the signal pin is .47 volts. I have a function that subtracts that .47v (to make zero) and then multiplies it by 25 (25 PSI per volt). Due to signal noise or other factors, sometimes my function returns a negative number, which wreaks havoc on my math. I would like to return a value of 0 when my offset math returns a negative number, but I'm having a problem with it.

The code that I wrote that doesn't work:

    double EngineOilPressure() {
        //insert oil pressure code here
        int reading = analogRead(sensorPin3);
        float voltage = reading * 5.0;
        voltage /=1024.0;

        Serial.print(voltage); Serial.println(" volts");

        if (voltage-.47 < 0)
        {
            float voltadj = 0;
        }
        else
        {
            float voltadj = (voltage-.47);
        }

        float pressureP = voltadj * 25;
        return PSIToPascal(pressureP);
    }
The error that I get is

    dynamic_engine.pde: In function 'double EngineOilPressure()':
    dynamic_engine.pde:41:23: error: 'voltadj' was not declared in this scope
    Error compiling.

The code that works but sometimes returns a very wrong value:

    double EngineOilPressure() {
        int reading = analogRead(sensorPin3);
        float voltage = reading * 5.0;
        voltage /=1024.0;

        Serial.print(voltage); Serial.println(" volts");

        float pressureP = (voltage - .47) * 25;
        return PSIToPascal(pressureP);
    }

body:
The scope of each of the two different and unrelated `voltadj` variables that your code (as below) declares is limited to within its enclosing set of braces.

    if (voltage-.47 < 0)
    {
        float voltadj = 0;
    }
    else
    {
        float voltadj = (voltage-.47);
    }

Instead perhaps say

    float voltadj = voltage-.47;
    if (voltadj < 0) voltadj = 0;

or perhaps

    float voltadj = voltage < .47? 0 : voltage-.47;

or

    float voltadj = constrain(voltage-0.47, 0.0, 5.0);

or

    float voltadj = max(0.0, voltage-0.47);

Also see [max()](https://www.arduino.cc/en/Reference/Max) and [constrain()](https://www.arduino.cc/en/Reference/Constrain) reference pages at arduino.cc.


body:
Another method, though one that is quite cryptic to understand, would be:

    float pressureP = voltage > 0.47 ? (voltage - 0.47) * 25 : 0;

That is known (by me at least) as an *inline conditional*.  The `?` acts as an `if` operator, and the `:` as an else.  Basically it's saying:

    Voltage is greater than 0.47
    Is that true?
        then subtract 0.47 and multiply by 25 and assign it
    otherwise:
        assign 0

The format is simply:

    value = {condition} ? {true value or expression} : {false value or expression};

If can be quite useful when you want to conditionally calculate or assign something.  @jwpat7 makes mention of a `max()` function above.  That `max()` function can itself be written with this inline conditional format:

    maxval = a > b ? a : b;

Or: If `a` is greater than `b` then assign `a` otherwise assign `b`.


body:
The Arduino way is to use [constrain][1]

    float pressureP = constrain ((voltage - 0.47) * 25 , 0 [The Maximum your code can handle]);

This will return the value ((voltage - 0.47) * 25) but never less than 0 and never more than The maximum you provide.

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


message:
Configure HC-05

I am trying to send/receive data from Android to my Arduino (via a HC-05) and later from Arduino to Android. I have configured my HC-05 as slave, and the UART=9600,0,0.... To send data from Android to Arduino I don´t have problem but to send data Arduino to Android I can not...

This is my sketch:

<!-- language: c -->

    char data;
    int a=1;
    int v=1;
    #include SoftwareSerial connection(10,11);//RX|TX
    void setup()
    {
     pinMode(7,OUTPUT);
     connection.begin(9600);
     digitalWrite(7,LOW);
    }

    void loop()
    {
     if(connection.available()>0)
     {
      data=connection.read();
       if(data=='1')
       {
        digitalWrite(7,HIGH);
        connection.write(data);
        delay(200);
       }
       //connection.write(data);
      }
     }

MY HANDLER IN THE MAIN:

           mhandler=new Handler()        {
            public void handleMessage(android.os.Message msg)            {
                switch (msg.what)
                {
                    case MENSSAGESEND:
                        msg = new DriveData((BluetoothSocket)msg.obj);    //DriveData msg = new DriveData((BluetoothSocket)msg.obj);
                        break;
                    case MESSAGEREADING:
                        byte[] bufferget = (byte[])msg.obj;
                        String men = new String(bufferget,0,msg.arg1);
                        sb.append(men);
                        int endline=sb.indexOf("\n");
                        if(endline>0)
                        {
                            String print=sb.substring(0,endline);
                            sb.delete(0, sb.length());
                            Toast.makeText(getApplicationContext(),"menssage"+" "+print,Toast.LENGTH_LONG).show();
                            txtData.setText(print);
                        }
                        break;

                }
            };
        };

MY METHOD FOR RECEIVER AND SEND DATA

      public void run()
        {
            byte[] wait=new byte[1024];
            int bytesReceived;
            while (true) {
                try {
                     bytesReceived=entrydata.read(wait);//entrydata is my inputstream
                    mhandler.obtainMessage(MESSAGEREADING,bytesReceived,-1,wait).sendToTarget();
                }catch (IOException e){
                    break;
                }
            }
        }

body:
You are missing the line termination
you must send '\n' after your data in order to receive the data
or use
conexion.println(entrada)
rather then
conexion.write(entrada)


message:
Works with gcc, not with Arduino. error: taking address of temporary array

I need to hard code 8 byte addresses into char arrays of length 8. This must be done many places in my code (in function scope), so I have tried to come up with a one-liner. The following works perfectly in C when compiling with gcc.

 char a[8];

 void cpaddr(char target[], char *source) {
  int i;
  for (i=0; i<8; i++)
   target[i] = source[i];
 }

 int main() {
  char b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
  cpaddr(a, b);

  // line below does not compile with Arduino IDE
  cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
 }

When compiling on Arduino the last line, which is the one-liner I was aiming for, does not compile. It gives:

 /home/bob/Desktop/ate/Ate.ino: In function 'int main()':
 Ate:101: error: taking address of temporary array
 cpaddr(a, (char[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
 ^
 exit status 1
 taking address of temporary array

What is the problem here, that apparently is not a problem with gcc?

How do I fix it?

body:
It is quite right, using that kind of syntax is not allowed. It's a bit of a pain, but it's ok since there is an alternative method - kind of a "trick" if you will.

That trick is to use a string, not an array. After all, a string is just an array, it's just handled slightly differently by the compiler.

Instead of using `{...}` use `"..."` and use the hexadecimal character escape sequence `\xNN`, such as:

    cpaddr(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D");

You could even lose your custom function and use a standard library function - `memcpy()`:

    memcpy(a, "\x00\x10\xFF\xCA\x00\x00\xA2\x7D", 8);

On the 8-bit AVRs you can save RAM by using the progmem variant and the `F()` macro:

    memcpy_P(a, F("\x00\x10\xFF\xCA\x00\x00\xA2\x7D"), 8);


body:
See [Using array init list as temporary in C++11?](https://stackoverflow.com/questions/15458883/using-array-init-list-as-temporary-in-c11)

You can solve it by using `const`. This compiles:

    char a[8];

    void cpaddr(char target[], const byte *source) {
        int i;
        for (i=0; i<8; i++)
            target[i] = source[i];
    }

    int main() {
        byte b[] = {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D};
        cpaddr(a, b);
        cpaddr(a, (const byte[]) {0x00, 0x10, 0xFF, 0xCA, 0x00, 0x00, 0xA2, 0x7D});
    }

Note I had to change your array from `char` to `byte` because I was getting (valid) warnings that things like 0xCA don't fit into a char.


body:
> How do I fix it?

"Char []" shouldn't compile under c. It is just invalid.

You can use string, cast to char * . or just another pointer as you did already.


message:
Fritzing PCB design review/questions

I've designed an PCB and due tot the delivery times, I kinda want to order it right now.
I don't yet have the components, so I haven't actually tried it on a breadboard.

Now I'm unsure if the PCB would work, as this also is my first try in PCB design.

It's a single-sided PCB.
All parts (should be) through hole.
I would be using SoftwareSerial since the ATTiny does not have serial (Rx/Tx).

[TL:DR] Would this PCB work?

Some points of which I'm unsure, or might be a problem:

 1. Is the spacing of the board/lines to other components/side big enough?
 2. Should I use a copper/ground fill? Which and why?
 3. Are the rounded-off traces actually better as sharp edges?
 4. It says: 36mm by 15mm isn't this too small to fit all those components?
 5. Can I actually use the RESET pin as other functions (without changing fuse bits)?
 6. Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

**Breadboard**

[![Breadboard][1]][1]

**Schematic**

[![Schematic][2]][2]

**Layout**

[![Layout][3]][3]

**File**

If someone needs the file:
It's opensource, no restrictions. Would be nice to give me some credits/donation, but you can freely use it for even commercial projects.
Download below:

https://www.dropbox.com/s/lggjg5fxd6s3kqc/ATTINY485.fzz?dl=0

Some credits to [Nick Gammon][4], I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).

**Version2!**

[![schematic][5]][5]

[![layout][6]][6]

Changes:
 - replaced the "V" shape.
 - pull-up on the reset pin.
 - decoupling capacitors

EDIT: It's better not to use a pull-up resistor on the reset line. The ATtiny85 has this internally.

  [1]: https://i.stack.imgur.com/okCNw.png
  [2]: https://i.stack.imgur.com/1iPyH.png
  [3]: https://i.stack.imgur.com/9lvmo.png
  [4]: http://www.gammon.com.au/forum/?id=11428
  [5]: https://i.stack.imgur.com/aFiLp.png
  [6]: https://i.stack.imgur.com/saaRD.png

body:
> Would this PCB work?

Possibly, sometimes, under some conditions. See below.

> Is the spacing of the board/lines to other components/side big enough?

Plenty.

> Should I use a copper/ground fill? Which and why?

For your circuit there is no real electrical reason to use a ground plane. However, many fab houses like you to use at least a copper fill in the empty areas since it means less copper has to be etched off the board, and so their etchant lasts longer before it needs to be replaced.

> Are the rounded-off traces actually better as sharp edges?

Yes. Always try to avoid right-angles. Sharp corners radiate EMI noise, mitred corners radiate a lot less.

> It says: 36mm by 15mm isn't this too small to fit all those components?

Not in the slightest.

> Can I actually use the RESET pin as other functions (without changing fuse bits)?

You can only disable the RESET functionality of the RESET pin using the fuse bits - and then it becomes somewhat difficult to program: you need a HVSP (High Voltage Serial Programmer) to get it back into programming mode again.  [This blog post details how it is done.](http://projectsfromtech.blogspot.co.uk/2013/04/using-reset-pin-as-io-on-attiny8545.html)

> Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Your circuit isn't complete.  There are a couple of things missing that you need to add, and some that you might want to add.

The things that are missing:

* Decoupling capacitors (100nF) on the power pins of both chips
* You should have one larger (10µF typical) reservoir capacitor at the power entry to the board
* (Assuming RESET is enabled) Pullup resistor on the RESET pin

The things you might want to add:

* RS-485 bus termination resistors

The latter are optional depending on where in the bus your module is. You need termination resistors at both ends, so it is common to have them on the boards but with jumpers to enable/disable them.


body:
>Is the spacing of the board/lines to other components/side big enough?

Looks ok.  You might be able to squeeze it a few mm smaller each way, although since the board already is small, that probably would make little difference in cost.

>Should I use a copper/ground fill? Which and why?

Copper/ground fill on a single-sided board won't make much difference for this circuit.  It would be reasonable, however, to make the ground traces two or three times as wide as they are.

>Are the rounded-off traces actually better as sharp edges?

If you mean, make square corners rather than the 45° turns as shown, either way will make little difference for this circuit.  The 45° turns are ok.

Note, sharp V-notches, like the one inside the traces at pin 2 of the Tiny85, are undesirable; I think they etch less accurately than more-open junctions do.

>It says: 36mm by 15mm isn't this too small to fit all those components?

Looks like there's room to spare and the board could be made slightly smaller.

For homemade boards that are drilled using a hand-cranked XY table, keeping drilled holes on the intersections of a .1"x.1" grid is a good idea.  For commercially-made boards, it's less important but can help with assembly.

*Edit:* Regarding “Making ground traces bigger makes sense, but does that also mean 5V traces should be bigger?”, yes, both ground and power traces typically should be large, if board layout allows.  It's desirable that those traces have low inductance and it's ok to have high capacitance between ground and power traces.

Regarding how long it takes to get your PCB back from a manufacturer: The [PCBshopper.com website](http://pcbshopper.com/) makes it easy to compare time vs cost across a range of manufacturers.  For small circuits like yours, [OSHpark](https://oshpark.com/) is an inexpensive choice (you would get three double-sided boards for under $5, in about 15 days).  If you need up to about 10 medium-size boards, [Maker Studio](http://makerstudio.cc/index.php?main_page=index&cPath=8) is quite economical but standard delivery may be slow (2-3 weeks).  If you are in a hurry and need a larger number of boards, consider (eg) [PCBway](http://www.pcbway.com/).  By paying $25 for DHL shipping, you can have a batch of boards in 9 or 10 days – about three days for manufacture and a week for delivery.  The pictures below show an example of PCBway's order tracking, the left side at about two days after the order was placed, the right side 11 hours later.  This order for 50 each 36 mm x 56 mm two-layer boards with silk both sides cost $27 for manufacture and $25 for delivery.

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

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


message:
How do I calibrate an ESC after connecting it to an Arduino?

I'm trying to connect an Arduino to an Electronic Speed Control and failing horribly. I'll explain what I've done so far, and then I'll explain the problem.

Before we get there, here's the list of parts I'm using:

- Arduino Uno (genuine)

- 6V to 8.4V rated 18300 RPM 350 g-cm brushed motor.

- Traxxas XL-5 brushed motor ESC. 1600 Hz is the highest PWM signal it accepts, if I'm not wrong.

- Venom 4200mAh NiMH 8.4V battery pack (will replace soon with a 7.2V).

So I first connected the ESC to the motor. The connection is this bullet lead connection (the connection seems intact), and then the ESC to the Arduino. I connected the white wire to pin 9 and the black wire to ground. If I'm not wrong, this is the standard servo motor setup. I then plugged the Arduino into my computer, which has an intact USB port. Lastly, I connected the battery pack to the ESC.

Now I've tried to upload some basic code to try and calibrate my ESC, but it just plain our refuses to work. Under no circumstances will the motor run.
The code I'm using just sends the signal sent by the signal monitor.

I'm a complete noob to Arduino, so I don't know what could be wrong. The program I have in mind needs to be able to run while not connected to the computer, activate when a push-button switch is activated, run the motor for a certain distance (which involves an encoder, right?), and then stop.

Any pointers or things I could be doing wrong?

<!-- language: c -->

    int value = 0;
    Servo myservo;
    void setup() {
        firstESC.attach(9);    // attached to pin 9
        Serial.begin(9600);
    }
    void loop() {
        myservo.writeMicroseconds(value);
        if(Serial.available())
            value = Serial.parseInt();    // Parse an Integer from Serial
    }

and the one here:

<!-- language: c -->

    #include <Servo.h>
    #define MAX_SIGNAL 2000
    #define MIN_SIGNAL 700
    #define MOTOR_PIN 9
    Servo motor;
    void setup() {
        Serial.begin(9600);
        Serial.println("Program begin...");
        Serial.println("This program will calibrate the ESC.");

        motor.attach(MOTOR_PIN);

        Serial.println("Now writing maximum output.");
        Serial.println("Turn on power source, then wait 2 seconds and press any key.");

        motor.writeMicroseconds(MAX_SIGNAL);

        // Wait for input
        while (!Serial.available());
        Serial.read();

        // Send min output
        Serial.println("Sending minimum output");
        motor.writeMicroseconds(MIN_SIGNAL);
    }
    void loop() {
    }

^shamelessly copied from the internet

body:
The is a standard with RC connectors, that is Black always goes to ground white/orange goes to the signal and red/brown goes to 5V.

I don't know if you have made a typo, but you need to connect the white to D9 and the black to GND. [Here is a instructables post][1], it describes using a brushed ESC step two reiterates the colour code standard.

You would also need a rotary encoder or shaft encoder to tell the distance moved, there are lots of ways to achieve this from simple(coded disk and IR arrangement) to custom made PCB add-ons.

  [1]: http://m.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/http://m.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/?ALLSTEPS


body:
Calibration can be done by sending the low throttle and high throttle values through the Serial monitor.Here's [an instructable][1] i have made using NODEMCU.Check this out.May be it helps.

  [1]: https://www.instructables.com/id/Quadcopter-With-Nodemcu-and-BlynkWithout-Flight-Co/


message:
error while loading libtinfo.so.5 - SOLVED

I just installed the 1.6.7 version and want to upload it a sketch to Arduino UNO hardware. I get error message:

>/home/pali/Irataim/TarBalls/Arduino/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory

I'm on Gentoo linux operating system.

How can I solve this problem?

By following this link:

[https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6][1]
  [1]: https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6

I just add tinfo USE flag to ncurses package, re-emerged it and can run Arduino IDE that I emerged from Gentoo repository.

body:
Install `libtinfo5`, the terminfo library.

If that doesn't help, you can try to debug the problem yourself. First,
check which libtinfo avrdude is looking for:

    ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo

On my Ubuntu, I get this:

 libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fa74a888000)

Next, see where your libtinfo is installed:

    find /lib /usr/lib -name 'libtinfo*'

On my system I get:

    /lib/x86_64-linux-gnu/libtinfo.so.5
    /lib/x86_64-linux-gnu/libtinfo.so.5.9

Do you have any discrepancy between the two?


body:
You have to rebuild `sys-libs/ncurses` with `tinfo` USE flag turned on. (You can also make a symlink: `libtinfo.so -> libncurses.so`, but it's not elegant solution).

Firstly, check if you have a record for ncurses in any file in `/etc/portage/package.use`. If not, create a file `/etc/portage/package.use/ncurses` with such content:

    sys-libs/ncurses tinfo

then, rebuild ncurses:

    emerge -av sys-libs/ncurses


message:
Neopixel Ring - How to breathe in a circle motion?

I'm trying to get an effect like (https://vine.co/v/Mwwbi5a1BFK) using a neopixel ring. I can get the neopixels to turn on and off in a circle motion and I can get the neopixels to fade all at once. What I can't get working is combining the two together. Any help would be much appreciated!

*EDIT* Tried making fade with the circle motion

    #include <Adafruit_NeoPixel.h>          // Library for NeoPixels

    #define pinPix 6                       // Pin driving NeoPixel Ring or String
    #define numPix 8                       // Number of NeoPixels in the Ring or Strip

    // Setup NeoPixel Ring
    // Parameter 1 = number of pixels in strip
    // Parameter 2 = pin number driving the strip
    // Parameter 3 = pixel type flags, add together as needed:
    //   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
    //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
    Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

    void setup() {
      myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
      myNeoPixels.show();    // turn all pixels off, and upload to ring or string

    }

    void loop() {
      ledTrail(50, 100, 100,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
    }

    // Pause = delay between transitions
    // Rf, Gf, Bf = RGB "Foreground" values
    // Rb, Gb, Bb = RGB "Background" values
    const byte extra = 4;  // how many ahead, and behind, to light up

    // Pause = delay between transitions
    // Rf, Gf, Bf = RGB "Foreground" values
    // Rb, Gb, Bb = RGB "Background" values
    void ledTrail(int pause, int steps, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

      int tmpR, tmpG, tmpB;         // Temp values
      // Fade up
      for (int s=1; s<=steps; s++) {
        tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
        tmpG = (Gf * s) / steps;
        tmpB = (Bf * s) / steps;

      for (int i=0; i<numPix; i++) {
        myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

        // now go "extra" pixels ahead and behind
        for (int s = 1; s < extra + 1; s++)
          {
          tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
          tmpG = (Gf * (extra - s)) / extra;
          tmpB = (Bf * (extra - s)) / extra;
          myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
          myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
          }

            // Fade down
      for (int s=steps; s>0; s--) {
        tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
        tmpG = (Gf * s) / steps;
        tmpB = (Bf * s) / steps;
      }

        myNeoPixels.show();
        delay(pause);
      }
       }
    }

*LED TRAIN CODE*

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>          // Library for NeoPixels

    #define pinPix 6                       // Pin driving NeoPixel Ring or String
    #define numPix 8                       // Number of NeoPixels in the Ring or Strip

    // Setup NeoPixel Ring
    // Parameter 1 = number of pixels in strip
    // Parameter 2 = pin number driving the strip
    // Parameter 3 = pixel type flags, add together as needed:
    //   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
    //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
    Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

    void setup() {
      myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
      myNeoPixels.show();    // turn all pixels off, and upload to ring or string

    }

    void loop() {
      ledTrail(100, 255,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
    }

    // Pause = delay between transitions
    // Rf, Gf, Bf = RGB "Foreground" values
    // Rb, Gb, Bb = RGB "Background" values
    void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

      for (int i=0; i<numPix; i++) {
        myNeoPixels.setPixelColor(i,Rf,Gf,Bf);
        myNeoPixels.show();
        delay(pause);
      }

      for (int i=0; i<numPix; i++) {
        myNeoPixels.setPixelColor(i,Rb,Gb,Bb);
        myNeoPixels.show();
        delay(pause);
      }
    }

*BREATHING CODE*

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>          // Library for NeoPixels

    #define pinPix 6                       // Pin driving NeoPixel Ring or String
    #define numPix 8                       // Number of NeoPixels in the Ring or Strip

    // Setup NeoPixel Ring
    // Parameter 1 = number of pixels in strip
    // Parameter 2 = pin number driving the strip
    // Parameter 3 = pixel type flags, add together as needed:
    //   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
    //   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
    //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
    //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
    Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

    void setup() {
      myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
      myNeoPixels.show();    // turn all pixels off, and upload to ring or string

    }

    void loop() {
      breathe(20, 100, 255,255,255);       // Pause; Number of steps; Full-on R,G,B values
    }

    // Pause = delay between transitions
    // Steps = number of steps
    // R, G, B = Full-on RGB values
    void breathe(int pause, int steps, byte R, byte G, byte B) {

      int tmpR, tmpG, tmpB;         // Temp values

      // Fade up
      for (int s=1; s<=steps; s++) {
        tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
        tmpG = (G * s) / steps;
        tmpB = (B * s) / steps;

        for (int i=0; i<numPix; i++) {
          myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
        }
        myNeoPixels.show();
        delay(pause);
      }

      // Fade down
      for (int s=steps; s>0; s--) {
        tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
        tmpG = (G * s) / steps;
        tmpB = (B * s) / steps;

        for (int i=0; i<numPix; i++) {
          myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
        }
        myNeoPixels.show();
        delay(pause);
      }

      delay(pause * 30);
    }

body:
I don't have any NeoPixels to try it with (yet) however this should do it. Replace the ledTrail function by this:

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

    const byte extra = 4;  // how many ahead, and behind, to light up

    // Pause = delay between transitions
    // Rf, Gf, Bf = RGB "Foreground" values
    // Rb, Gb, Bb = RGB "Background" values
    void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

      int tmpR, tmpG, tmpB;         // Temp values

      for (int i=0; i<numPix; i++) {
        myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

        // now go "extra" pixels ahead and behind
        for (int s = 1; s < extra + 1; s++)
          {
          tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
          tmpG = (Gf * (extra - s)) / extra;
          tmpB = (Bf * (extra - s)) / extra;
          myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
          myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
          }

        myNeoPixels.show();
        delay(pause);
      }
    }

What this is doing is having an inner loop that "looks ahead" and behind another `extra` pixels and makes them brighter/darker. Debugging code (since removed) shows the effect:

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

    i = 4, R = 255, G = 255, B = 255   <-- original code
    i = 5, R = 191, G = 191, B = 191   <-- one ahead  (darker)
    i = 3, R = 191, G = 191, B = 191   <-- one behind (darker)
    i = 6, R = 127, G = 127, B = 127   <-- two ahead  (darker still)
    i = 2, R = 127, G = 127, B = 127   <-- two behind (darker still)
    i = 7, R = 63, G = 63, B = 63      <-- and so on
    i = 1, R = 63, G = 63, B = 63
    i = 8, R = 0, G = 0, B = 0
    i = 0, R = 0, G = 0, B = 0


message:
ESP8266 shows garbage in serial monitor

I have my ESP8266 connected via serial to USB like the image shows: [![enter image description here][1]][1]

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

It worked just fine, however, when I tried flashing Blynk code

<!-- language: c -->

    #define BLYNK_PRINT Serial
    #include <ESP8266WiFi.h>
    #include <BlynkSimpleEsp8266.h>

    char auth[] = "YourAuthToken";

    void setup()
    {
      Serial.begin(9600);
      Blynk.begin(auth, "ssid", "pass");
    }

    void loop()
    {
      Blynk.run();
    }

It started outputting loads of garbage in the serial monitor, while Blynk app said ESP is not connected to network. I've tried since then flashing empty sketches or some other stuff, whatever I do, serial monitor shows loads of junk. I've tried changing modes, I've tried changing baud rates (57600 was default, and AT worked just fine).

Junk example:

      …ÕZªP‚,JHVYº—¡VÕ]J*ÉW¥¡Õ¥Õ-”ªUŠQd®”¡âJ%H
    !HiZÊIIRPÖuUPÒ‚BñZT¥ *EUeZB\)*EVjU!\©Š_¥¢”ÅVªqYiUµP”¬ÕPQT°*uH)HZKB*ÕXªuH!HBHBH…µEIâHBH!H©ªqY+hZVB\BH!HÊ*Òµe�qHBHBHŠ*i±…Z¦-hUµPÔ¬ÔPQT°*uH)H-KB*ÕXªuH!HBHBH…µEB\!H!HBVªqY+iZVB\BH!HeVÒZ¢qHBHBHŠ*iQ…Z¦-hUµPÔ¬ÔPQTaYRB\ jHiBHªaYRB\BH!HBVªaYRB\BH!HBVªqY+iZVB\BH!HÊVÒZ¢qHBHBHŠ*i±Õ\V
    iUµPÔ¬ÕPQT°*uH)H-JBVªaYRB\BH!H!VªaYR!\BHBH!Vªq©+hZW!\BHBHJ*iµE�âHBH!HŠ*i±…Z¦-hUµPÕ¬ÔPQTaYR!\ %Hi!HÕXªuH!HBHBH…µEIqHBHBH

body: Have you also pulled up the ESP8266's reset pin? I don't know what effect not doing so might have, but the recommended connections I have read and followed include that. The RST and CH_PD pins are adjacent; they're easy to jumper together.


body:
Try stabilizing the power source.

I parallel connected two AA batteries with the Arduino's 3.3V output and the garbage disappeared and my ESP8266-01 got much more stable.


body:
In this case, it looks like your Serial Monitor just isn't set to the right baud rate with Both NL & CR. Even if your monitor is set to the default 115200 baud rate, you'll still see some garbage characters which leads into the next issue.

Using 115200 has too many instructions for the Arduino Uno to reliably decode characters and that's where the garbage is coming from.

The ESP8266 default baud is 115200, so you need to connect at the default rate and issue an AT command to reduce the baud rate to 9600.

Each time you reset, the ESP8266 goes back to the default baud rate.

Here's an example script that connects at the default baud rate and then reduces it to 9600. You'll connect the Serial Monitor at 9600. At the lower baud rate, I'm not getting any garbage characters.

    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup()
    {
      Serial.begin(9600);
      ESPserial.begin(115200);
      ESPserial.println("AT+IPR=9600");
      delay(1000);
      ESPserial.end();
      // Start the software serial for communication with the ESP8266
      ESPserial.begin(9600);

      Serial.println("Ready");
      ESPserial.println("AT+GMR");
    }

    void loop()
    {
        // listen for communication from the ESP8266 and then write it to the serial monitor
        if ( ESPserial.available() )   {  Serial.write( ESPserial.read() );  }

        // listen for user input and send it to the ESP8266
        if ( Serial.available() )       {  ESPserial.write( Serial.read() );  }
    }

An odd thing that happened to me is that I tried to use a baud rate of 4800 and I bricked one ESP8266 module. I don't know if that was a glitch or just a coincidence.


body:
I had a similar problem with a NodeMCU ESP-12E (Amica v2) board... after pressing and releasing the RST button with Serial Monitor open & set to 115200 baud, it would display the boot message (starting with " ets Jan 8 2013, rst cause:2, boot mode(3,6)", and ending with "~ld"), then display gibberish when the program itself attempted to use Serial.print() or Serial.println().

It appears to be a strange bug related to NodeMCU itself, but the following work-around got Serial.print working for me:

1. Before using Serial.print() or Serial.println() for the first time in the program (setup() is probably a good place), do **Serial.begin(74880);**

2. Step 1 notwithstanding, set the baud rate in Serial Monitor to **115200**.

My guess is that somewhere between the Arduino library and CP2102, a register value is being miscalculated (or mangled), and calling Serial.begin(74880) results in setting a register to the value that calling Serial.begin(115200) *should* have set it to.

Here's the page where I read about the bug: https://github.com/esp8266/Arduino/issues/4005


body:
I had errors in printing sensor values to serial, normal output starts with "D:" and ends with "all".

    D: 23 24 25 23 22 22 21 22 22 22 23 24 23 24 24 24 24 25 25 25 26 26 25 25 21 21 21 21 21 21 all
     36 36 37 45 44 43 41 41 41 40 39 39 38 38 37 38 38 38 37 40 all
    &&B⸮⸮R⸮B &⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮
    ⸮⸮5
    D: 29 45 29 28 27 26 25 27 29 26 22 23 24 22 21 21 20 20 22 22 149 26 25 24 27 26 23 21 21 22 all

I grounded, stabilized power source, change code not to use interrupts notthing had changed

How i solved:
I had spare mcu, changed it,  now serial works flawlessly.


body:
This might be related to old ESP-01 firmware. I mean 2018-ish firmware in 01s I bought 3 years ago or so.

I had the same problem –- `write_flash` works but after the reset garbage is coming in. Try this [installs micropython; change serial device to fit your setup]:

    esptool.py -p /dev/tty.usbserial-02022FD3 erase_flash
    esptool.py -p /dev/tty.usbserial-02022FD3 write_flash 0xfc000 esp_init_data_default.bin
    esptool.py -p /dev/tty.usbserial-02022FD3 write_flash -fs 1MB 0x00000 ../upython-esp8266-1m-20220117-v1.18.bin

Note: the location is flash size dependant – my ESP-01s have 1 MB of flash and you can check it using the `esptool.py flash_id` command. Use this reference:

 - `0x7c000` for 512 KB, modules like most ESP-01, -03, -07 etc.
 - `0xfc000` for 1 MB, modules like ESP8285, PSF-A85, some ESP-01, -03 etc.
 - `0x1fc000` for 2 MB
 - `0x3fc000` for 4 MB, modules like ESP-12E, NodeMCU devkit 1.0, WeMos D1 mini

The `esp_init_data_default.bin` file is taken from **Espressif SDK**, here's my SHA256 of it:

    shasum -a 256 esp_init_data_default.bin
    81e04e5ec0afef0aad3b52cca2a9bbccc205f4c57334c438e1d81e38ce94b932  esp_init_data_default.bin

But I guess the init file from Github should work OK as well [didn't try though].

https://github.com/espressif/ESP8266_RTOS_SDK


message:
Adding button which resets to top of void

I'm quite new to Arduino and the programming of the board, but I wanted to have a go at making a traffic light based on an example I found online.

The example supplied a simple layout which I roughly copied with the components I had.

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

I then created the following code to mimic the traffic lights of my local area.

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

    int red = 13;   int yellow = 12;   int green = 11;

    void setup(){
        pinMode(red,OUTPUT);
        pinMode(yellow,OUTPUT);
        pinMode(green,OUTPUT);
    }

    void loop(){
        changeLights();
    }

    void changeLights(){
        // red on, other off for 3 seconds
        digitalWrite(green,LOW);
        digitalWrite(yellow,LOW);
        digitalWrite(red,HIGH);
        delay(3000);

        // red on, amber on,green off for 3 seconds
        digitalWrite(green,LOW);
        digitalWrite(yellow,HIGH);
        digitalWrite(red,HIGH);
        delay(3000);

        // red off, amber off,green on for 3 seconds
        digitalWrite(green,HIGH);
        digitalWrite(yellow,LOW);
        digitalWrite(red,LOW);
        delay(3000);

        // red off, amber on,green on for 3 seconds
        digitalWrite(green,HIGH);
        digitalWrite(yellow,HIGH);
        digitalWrite(red,LOW);
        delay(3000);
    }

What I'm wanting to achieve next is a button which resets the code back to the top of `void changeLights`.
I assume I would be able to do this using a push-to-make switch, but I'm not sure how to incorporate it into my circuit or if it is even possible to reset using this.

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

body:
As currently written, your changeLights() function, which is repeatedly called over and over again by the Arduino loop() function, runs a timed sequence of lights.

  - Red light is on for 3000 ms
  - Amber is on for 3000 ms
  - Green is on for 3000 ms

This sequence could also be implemented using a state machine, but as it is right now, it's just a simple sequence of operations.

So now you have a new feature request *(heh, this happens all the time in pro software development)*:

  - hardware will include a momentary switch to ground
  - when the switch is pressed, the changeLights() sequence will skip to the next Red light
  - we might also want to do other kinds of sequence change, not just reset

The simplest way to code this would be to use digitalRead() to test whether the switch is pressed. You could test just after each of the delay(3000) calls. Technically this would work, but it would only sense the switch state just at the instant that digitalRead() is called. So for most of your 9-second sequence, it will ignore the switch, and only briefly test. The user will have to hold the button for 3 seconds to be sure the program senses the switch press.

There are some better ways to make this work. The delay(3000) actually makes the program do nothing else but watch the clock for the full delay interval, it doesn't do anything else during this time. So instead of delay(3000) you could use a for loop, and test whether the button has been pressed.

    // Spend 3 seconds waiting; exit the function if BUTTON1 is pressed.
    for(int count = 300; count > 0; count--) {
        delay(10); // test the button every 10 ms
        if (digitalRead(BUTTON1) == LOW) {
            return; // skip out of the changeLights() function
        }
    }

(Just saw Edgar Bonet's comment about the [blink without delay](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) Ardino example, which is another valid way to do the same thing. You could also use the millis() function and calculate the time when the next state transition should happen.)

Since this is an educational example, it's worth looking into how you would implement this as a **state machine**. (The traffic lights controller is often used as an introduction to state machines.) There's two types of state machines, Mealy and Moore, the difference is that one kind the outputs are determined only by the internal state, and the other kind, the outputs are a function of the internal state and the inputs.

A simple traffic light controller state machine might look like this:

  - state 0: initialize; next state=1
  - state 1: Red light on, timer=5 seconds, next state=2
  - state 2: Green light on, timer=3 seconds, next state=3
  - state 3: Amber light on, timer=1 seconds, next state=1

Use a timing countdown like in the example above, and when the countdown reaches 0, advance to the next state.

    const int S0_INIT = 0; // state 0: initialize
    const int S1_RED = 1; // state 1: Red light on
    const int S2_GREEN = 2; // state 2: Green light on
    const int S3_AMBER = 3; // state 3: Amber light on
    int state = S0_INIT;
    int stateTimer = 0;
    // void setup() not shown; configures input and output pins by pinMode(...)
    void loop()
    {
        if (stateTimer < 0) { stateTimer = 0; state = S0_INIT; return; }
        if (stateTimer > 0) {
            stateTimer = stateTimer - 1;
            delay(10); // 10 ms interval
            return;
        }
        switch(state) {
        case S0_INIT: // state 0: initialize; next state=1
            stateTimer = 0;
            state = S1_RED;
            break;
        case S1_RED: // state 1: Red light on, timer=5 seconds, next state=2
            // digitalWrite(... etc.) Red light on
            stateTimer = 500;
            state = S2_GREEN;
            break;
        case S2_GREEN: // state 2: Green light on, timer=3 seconds, next state=3
            // digitalWrite(... etc.) Green light on
            stateTimer = 300;
            state = S3_AMBER;
            break;
        case S3_AMBER: // state 3: Amber light on, timer=1 seconds, next state=1
            // digitalWrite(... etc.) Amber light on
            stateTimer = 100;
            state = S1_RED;
            break;
        }
    }

A more advanced traffic light controller (that responds to input) might look like this:

  - state 0: initialize; next state=1
  - state 1: Red light on, next state=2 (unless SWITCH1=HIGH, next state=4)
  - state 2: Green light on, next state=3 (unless SWITCH1=HIGH, next state=4)
  - state 3: Amber light on, next state=1 (unless SWITCH1=HIGH, next state=4)
  - state 4: Red light on, next state=5 (unless SWITCH1=LOW, next state=2)
  - state 5: no lights on, next state=4 (unless SWITCH1=LOW, next state=2)

An external input SWITCH1 switches this traffic controller between Red-Amber-Green sequence (states 1-2-3) and flashing-Red sequence (states 4-5). Adding constants for S4_BLINKING_RED=4 and S5_BLINKING_RED=5 and replacing the switch(state):

        switch(state) {
        case S0_INIT:
            stateTimer = 0;
            state = S1_RED;
            break;
        case S1_RED:
            // digitalWrite(... etc.) Red light on
            stateTimer = 500;
            state = S2_GREEN;
            if (digitalRead(SWITCH1) == HIGH) {
                state = S4_BLINKING_RED;
            }
            break;
        case S2_GREEN:
            // digitalWrite(... etc.) Green light on
            stateTimer = 300;
            state = S3_AMBER;
            if (digitalRead(SWITCH1) == HIGH) {
                state = S4_BLINKING_RED;
            }
            break;
        case S3_AMBER:
            // digitalWrite(... etc.) Amber light on
            stateTimer = 100;
            state = S1_RED;
            if (digitalRead(SWITCH1) == HIGH) {
                state = S4_BLINKING_RED;
            }
            break;
        case S4_BLINKING_RED:
            // digitalWrite(... etc.) Red light on
            stateTimer = 50;
            state = S5_BLINKING_RED;
            if (digitalRead(SWITCH1) == LOW) {
                state = S2_GREEN;
            }
            break;
        case S5_BLINKING_RED:
            // digitalWrite(... etc.) no lights on
            stateTimer = 50;
            state = S4_BLINKING_RED;
            if (digitalRead(SWITCH1) == LOW) {
                state = S2_GREEN;
            }
            break;
        }

(Remember to define the SWITCH1 pin, and configure pinMode(SWITCH1 ) in setup().)

Of course a *real* traffic light controller has more lights, say Northbound-Red, Northbound-Amber, Northbound-Green, Westbound-Red, Westbound-Amber, Westbound-Green, etc. Not to mention left turn arrows and maybe even "vehicle present" sensors. For a smart traffic light controller like that, the state is named by what traffic flow is authorized during that state:

  - state 1: northbound-southbound traffic green, 5 seconds, next state 2
  - state 2: northbound-southbound traffic amber, 2 seconds, next state 3
  - state 3: all lights red, 0.5 second, next state 4 (unless no vehicles waiting west-east lanes, then next state 6)
  - state 4: westbound-eastbound traffic green, 5 seconds, next state 5
  - state 5: westbound-eastbound traffic amber, 2 seconds, next state 6
  - state 6: all lights red, 0.5 second, next state 7 (unless no vehicles waiting N-W nor S-E left turn bays, then next state 9)
  - state 7: north-to-west left turn and south-to-east left turn green, 3 seconds, next state 8
  - state 8: north-to-west left turn and south-to-east left turn amber, 2 seconds, next state 9
  - state 9: all lights red, 0.5 second, next state 10 (unless no vehicles waiting W-S nor E-N left turn bays, then next state 12)
  - state 10: west-to-south left turn and east-to-north left turn green, 3 seconds, next state 11
  - state 11: west-to-south left turn and east-to-north left turn amber, 2 seconds, next state 1
  - state 12: all lights red, 0.5 second, next state 1 (unless no vehicles waiting north-south lanes, then next state 3)

The power of using state machines is that they all use the same basic "engine", just with more states, more outputs, more inputs. If the traffic engineer wants to adjust the timing to improve the flow of traffic, that only requires adjusting some of the data, which is much lower risk than rewriting code.  ... and of course state machines apply to more than just traffic lights, it's a very generally useful design technique.


body:
MarkU provided a pretty thorough answer with all the whys and hows of
state machines. This is definitely the way to go, and I encourage you to
read that answer very carefully.

I wrote a comment to your question where I suggest dropping `delay()` in
order for your loop to never block and your program to be responsive to
user input. Now I am writing this answer only to show you how to combine
both ideas, i.e. implement a state machine without delays. I do not
think this code needs any explanation besides those in [MarkU's
answer](https://arduino.stackexchange.com/a/21343) and in the [Blink
without delay](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay)
Arduino example.

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

    // Pinout.
    const int red = 13, yellow = 12, green = 11, reset = 10;

    void setup() {
        pinMode(red,    OUTPUT);
        pinMode(yellow, OUTPUT);
        pinMode(green,  OUTPUT);
        pinMode(reset,  INPUT_PULLUP);  // use internal pull-up
    }

    void loop() {
        static enum { INIT, RED, RED_AMBER, GREEN, GREEN_AMBER } state = INIT;
        static uint32_t duration;
        static uint32_t last_change;
        uint32_t now = millis();

        // Sense the reset button.
        if (digitalRead(reset) == LOW)
            state = INIT;

        // Wait at this state for the specified duration.
        if (state != INIT && now - last_change < duration)
            return;

        // Switch to next state.
        switch (state) {
            case INIT:
            case GREEN_AMBER:
                state = RED;
                duration = 3000;
                digitalWrite(green,  LOW);
                digitalWrite(yellow, LOW);
                digitalWrite(red,    HIGH);
                break;
            case RED:
                state = RED_AMBER;
                duration = 3000;
                digitalWrite(green,  LOW);
                digitalWrite(yellow, HIGH);
                digitalWrite(red,    HIGH);
                break;
            case RED_AMBER:
                state = GREEN;
                duration = 3000;
                digitalWrite(green,  HIGH);
                digitalWrite(yellow, LOW);
                digitalWrite(red,    LOW);
                break;
            case GREEN:
                state = GREEN_AMBER;
                duration = 3000;
                digitalWrite(green,  HIGH);
                digitalWrite(yellow, HIGH);
                digitalWrite(red,    LOW);
                break;
        }
        last_change = now;
    }

I would normally have declared `duration` as a `static const`. I kept it
non-const only to follow MarkU's steps and make it easy to have
different durations for different states (really, the green light should
last longer...).


body:
The best way to handle this problem is using a state machine, as shown in all the other answers. In fact, this IS the classical problem to learn how to use and implement state machines.

I just wanted to add the "fast" solution to your problem, which will enable you to do what you want without changing your code too much:

    void changeLights(){
     unsigned long startTime;

     // red on, other off for 3 seconds
     digitalWrite(green,LOW);
     digitalWrite(yellow,LOW);
     digitalWrite(red,HIGH);
     startTime = millis();
     while ((millis() - startTime) < 3000)
     { // Wait for 3 seconds while checking for the button
      if (digitalRead(buttonPin) == HIGH)
       return; // Just exit this function; the loop will start again
     }

     [ repeat for the other colors ]
    }


message:
How do I adjust the scale/calibration of a photoresistor?

This photoresistor has a min/max of 0-1023.

I'm trying to scale the brightness of a cathode RGB LED based on the sensor's value, but based on my current lighting, the min/max readings I generally am getting are 100-700.

So how can I scale the sensor reading so that 100 = no light on the LED and 700 = max brightness?

body:
You can easily scale in Arduino code with the [map()][1] function.

e.g.:

    const int MIN_LIGHT 100;
    const int MAX_LIGHT 700;

    int light_reading = analogRead(A0);

    // Convert MIN reading (100) -> MAX reading (700) to a range 0->100.
    int percentage_bright = map(light_reading, MIN_LIGHT, MAX_LIGHT, 0, 100);

But you may need some calibration of your system to handle different ambient light situations. What reading do you get in direct sunlight for example?

So then I assume you're using PWM (Pulse Width Modulation) to drive the LED.  This requires a value between 0 & 255.  Once again we can use the map() function.

    // Convert light-value % (0-100) to PWM speed (0-255)
    int led_brightness = map(percentage_bright, 0, 100, 0, 255);
    analogWrite(LED_PIN_RED, led_brightness);

Obviously these bits of code can be reduced down to a single line - mapping directly from the reading to the desired result.
  [1]: https://www.arduino.cc/en/Reference/Map


message:
Arduino vs Raspberry, Advantages And Disadvantes

I have done extensive research into the differences and here are the questions i have:

1. What is a micro controller and what differs it from the raspberry pi system

2. Why buy the Arduino when it is less powerful than the raspberry pi

3. What projects would either system be better for

4. Does Arduino run a full OS

5. Where is the best place to buy arduino and raspberry pi

6. What is the difference in the ad dons

7. Which has the most tutorials

8. What is the different's in power supply and usages

9. I know i'm asking this on a forum with arduino fans (There is no arduino vs raspberry pi forum) but opinions aside which is the best for beginners (I can program C++ and python as well as building hardware components)

10. What is the general price different overall including buying extra ad dons/shields

Thank you for your answers :)

body:
1) Here is a great article about microcontrollers and how they differ from a full computer: http://electronics.howstuffworks.com/microcontroller1.htm
tl;dr: A Raspberry Pi runs a full desktop OS (often Linux) and as such, can do most of the things a "typical" computer can do, such as browse the internet or install different programs. An Arduino, however, cannot do that. An Arduino can run one piece of software that you program to it (called a sketch in the Arduino world) and repeat that same program over and over.

2) They have different purposes. A Raspberry Pi is designed as a low-cost desktop computer that you can put anywhere, and also as a platform that is easy to put into different projects. An Arduino is better suited for attaching sensors to, controlling motors, etc.

3) see #2
Also, a Raspberry Pi is typically used when a GUI is wanted, or when more computing power is required. An Arduino is typically used for more real time things such as reading sensors or controlling LED's.

4) No, it does not. Arduino's run C++ compiled as machine code object files.

5) For the Raspberry Pi, Here is the list of official resellers: https://www.raspberrypi.org/products/model-b-plus/
For the arduino, it depends on what kind you're buying and where you live, there are many different styles.

6) As a general rule, Arduino's have more shields. But, a raspberry pi typically needs a screen, mouse, keyboard, etc. Everything a standard computer needs.

7) Entirely depends on what you're trying to do.

8) Both take a 5V input voltage. An Arduino can take up to a 20v input (again, depending on the model) whereas the Raspberry Pi can just be powered with 5v over USB.

9) Again, depends on what you're trying to do. A Raspberry Pi is "easier" to use, as it's a full computer.


message:
How do I install the latest Arduino IDE on Ubuntu 14.04LTS?

What I've tried:

- I downloaded the package for 1.6.7 on Ubuntu 14.04 LTS but when I open it no matter what I try it will not start.
- I installed 1.0.5 from the Ubuntu Software Center. I tried to update it but found no solution.

UPDATE: I found my answer in talamaki's answer on that other question linked above.

body:
Follow the following step to download, install and run Arduino IDE on Ubuntu

 1. First Download the Tar (tar-bal) from this link http://arduino.cc/en/Main/Software (download the correct 32 / 64 bit linux version ) depends upon your Ubuntu version.
 2. Then goto download folder using terminal (shell) or the folder where you downloaded the tar and unpacked that tar using the following commands
like
  cd /Downloads
  tar -zxvf arduino-1.6.7-linux32.tgz
where 1.6.7 is the version of ide

 3. you also need java runtime environment for arduino IDE download and install it using the following command
       sudo apt-get install openjdk-7-jre

 4. you also need to provide the UART permissions for your hardware using following commands
   sudo chmod a+rw /dev/ttyACM0
where ACM0 is the port number if you are using multiple or many arduinos just give permissions using the above commands by replacing the ACM0 to ACM1 to ACMN

5. then create a shortcut of arduino ide from the folder where you extract the tar
 cd ~/Desktop
 ln -s /Downloads/arduino-1.6.7/arduino

and then double click the shortcut to run arduino if it gives permission error then right click the shortcut and in file preferences gives permissions to the shortcut


message:
Arduino is not responding to a Tiny RTC I2C modules, How to fix?

We have an arduino due with a Tiny RTC I2C module and we're trying to print the current time to the serial monitor. However its not working, currently its printing the time as 2165/165/165 (Monday) 165:165:85 (it should read something like 2016/3/3 (Thursday) 4:15:00). Interestingly it continues to read the same thing, it doesn't change, even if I remove the module from the breadboard completely. I have tried this with two of the modules and both have the same exact results. Does anyone know how to fix this?

My schematics are the same as shown here:
http://www.hobbyist.co.nz/?q=real_time_clock

This is my code, it's just the example code from the imported library for the clock.

    // Date and time functions using a DS1307 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    #if defined(ARDUINO_ARCH_SAMD)
    // for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
       #define Serial SerialUSB
    #endif

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {

    #ifndef ESP8266
      while (!Serial); // for Leonardo/Micro/Zero
    #endif

      Serial.begin(57600);
      if (! rtc.begin()) {
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (! rtc.isrunning()) {
        Serial.println("RTC is NOT running!");
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
    }

    void loop () {
        DateTime now = rtc.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(" (");
        Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
        Serial.print(") ");
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();

        Serial.print(" since midnight 1/1/1970 = ");
        Serial.print(now.unixtime());
        Serial.print("s = ");
        Serial.print(now.unixtime() / 86400L);
        Serial.println("d");

        // calculate a date which is 7 days and 30 seconds into the future
        DateTime future (now + TimeSpan(7,12,30,6));

        Serial.print(" now + 7d + 30s: ");
        Serial.print(future.year(), DEC);
        Serial.print('/');
        Serial.print(future.month(), DEC);
        Serial.print('/');
        Serial.print(future.day(), DEC);
        Serial.print(' ');
        Serial.print(future.hour(), DEC);
        Serial.print(':');
        Serial.print(future.minute(), DEC);
        Serial.print(':');
        Serial.print(future.second(), DEC);
        Serial.println();

        Serial.println();
        delay(3000);
    }

body:
You have a couple of problems (although the lack of pull-up resistors is not one of them, because the board you linked has pull-up resistors on it).

* The DS1307 needs to operate at a minimum of 4.5 volts, so you can't connect it to the 3.3V pin on the Due. (You need to supply it with 5V).

* However the Due is a 3.3V device on its data pins, and thus you can't connect the DS1307 directly to SDA/SDL or you will damage the Due.

Thus you need to supply the clock board with 5V, and use a bi-directional logic-level converter, such as this (using two logic-level MOSFETs):

[![Logic level converter][1]][1]

You can buy level-converter boards, but as you can see, one is easy enough to make up.

Now the clock chip runs at 5V, but the logic levels are converted to 3.3V for the Due.

I tested this with mine, and it worked OK.

---

    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS1307 myclock;

    void setup () {
        Serial.begin(115200);
        Wire.begin();
        myclock.begin();
    }

    void loop () {
        DateTime now = myclock.now();

        Serial.print(now.year(), DEC);
        Serial.print('/');
        Serial.print(now.month(), DEC);
        Serial.print('/');
        Serial.print(now.day(), DEC);
        Serial.print(' ');
        Serial.print(now.hour(), DEC);
        Serial.print(':');
        Serial.print(now.minute(), DEC);
        Serial.print(':');
        Serial.print(now.second(), DEC);
        Serial.println();

        Serial.print(" since midnight 1/1/1970 = ");
        Serial.print(now.unixtime());
        Serial.print("s = ");
        Serial.print(now.unixtime() / 86400L);
        Serial.println("d");

        Serial.println();
        delay(3000);
    }

---

Output:

    2016/3/6 12:0:20
     since midnight 1/1/1970 = 1457265620s = 16866d

    2016/3/6 12:0:23
     since midnight 1/1/1970 = 1457265623s = 16866d

    2016/3/6 12:0:26
     since midnight 1/1/1970 = 1457265626s = 16866d

---

A useful technique for debugging is to run the "I2C scanner" I have on my [I2C page](http://www.gammon.com.au/i2c). The code is:

    // I2C Scanner
    // Written by Nick Gammon
    // Date: 20th April 2011

    #include <Wire.h>

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

      // Leonardo: wait for serial port to connect
      while (!Serial)
        {
        }

      Serial.println ();
      Serial.println ("I2C scanner. Scanning ...");
      byte count = 0;

      Wire.begin();
      for (byte i = 8; i < 120; i++)
      {
        Wire.beginTransmission (i);
        if (Wire.endTransmission () == 0)
          {
          Serial.print ("Found address: ");
          Serial.print (i, DEC);
          Serial.print (" (0x");
          Serial.print (i, HEX);
          Serial.println (")");
          count++;
          delay (1);  // maybe unneeded?
          } // end of good response
      } // end of for loop
      Serial.println ("Done.");
      Serial.print ("Found ");
      Serial.print (count, DEC);
      Serial.println (" device(s).");
    }  // end of setup

    void loop() {}

If you don't see your device appear in the Serial Monitor, there is no point wondering why the date doesn't change, because it hasn't found the clock at all. You should see something like this:

    I2C scanner. Scanning ...
    Found address: 104 (0x68)
    Done.
    Found 1 device(s).

---

## How the level converter works

For more information, read the [Philips Application Note AN97055](http://cdn.sparkfun.com/tutorialimages/BD-LogicLevelConverter/an97055.pdf)

In brief (taking SDA as an example):

* If neither side is driving SDA low, then VGS is zero (they are both 3.3V) and the MOSFET does not conduct. Hence each side is "pulled-up" to their respective voltages. The low side is pulled up to 3.3V and the high side is pulled up to 5V.

* If the low side drives SDA low, then VGS is 3.3V which is high enough for the MOSFET to conduct. Since it conducts it also drags the high side low as well (overpowering the 10k pull-up resistor).

* If the high side drives SDA low, current initially flows through the drain substrate diode of the MOSFET (it will be a diode drop above 0V, namely 0.7V), lowering the voltage at the source, until VGS is high enough for the MOSFET to conduct. Once it starts conducting then the low side is pulled further lower.

---

> Do you have an actual photograph of this?

I've pulled it all apart days ago, however thankfully I took a snapshot before I did.

[![Photo of schematic][2]][2]

To be honest, the schematic is easier to follow. When looking at photos it can be hard to see exactly what is plugged into where.

  [1]: https://i.stack.imgur.com/Rkj8N.png
  [2]: https://i.stack.imgur.com/QGg5i.jpg


message:
help compiling code for flora project

I'm working on the Adafruit Firewalker shoes.

I can't make my code compile to test my flora project.

This is my error message:

    Arduino: 1.6.7 (Windows 10), Board: "Adafruit Flora"

    C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel: No such file or directory

     #include <Adafruit_NeoPixel>

                                 ^

    compilation terminated.

    exit status 1
    Error compiling.

      This report would have more information with
      "Show verbose output during compilation"
      enabled in File > Preferences.

---

<https://learn.adafruit.com/firewalker-led-sneakers/test-circuit>

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

        #include <Adafruit_NeoPixel.h>

    const int analogInPin = A9;  // Analog input pin that the potentiometer is attached to
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, 6, NEO_GRB + NEO_KHZ800);
    int sensorValue = 0;        // value read from the pot

    void setup() {
      // initialize serial communications at 9600 bps:
      Serial.begin(9600);
     pinMode(9, INPUT_PULLUP);
       strip.begin();
      strip.show(); // Initialize all pixels to 'off'

    }

    void loop() {
      // read the analog in value:
      sensorValue = analogRead(analogInPin);
      // print the results to the serial monitor:
      Serial.print("sensor = " );
      Serial.println(sensorValue);

    if (sensorValue < 100){
      Serial.println("leds triggered");
    colorWipe(strip.Color(255, 0, 0), 25);
    colorWipe(strip.Color(0, 0, 0), 25);
    }

    }

    void colorWipe(uint32_t c, uint8_t wait) {
      for(uint16_t i=0; i<strip.numPixels(); i++) {
          strip.setPixelColor(i, c);
          strip.show();
          delay(wait);
      }
    }

body:
I had the same problem, you just have to download the Adafruit Neo Pixel library:

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

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


message:
Integration of signal

In my house, I have a low voltage AC signal (0-10V) that is proportional to the amount of current that is drawn at any moment (or as it is presented: kW) (europe, 50Hz). Presently, it is just shown as a dial in my kitchen, of course I would to log this. I want to rectify and integrate this singnal over an appropriate time span (maybe on minute) As far as I can see, I basically have two ways of doing this:

 1. The pure arduino approach: Using a voltage divider to get it down to 0-5 V (after rectification) (and maybe throw in a zener diode as an extra protection) Then using an adc in the arduino and measure the voltage directly. The problem I foresee with this approach is that I will need a pretty high sampling rate to make sure I get the peak values. If I managed to sample at exactly the same frequency as my mains,I could just calibrate the measured value (unless I managed to hit the cross overs) but I do not think that would be feasible So I think I need to maybe sample on approx 500 Hz and pick out the highest value from each 1/50 second.

 2. Using an opamp, a few resistors and a capasitor to set up an analog integration circuit, then use the arduino to read out and reset that at appropriate times. Setting up the integration circuit is no problem for me, but I need some feedback on the reset circuit. I have been looking around a bit, but I have not found any standard way to reset an integrator circuit, it seems like the idea is that it should be integrating for as long as it is running.. As far as I can see, as long as it running on <= 5V, I could use an input on the arduino to drain it? - I would then need to make the dimensions such that the low current the arduino input draws will allow the integrator to be reset fast enough.

Any comments? Have I overlooked something? is there a third approach that I have not been thinking about? Is the 1st approach easier that what I think?

body:
I'm not quite clear on the 'peak' detection - this would mean your reading would be changing several times a second potentially. Does the current in your house vary that much per second? I don't think your electricity meter is that clever anyway (there must be a smoothing effect, I reckon). For example, if you turned on your electric kettle for 1/50th of a second, would your domestic meter accurately record that (or the 0-10V signal vary)? I personally doubt it but I'm no meter designer! Anyway, you also mention that you want to log over a minute? I'm unclear on the exact requirements here.

Anyway, if you are reading the 'max' current (so you can accurately calculate bills, for example) I think your first approach would work - after all a 50Hz sampling rate is very low for an Arduino. You won't need a 500Hz sample rate as the data doesn't change *that* frequently anyway, does it?

Perhaps you could trigger the sampling activity by synchronising to the mains frequency (which you sort of allude to) and then do the reading? Use an analog input to detect the rising LV mains cycle and then do the reading? Or use a Schmidt trigger to trigger the Arduino (sounds a bit of overkill, I think the Arduino could do it all).

Experimentation is called for to see what works and what doesn't but your first approach seems eminently feasible to me.


body:
With an Arduino Uno, you can get 9615 samples per second from an analog
input, and do the data processing at the same time. That's more than
enough to reliably detect a peak. For this, you have to set the ADC to
"free running mode" and do the processing in the ADC interrupt service
routine. Se [this answer](https://arduino.stackexchange.com/a/21175) for
a detailed explanation and code.

Oh, and instead of peak detection, you could just integrate your signal.
That should be simpler, and simple is good for interrupt-driven data
processing.


body:
Sorry, but.. Why integration? Just use a peak detector like this one:

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

The output will "float" to the peak value of the input signal, minus the voltage drop across the diode:

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

The output oscillates between 9.7V and 9.2V, which is a 5% maximum error. If you want to reduce it, sample with a sample rate not multiple of 50Hz and average the measures.

The RC constant is 500ms. This means that it will require less than a second to pass from a value to a lower one:

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

Here in almost 500ms it will go from 10V to 5V.

If you want to reduce the diode effect (9.7V instead of 10V) use a schottky diode. This, however, will not reduce the 9.2V effect.

You should divide by 2 the voltage; you can either

 1. divide it before the diode (but then the diode effect will be more evident - you can however correct it in software
 2. divide it after the circuit (In this case, replace the 500k resistor with two 250k resistors and take the voltage in the middle)

Of course 500k and 250k are not standard values, but you can use any nearby value without affecting the behavior

  [1]: https://i.stack.imgur.com/6voW0.png
  [2]: https://i.stack.imgur.com/lafnM.png
  [3]: https://i.stack.imgur.com/q5reW.png


message:
Why isn't there bus contention on the MISO line during SPI-based programming?

Consider this image from [sparkfun][1]:

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

Let's say I have this setup, a master and *n* slaves, plus a programmer connected to the SPI lines.

When I program the master (Arduino), the Arduino is reset. This means that all the data pins go low.

Since SS is active low, all the SS pins on the slaves go active.

I believe this means that all the slaves start driving the same MISO line (blue arrow from slaves to master), either high or low.

Doesn't this result in bus contention on that line? If not, what's the mechanism that prevents bus contention from happening?

  [1]: https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi
  [2]: https://i.stack.imgur.com/EGm4Q.png

body:
Yes, you *can* get SPI bus contention when using multiple SPI slave devices. It is up to you, the designer, to ensure that each SPI slave device has its chip select (CS or SS) asserted only when no other devices are driving MISO. Normally that is achieved by:

 - initialize all of the CS pins high (inactive) during setup
 - in the code that accesses SPI device #1,
   - assert SPI device #1 CS1 low (active)
   - perform SPI transfers on SPI device #1
   - release SPI device #1 CS1 high (inactive)
 - in the code that accesses SPI device #2,
   - assert SPI device #2 CS2 low (active)
   - perform SPI transfers on SPI device #1
   - release SPI device #2 CS2 high (inactive)

SPI bus contention can also occur during device programming (loading the bootloader or firmware image), if there is an attached SPI slave device, and its chip select (SS) is not pulled inactive by a pullup resistor.

I had a problem with this on one of my designs a few weeks ago. I was trying to burn the bootloader into some blank ATmega328-AU chips post-assembly, and my device programmer wasn't able to successfully program the chips because my one slave device had its chip select connected only to an ATmega328 pin.

I had previously breadboarded this design using an Arduino Pro Mini board, and it was working fine; but when I moved to first prototype PCB there was bus contention on MISO -- the blank ATmega328 wasn't driving the slave device's chip select high or low, but it floated low (active), causing MISO contention.

My solution (workaround) was temporarily contacting the chip-select to VDD 3.3V through a 10kohm resistor. This made my SPI slave device inactive, allowing the device programmer to successfully load the bootloader.

I think there would be no harm in leaving the pullup resistor on chip select (since it's an active-low signal), but it was only really necessary when using the device programmer. After I had the prototype boards initialized with the bootloader image, I was subsequently able to load firmware images as usual.

*(One minor unrelated issue was that my assembler purchased ATmega328-AU when I had specified ATmega328P-AU -- they are almost the same, and it doesn't make a difference for my application, but it was annoying that I had to use a slightly different command line argument than then one I used with the Arduino Pro Mini board.)*


message:
How to pad an ascii number with leading zeros?

I need to include a 3 digit ascii representation of message length number in the message header, but I am having difficulty trying to pad the number with leading '0' zeros in order to keep the number of 'length' digits needing to be appended always 3 even when the message length is only one or two digits long.

Addendum:
The problem, more specifically, is how to left-pad a char array containing the number representation.
I got as far as defining what and where, but I couldn't figure out **how** to shift the char[] contents right in order to insert the "0" at msglength[0].  (I tried using strcat, but that didn't work).

    char msglength[4]          //(3 digits + nul)
    for (int pad=1; pad<=3-strlen(msglength); pad++)
    {
        // add a leading zero char to msglength, but that involves
        // somehow shifting all its contents to the right
    }

body:
This is the kind of situation where `printf()` comes handy:

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

    printf("d", number);

prints the number in the format you described. Alas, `printf()` is not
part of the standard Arduino API. But you can have it, nonetheless, at
least on AVR-based Arduinos, as it is provided by the avr-libc, which is
always linked with all Arduino programs. Some setup is needed to tell
avr-libc about where is its “standard output”. We can use the macro
`fdev_setup_stream()` to tell it to just push the bytes through
`Serial.write()`:

    static int Serial_write(char c, FILE *) {
        if (c == '\n') Serial.write('\r');  // convert LF -> CRLF
        return Serial.write(c);
    }

    static FILE mystdout;

    void setup() {
        Serial.begin(9600);
        stdout = &mystdout;
        fdev_setup_stream(stdout, Serial_write, NULL, _FDEV_SETUP_WRITE);
    }

    void loop() {
        static int count;
        printf("d and counting...\n", count++);
        delay(500);
    }

C.f. the [manual of avr-libc's
stdio.h](http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html#details)
for details.

**Pros of this method**:

* `printf()` has plenty of options to control the formatting of your
  messages.
* It's very standard C, understood by anyone having programmed in that
  language.

**Cons**:

* This can make your compiled program bigger than it would be if
  sticking with the Arduino API.
* It's not the “Arduino way”.


body:
There is always brute force.

    char* itob(int val, char* buf, size_t n)
    {
      char* bp = buf + n;
      do {
        *--bp = (val % 10) + '0';
        val = val / 10;
      } while (bp != buf);
      return (buf);
    }

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

      const int BUF_MAX = 3;
      char buf[BUF_MAX];

      Serial.write(itob(42, buf, BUF_MAX));
      Serial.println();
    }

    void loop()
    {
    }

Please observe that the buffer is not null-terminated, therefore the Serial.write().

Several possible optimizations from the simple solution such as detect when the value is zero and short-cut.

Cheers!


body:
One straightforward way to do this is to extract digits separately (using integer division and mod).  For example, the hundreds digit of a positive or unsigned `int x` is `(x/100)`.

A sketch shown below uses the statement

      Serial << ' ' << b/100 << (b/10) << b;

to print a space and three digits of a positive number, with leading zeroes.  Here are the first 18 lines of output from the sketch:

     000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
     016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031
     032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047
     048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063
     064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079
     080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095
     096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111
     112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
     128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
     144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
     160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
     176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
     192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
     208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
     224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
     240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
     000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015
     016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031

Here is the sketch:

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

    #include <Streaming.h>

    //char b=0;    // char is signed; messy when hi bit is on
    byte b=0;    // byte is unsigned, all ok
    void setup() {
      Serial.begin(115200);
    }

    void loop() {
      // To emulate
      //    Serial << ' ' << setw(3) << setfill('0') << b;
      // or
      //    Serial << ' ' << b<100? '0': '' << b<10? '0': '' << b;
      // write (eg)
      Serial << ' ' << b/100 << (b/10) << b;
      // or if b is an int instead of a byte, write
      //    Serial << ' ' << (b/100) << (b/10) << b;

      ++b;
      if (b == 0) Serial.println();
      delay(17);
    }

The code shown above uses `Streaming.h`, a [contributed library](https://www.arduino.cc/en/Reference/Libraries) that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like `<<` Serial stream operators to `Serial.print` statements, without increasing code size.  If you don't have `Streaming.h` installed, either install it via [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/) or manually translate the `Serial << ...` statement to `Serial.print` statements.

Note, if the `Streaming.h` library supported `setw()` and `setfill()`, they could be used to set field width and fill character.  (See comments in sketch.)  However, the current implementation merely translates the stream insertion operator `<<` form into `print()` form.  It supports four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and `endl`.  Some _FILL functions are suggested at the Arduiniana.org link.


body:
Thank you all for your suggestions.
This is what I came up with, which seems to work ok.

    char lengthstr[4]="7";
    Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");
    int maxsize=sizeof(lengthstr);  // size of lengthstr array
    int steps=strlen(lengthstr)+1;  // number of chars to be moved
    int hop=maxsize-steps;          // number of steps to be jumped over each move
    if((steps>1)&&(maxsize>steps)) {
       for (int pos=steps; pos >= 0; pos--) {
       lengthstr[pos+hop] = lengthstr[pos];
       lengthstr[pos]='0';
       }
    }
    Serial.print("lengthstr='"); Serial.print(lengthstr); Serial.println("'");


message:
Can not connect with Bluetooth hc-05

I connect my Bluetooth hc-05. But the blind led in the Bluetooth module is not stable when I connect with my Android phone. Help help me to solve this.

body: Through which android app you are connecting because normally android only pair and will connect to device if you are sharing some data or files or you can connect to android device using any bluetooth app like bluetooth terminal or dual bluetooth chat


body:
It is very simple really.

Initially the Bluetooth got paired automatically with my Android, but apparently the variable transmission was not complete.

**If this is the case with your module,it will be blinking with high frequency.**

So here is what I did:

 1. Hit the RESET button on HC-05 once
 2. Go to Android Bluetooth Settings and UNPAIR HC-05
 3. Now Pair it again by clicking on it
 4. You will be prompted to enter password- '1234'
 5. Open your Bluetooth Terminal and you will find your data appearing
    on Android

**P.S.-A 2 Hz blinking frequency on HC-05 should signify proper connection**


message:
Board won't show on one of my computers

I have the same problem with these two boards: Ruggeduino (Uno compatible) and DFRobot Romeo 1 (Duemilanove compatible). On one of my Macs (a Macbook Pro running 10.11.4), I can see a new port  /dev/cu.usbmodem641 or /dev/a4005g3t depending on the board. On the other computer (a Mac Mini late 2014), they just won't show. Same cable, same boards, and no hub. I don't know where to look to see an indication of a failure of some sort.

These two ones use a type-b USB socket (printer style)

Also on the Mac Mini that won't see any of those boards, I can connect an EtherMega2560 (Arduino Mega 2560) which happens to use a micro USB socket. I don't know if that is related to the problem.

Both computers run the same OS (OS X 10.11.4) and the latest version of Arduino.

Here is a difference (found in /var/log/system.log):

On the working computer:

    Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: fInBufPool,kMaxInBufPool 8,64
    Mar  3 22:20:42 pc101 kernel[0]: AppleUSBFTDI: Version number - 5.0.0, Input buffers 8, Output buffers 16

On the non working one:

    cfprefsd[114]: BUG in libdispatch: 15E49a - 1718 - 0x0

..

body:
My Ruggeduino stopped showing up as a serial device under El Capitan (10.11.6). I was able to fix this by installing/updating the VCP drivers for Silicon Labs USB devices available here:

https://www.silabs.com/products/mcu/Pages/USBtoUARTBridgeVCPDrivers.aspx

After installing the Mac driver the Ruggeduino shows up as SLAB_USBtoUART and works fine with the Arduino GUI.


message:
What are the components of a Xively HTTP PUT request to send to my SIM800 GPRS module?

I have an Elecrow GPRS shield which I want to use to post temperatures from 3 x DS18B20s to Xively. The example code is a mystery to me. You can find in full at this link: http://www.elecrow.com/wiki/index.php?title=GPRS/GSM_Shield_v1.0#A_Simple_Source_Code_Example

The relevant function is here:

    ///send2Pachube()///
    ///this function is to send the sensor data to the pachube, you can see the new value in the pachube after execute this function///
    void Send2Pachube()
    {
    mySerial.println("AT+CGATT?");
    delay(100);

    ShowSerialData();

    mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
    delay(1000);

    ShowSerialData();

    mySerial.println("AT+CIICR");//bring up wireless connection
    delay(300);

    ShowSerialData();

    mySerial.println("AT+CIFSR");//get local IP adress
    delay(2000);

    ShowSerialData();

    mySerial.println("AT+CIPSPRT=0");
    delay(3000);

    ShowSerialData();

    mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
    delay(2000);

    ShowSerialData();

    mySerial.println("AT+CIPSEND");//begin send data to remote server
    delay(4000);
    ShowSerialData();
    String humidity = "1031";//these 4 line code are imitate the real sensor data, because the demo did't add other sensor, so using 4 string variable to replace.
    String moisture = "1242";//you can replace these four variable to the real sensor data in your project
    String temperature = "30";//
    String barometer = "60.56";//
    mySerial.print("\"method\": \"put\",\"resource\": \"/feeds/43634/\",\"params\"");//here is the feed you apply from pachube
    delay(500);
    ShowSerialData();
    mySerial.print(": ,\"headers\": \"X-PachubeApiKey\":");//in here, you should replace your pachubeapikey
    delay(500);
    ShowSerialData();
    mySerial.print(" \"_cXwr5LE8qW4a296O-cDwOUvfddFer5pGmaRigPsiO0");//pachubeapikey
    delay(500);
    ShowSerialData();
    mySerial.print("jEB9OjK-W6vej56j9ItaSlIac-hgbQjxExuveD95yc8BttXc");//pachubeapikey
    delay(500);
    ShowSerialData();
    mySerial.print("Z7_seZqLVjeCOmNbEXUva45t6FL8AxOcuNSsQS\",\"body\":");
    delay(500);
    ShowSerialData();
    mySerial.print(" \"version\": \"1.0.0\",\"datastreams\": ");
    delay(500);
    ShowSerialData();
    mySerial.println("[\"id\": \"01\",\"current_value\": \"" + barometer + "\",");
    delay(500);
    ShowSerialData();
    mySerial.println("\"id\": \"02\",\"current_value\": \"" + humidity + "\",");
    delay(500);
    ShowSerialData();
    mySerial.println("\"id\": \"03\",\"current_value\": \"" + moisture + "\",");
    delay(500);
    ShowSerialData();
    mySerial.println("\"id\": \"04\",\"current_value\": \"" + temperature + "\"],\"token\": \"lee\"");

    delay(500);
    ShowSerialData();

    mySerial.println((char)26);//sending
    delay(5000);//waitting for reply, important! the time is base on the condition of internet
    mySerial.println();

    ShowSerialData();

    mySerial.println("AT+CIPCLOSE");//close the connection
    delay(100);
    ShowSerialData();

    }
    void ShowSerialData()
    {
    while(mySerial.available()!=0)
    Serial.write(mySerial.read());
    }
Note that although this is called "send2Pachube" it uses the Cosm API, which still works.
The section following the line

    mySerial.println("AT+CIPSEND");

is where the HTTP gets formulated. I've assembled the string in the example code and it looks odd. The API key goes on about four times longer than it should. I'm not sure what all those colons are doing in there, are they a String operator? Can anyone give me an example of an HTTP PUT request for Cosm or Xively that illustrates how this string should be assembled?
Thanks

body:
I've got a working solution to this issue. Here's the values you can edit and the function:

    String FEED = "YOUR_FEED";
    String KEY = "YOUR_API_KEY";
    String DATASTREAM1 = "YOUR_DATASTREAM1_NAME";
    Int VALUE1 = YOUR_VALUE1;
    String DATASTREAM2 = "YOUR_DATASTREAM2_NAME";
    Int VALUE2 = YOUR_VALUE2;

    void send2Cosm()
    {
    mySerial.println("AT+CGATT?");
    delay(100);
    ShowSerialData();
    mySerial.println("AT+CSTT=\"CMNET\"");//start task and setting the APN,
    delay(1000);
    ShowSerialData();
    mySerial.println("AT+CIICR");//bring up wireless connection
    delay(300);
    ShowSerialData();
    mySerial.println("AT+CIFSR");//get local IP adress
    delay(2000);
    ShowSerialData();
    mySerial.println("AT+CIPSPRT=0");
    delay(3000);
    ShowSerialData();
    mySerial.println("AT+CIPSTART=\"tcp\",\"api.cosm.com\",\"8081\"");//start up the connection
    delay(2000);
    ShowSerialData();
    mySerial.println("AT+CIPSEND");//begin send data to remote server
    delay(4000);
    ShowSerialData();

    mySerial.print("{\"method\": \"put\",\"resource\": \"/feeds/" + FEED + "/\",\"params\"");
    delay(500);
    ShowSerialData();
    mySerial.print(": {},\"headers\": {\"X-ApiKey\":");
    delay(500);
    ShowSerialData();
    mySerial.print("\"" + KEY + "\"},\"body\":");
    delay(500);
    ShowSerialData();
    mySerial.print(" {\"version\": \"1.0.0\",\"datastreams\":");
    delay(500);
    ShowSerialData();
    mySerial.print("[{\"id\": \"" + DATASTREAM1 + "\",\"current_value\": \"");
    mySerial.print(VALUE1);
    delay(500);
    ShowSerialData();
    mySerial.print("\"},{\"id\": \"" + DATASTREAM2 + "\",\"current_value\": \"");
    mySerial.print(VALUE2);
    delay(500);
    ShowSerialData();
    mySerial.println("\"}]}}");
    delay(500);
    ShowSerialData();

    mySerial.println((char)26); //sending = ctrl+z
    delay(5000);//waitting for reply, important! the time is base on the condition of internet
    mySerial.println();

    ShowSerialData();

    mySerial.println("AT+CIPCLOSE");//close the connection
    delay(100);
    ShowSerialData();

    }

    void ShowSerialData()
    {
    while(mySerial.available()!=0)
    Serial.write(mySerial.read());
    }

To answer part of my question: no, the colons aren't a String operator, they're part of the HTML. Here's an example of the formed URL that gets sent:

    {"method": "put","resource": "/feeds/YOUR_FEED/","params": {},"headers": {"X-ApiKey":"YOUR_API"},"body": {"version": "1.0.0","datastreams":[{"id": "DATASTREAM1","current_value": "VALUE1"},{"id": "DATASTREAM2","current_value": "VALUE2"}]}}

This code updates my feed but after several hours the updates stop. I'm still troubleshooting this new problem so I'm not 100% sure that this code is good. I will post back if the problem's in here.


message:
Custom built Arduino is not working - double blinks

I've made a home-made Arduino based on [this video][2]. The problem is that I can't upload anything, it doesn't react, only the LED double blinks in every second. What does that mean? How to fix it? Thanks.

Update:
[![photo][1]][1]

  [1]: https://i.stack.imgur.com/REGTX.jpg
  [2]: https://www.youtube.com/watch?v=sNIMCdVOHOM

body:
It's a reasonably clear photo (another couple would help) however I do see at least one major problem. Pin 8 (and pin 22) are Ground, but I don't see any wires running to that. Also the 22 pF (or similar) capacitors connected to the crystal should have their other sides grounded.

I suggest you look at my page [Breadboard Arduino](http://www.gammon.com.au/breadboard) which has clear photos and wiring guides. In particular:

[![Minimal Arduino][1]][1]

Notice the ground wire, and how the capacitors are connected.

I suggest you double-check all wiring, and make sure it is very similar to this:

[![Atmega328P wiring][2]][2]

  [1]: https://i.stack.imgur.com/mZ4n8.jpg
  [2]: https://i.stack.imgur.com/pIXMx.png


message:
MicroSD interfering with ISP programming

I have a microSD connected to an Arduino and I can't program it over ISP without removing the SD card. Does anybody know how to prevent the SD card from interfering with the ISP programming?

Details:

This is the microSD breakout: https://www.adafruit.com/products/254

I'm using an ATMEGA328P at 3.3V 8MHz.

I'm not using a bootloader and, for several reasons, I can't use the serial port for programming.

Thanks!

body:
Because the SD card is an SPI device it shares the same pins as the ISP interface. The only way to not have the SD card interfere with the ISP is to not have the SD card connected.

As you have seen, that can be achieved by removing the card.

It can also be achieved by adding a tri-state buffer between the MCU and the card so the MCU only connects the card to the SPI bus when it is ready to use it - under default operation the card is disconnected.


body:
I had the exact same problem, also using Arduino (Atmega 328P). I have an sd card module with a different layout, but also with a level shifter. My circuit is running at 5V (which is appropriate when using a level shifter).

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

To resolve the issue I just installed a pullup resistor (10k) on my own board to the chip select line of the sd module, which keeps the sd card unselected while programming the MCU. Now it works.

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

There seems to be no pullup integrated into the module. Hence the CS is low during programming (without the pullup), the sd card thinks it should answer the SPI commands, and so interferes with the communication to the MCU, which is why programming over an ISP fails.

  [1]: https://i.stack.imgur.com/PrAD1.jpg
  [2]: https://i.stack.imgur.com/dJq6L.png