message:
Mega pin stuck high after driving optocoupler

I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.

    void setup() {
      pinMode(42, OUTPUT);
      digitalWrite(42, LOW);
    }

    void loop() {
      digitalWrite(42, LOW);
    }

Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is > 1Mohm of isolation between pin 42 and the 5V rail.

body:
Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)

Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current.  If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working).  Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.

(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)


sender: user

message:
Arduino ethernet need help with game logic!

I'm making a game where there are three LEDs and three buttons: 1 LED for 1 button. One has to press the button that has its LED lit. If it is correct, another (random) LED will light up and the game continues. However, if one presses one that isn't lit, one has points taken from one's score.

Example image: https://i.stack.imgur.com/gtnUm.png

I'm having trouble figuring out how to find out when the wrong one is pressed. With the code below it will print "Ouch" whenever the led switches numbers.

Code that switches LED:

    led = random(1, 4);
    switch(led) {
      case 1:
        ledLeftState = HIGH;
        break;
      case 2:
        ledMiddleState = HIGH;
        break;
      case 3:
        ledRightState = HIGH;
        break;
    }

Code that checks if the wrong button is pressed:

     if(digitalRead(BUTTON_LEFT) == LOW && led != 1 || digitalRead(BUTTON_MIDDLE) == LOW && led != 2 || digitalRead(BUTTON_RIGHT) == LOW  && led != 3) {
        static unsigned long lastTime = 0;
        if(millis() - lastTime > 400) {
          Serial.println("Ouch, minus ten miliseconds!");
          hurt += 10;
          lastTime = millis();
        }
      }

Hopefully you can figure this scenario out in your heads, otherwise simply tell me that you'd like code instead of downvoting.

Thanks for your time!

sender: assistant

body:
Off the top of my head and without a compiler would something like this work?

    int BasePin = 3;
    int BaseButton = 7;

    int led = random (1, 4); // Are you sure its 4??
    digitalWrite(BasePin+led, HIGH);

    if (digitalRead(BaseButton+led))
    {
      // Success
    }
    else if (millis() - lastTime > 400))
    {
      // Out of time
    }
    else if (  digitalRead(BaseButton+1)
            || digitalRead(BaseButton+2)
            || digitalRead(BaseButton+3)
    {
      // Wrong button
      // (The right one will have been handled by the earlier clause)
    }

OK the last clause is a bit of a hack, but it should give you a starting point to tidy up.

You are probably going to get issues unless you debounce the switches.


body:
The line

    if(millis() - lastTime > 400)

is supposed to test that the button press does not come right after the
LED switches. This means the line

    lastTime = millis();

should be right when you change the displayed LED.


body:
First: Your buttons are not wired up properly according to the diagram.  They seem to be only connected to 5V.

On Arduino buttons can be wired both active-high and active-low.  Active-high means then when the button is pressed you get a HIGH signal, and LOW otherwise.  Obviously active-low is the opposite.  The code below assumes active-high.

You might want to go do some reading on "[button de-bouncing][1]".  I've included some rudimentary code to help, but it's not perfect.  A 0.1 micro-farad capacitor across the button terminals will help with this too.

So ... onto the code.

It's really the game-loop that needs some work.
I'll assume your random LED-lighting code is in a function called newRandomLED(), and variables *ledLeftState*, *hurt*, etc. are globals.

The *new_pattern_time* variable should probably also be set in newRandomLED() since they always are called together.  But I'm trying to help, not re-write ;)

    const int debounce_time  =  30; // milliseconds
    const int max_push_time  = 400; // milliseconds - How long is a turn

    // Draw the first LED pattern
    newRandomLED();

    // the time the latest LED pattern was re-drawn
    unsigned long new_pattern_time = millis();

    // Reset the score
    hurt = 0;

    while (true) // TODO: insert some game-length decision
    {
        // Has the time to press a button expired?
        if (millis() - new_pattern_time > max_push_time)
        {
            // TODO: sound the buzzer for *fail*

            // Time is up, penalise the user
            hurt += 10;

            // Time for a new pattern
            newRandomLED();
            new_pattern_time = millis();
        }

        // Perform the initial-read of the buttons
        int butt_left  = digitalRead(BUTTON_LEFT);
        int butt_mid   = digitalRead(BUTTON_MIDDLE);
        int butt_right = digitalRead(BUTTON_RIGHT);

        // de-bounce the button presses
        delay(debounce_time);
        if (butt_left == HIGH)
            butt_left = digitalRead(BUTTON_LEFT);
        if (butt_mid  == HIGH)
            butt_mid = digitalRead(BUTTON_MIDDLE);
        if (butt_right == HIGH)
            butt_right = digitalRead(BUTTON_RIGHT);

        // So now we have the state of the three buttons, de-bounced too.
        // Was there any input from the user?
        if (butt_left == HIGH || butt_mid == HIGH || butt_right == HIGH)
        {
            // So one (or more) buttons have been pressed
            // Check that for each LED that is on, that the button is pressed too
            boolean success = true;
            if (ledLeftState != butt_left)
                success = false;
            if (ledMiddleState != butt_middle)
                success = false;
            if (ledRightState != butt_right)
                success = false;

            // Was the user correct?
            if (success == true)
            {
                // TODO: sound the buzzer for *WIN*
                hurt -= 10;

                // And we need to show the next pattern
                newRandomLED();
                new_pattern_time = millis();
            }
        }
    }

So essentially you're looping around checking to see if the player pressed anything.  Most of the time, there will be no input from the user, and this loop will spin thousands of times without any input.

On each loop the code checks to see if the time is up, or some buttons were pushed.  In both cases, it's time for a new pattern.  A side effect of this code is that it allows for simultaneous button pushes, so at higher difficulty levels you could illuminate more than 1 LED.

Note: this code is a quick response to the question.  It may not be 100% correct, nor have flawless C-textbook syntax.

  [1]: https://www.arduino.cc/en/Tutorial/Debounce


message:
Using a state machine

I'm trying to get a strip of Neopixels to circle through its length, one LED at a time, I want it to do it faster as the value received from the sensor increases

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

    #include <FastLED.h>
    #define NUM_LEDS    34
    #define DATA_PIN    6
    #define SENSOR_PIN  A0

    int airPressure,
        barometricToRGB,
        frequency       = 0,
        high            = 0,
        low             = 600,
        interval        = 50;

    long previousMillis = 0;

    CRGB leds[NUM_LEDS];

    void setup() {
      Serial.begin(115200);
      pinMode(SENSOR_PIN,INPUT);
      FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
    }

    void loop() {
      airPressure = analogRead(SENSOR_PIN);
      autoTune();

      unsigned long currentMillis = millis();
      Serial.print("frequency ");
      Serial.println(frequency);
      Serial.print("Time to beat ");
      Serial.println(frequency*interval);
      Serial.print("Last Called ");
      Serial.println(currentMillis - previousMillis);

      if(currentMillis - previousMillis > (frequency/interval)) {
        previousMillis = currentMillis;

        for (int i=0; i<NUM_LEDS; i++) {
              leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
              FastLED.show();
            }
      }
    }

    void autoTune() {
      if (airPressure < low) {
        low = airPressure;
      }
      if (airPressure > high) {
        high = airPressure;
      }
      barometricToRGB = map(airPressure, low, high, 1, 255);
      barometricToRGB = constrain(barometricToRGB, 1, 255);
      frequency = map(airPressure, low, high, 1, 100);
      frequency = constrain(frequency, 1, 100);

    }

While I had managed to cause the color to change based on the sensor, I can't seem to understand how to control how fast it will go, every how long.

body:
Are these reversed?

    high            = 0,
    low             = 600,

It looks like high and low both get set to airPressure on the first pass through autoTune(). If the pressure drops after this, for example, low will track airPressure and high will stay the same.

Also, with frequency 1 to 100 and interval 50 the largest time difference is 2 milliseconds and the smallest is 0.  Your loop could be taking 2 ms without the if statement.


body:
Ok, if I understood what you meant, you want that a single led in the ring is on and the refresh rate is dependent on the pressure, right?

If so, you did not write any "select this led" code, so it can't work.

I fixed a couple of things in your code. Mainly:

1. added the circularity to the ring (with variable `currentlyOnLed`)
2. fixed some types (use the `byte` unless you need a bigger type)
3. removed some `constrain`s, which were reduntant
4. `frequency*interval` instead of `frequency/interval` (I guess it was a typo)
5. I prefer summing the step instead of setting `previousMillis` to `currentMillis`, so you will not add error with time passing
6. moved `FastLED.show()` outside the loop: I'm not sure about this, but I think that you don't need to call it every loop. I can't test it, anyway.

So, here is the fixed code. Let us know if it works for you

    #include <FastLED.h>
    #define NUM_LEDS    34
    #define DATA_PIN    6
    #define SENSOR_PIN  A0

    int airPressure;
    int high  = 0;
    int low   = 600;
    byte barometricToRGB;
    int frequency = 0;
    byte interval = 50;
    byte currentlyOnLed;

    long previousMillis = 0;

    CRGB leds[NUM_LEDS];

    void setup() {
     Serial.begin(115200);
     pinMode(SENSOR_PIN,INPUT);
     FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
     currentlyOnLed = 0;
    }

    void loop() {
     airPressure = analogRead(SENSOR_PIN);
     autoTune();

     unsigned long currentMillis = millis();
     Serial.print("frequency ");
     Serial.println(frequency);
     Serial.print("Time to beat ");
     Serial.println(frequency*interval);
     Serial.print("Last Called ");
     Serial.println(currentMillis - previousMillis);

     if(currentMillis - previousMillis > (frequency*interval)) {
      previousMillis += (frequency*interval);

      //Set next on led
      if (currentlyOnLed >= NUM_LEDS - 1)
       currentlyOnLed = 0;
      else
       currentlyOnLed++;

      for (byte i=0; i<NUM_LEDS; i++) {
       if (i == currentlyOnLed)
        leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
       else
        leds[i] = CRGB::Black;
      }
      FastLED.show();
     }
    }

    void autoTune() {
     airPressure = constrain(airPressure, low, high);
     barometricToRGB = map(airPressure, low, high, 1, 255);
     frequency = map(airPressure, low, high, 1, 100);
    }


message:
1x4 Button membrane help

Im trying out [this membrane][1] from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?

**UPDATE**

Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on `HIGH`. i used `Serial.println(digitalRead(one));` to verify that and the output was 1.

    int two =  8;
    int one = 9;
    int four = 10;
    int three = 11;

    void setup() {
      pinMode(one, INPUT);
      pinMode(two, INPUT);
      pinMode(three, INPUT);
      pinMode(four, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      if(digitalRead(one) == LOW){
        Serial.println("One");
      }else if(digitalRead(two) == LOW){
        Serial.println("Two");
      }else if(digitalRead(three) == LOW){
        Serial.println("Three");
      }else if(digitalRead(four) == LOW){
        Serial.println("Four");
      }
    }

  [1]: http://www.adafruit.com/products/1332?gclid=CjwKEAjw7aiwBRCPgdu70arX70wSJADK6iDD89H4xAIdw88_bv9K8EcrhdbdzERDU0gKJgrRwAcO2xoClM_w_wcB

body:
>     pinMode(one, INPUT);

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You *must* enable the pullup on the pins (and connect the common to ground) if you want correct operation.

     pinMode(one, INPUT_PULLUP);


message:
Can a ESP8266 and a HC-SR04 be friends?

I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.

The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.

    duration = pulseIn(echoPin, HIGH);

Any idea on how I can change the pulseIn function with interrupts or something else?

Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...

body:
`pulseIn()` is actually a very simple function.  As long as there is a microseconds counter of some form available you can easily enough roll your own.

Also, I don't know which implementation of the ESP8266 plugin you are using, but [the one I use](https://github.com/esp8266/Arduino) has [pulseIn available](https://github.com/esp8266/Arduino/blob/esp8266/hardware/esp8266com/esp8266/cores/esp8266/core_esp8266_wiring_pulse.c).


body:
I had trouble with pulseIn() until the proper initializing code was put in setup().

As follows:

  pinMode(TRIGGER, OUTPUT);

  digitalWrite(TRIGGER, LOW);

  delay(2);

  pinMode(ECHO, INPUT);

TRIGGER and ECHO were initially defined at top of code with other variables as follows:

  #define TRIGGER 13 // Data pin D7

  #define ECHO    12 // Data pin D6

My HC-SR04 board was wired to D7 and D6, but D1 and D2 are often used.

Project was a 'Tide' reporting system. A work in progress.
Also found HC-SR04 board was  unstable if using 3.3vdc as VCC. Works better if the HC-SR04 board VCC is tide to Vin on the ESP8266 board.


message:
Dust sensor for Arduino in open and windy environment

I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition?
Any implementation ideas are also welcome.

body:
It depends on how far you want to go.  If you are looking for something cheap, than a GP2Y1010AU0F will only cost you a few pounds.  Or you could step up to £30 GBP or even £1000GBP.

Since you are looking at using an Arduino and not a PC then I'm guessing the GP2Y1010AU0F would be a good idea.  I haven't tried it but this site should steer you the right way: http://arduinodev.woofex.net/2012/12/01/standalone-sharp-dust-sensor/


body:
A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.

I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.

I mainly followed this blog's instructions for the code:
http://www.howmuchsnow.com/arduino/airquality/grovedust/

I think I read a few months ago that the next best sensors are in the $200 range.

I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.


message:
Arduino: how can I stop while() when bluetooth send a data?

I have learned Arduino for a month, and I want to bulid a car with 2 modes,
Remote and Auto. Auto mode needs to have while() loop, so it can receive data from sensors. When I choose Auto mode via bluetooth, it keeps looping and it won't stop when I choose the Remote mode. Here's the part code:

    char mode;

    void loop()
    {
        while(serial1.available())
        {
            char control = serial.read();
            if(control == 'r') mode = 'r';     // r stand for Remote Mode
            if(control == 'a') mode = 'a';     // a stand for Auto Mode

            if(mode == 'r') remoteMode(control);

            while(mode = 'a')
            {
                int IR = analogRead(A10);
                float U1cmMsec,U2cmMsec;
                long U1microsec = u1.timing();
                long U2microsec = u2.timing();
                U1cmMsec = u1.convert(U1microsec, Ultrasonic::CM);
                U2cmMsec = u2.convert(U2microsec, Ultrasonic::CM);

                robot(U1cmMsec, U2cmMsec,IR);

                /*
                Here is the code to stop while() that I don't know how
                to program.
                I have tried:

                if(serial1.read() != 'a') break;

                But it will stop while(), because it will waits for
                bluetooth send data to arduino board.
                And if I take this line off, it will keeps while() and
                nothing can stop it.
                So, what am I supposed to do?
                */
            }
        }
    }

body:
Your problem is with this line:

    while(mode = 'a') {

What you are saying there is not what you think you are saying.  You are confusing `=` (assignment) with `==` (comparison).

You are basically saying "While I assign 'a' to the variable 'mode' and 'a' is not 0 ...", which of course will always be true.

Instead you want:

    while (mode == 'a') {

or, "While the variable 'mode' contains the letter 'a' ..."

Now you just need to program in some way of changing the value of `mode` within your while loop.

You can read more on while loops here:

* http://hacking.majenko.co.uk/the-while-loop


body:
The `while(serial1.available())` can be turned into an `if`: the loop function is already executed in a loop, as the name hints :-)

And unnest the inner `while`.

here it is at high level, which is probably easier to understand:

`
void loop() {
  static char mode; /*notice the "static"*/
  if (character_available())
    update_mode();
  if (mode == 'r')
    do_one_iteration_in_remote_mode();
  else if (mode == 'a')
    do_one_iteration_in_auto_mode();
}
`

Just make sure that you do not loop inside neither `do_one_iteration_in_remote_mode()` nor `do_one_iteration_in_auto_mode()`.


body:
I have replaced both 'mode' and 'control' (they were identical) with a single variable, `btChar`. At the end of `setup()`, wait for a transmission to be received before entering the main loop.

Once the main loop begins, a while loop executes until the serial receives a new transmission. Once it is received it is read, btChar is updated and the main loop starts again.

    char btChar;

    void setup()
    {
    /* AT THE END OF SETUP() */

    // Wait in setup for first BT transmission

        while (!serial1.available())
        { /* do nothing */ }
        btChar = serial1.read();
    }

    void loop()
    {
        while(!serial1.available())
        {
        // Program will stay in this 'while' loop until
        //    a new BT character is recv'd

            switch(btChar)
            {
                case('a'):
                {
                // do the 'auto' stuff
                    break;
                }
                case('r'):
                {
                // do the 'remote' stuff
                    break;
                }
                default: // this 'block' is not essential
                {
                // you end up here if neither 'a' nor 'r' was received
                }
            }
        }
        btChar = serial1.read();
    }

You can adapt the setup while-loop further to make sure that the main loop doesn't begin until the a correct character is received - change the line to:

    while ((!serial1.available())&&(btChar != 'a')&&(btChar != 'r'))

Using a `switch-case` statement within the main while-loop is not essential, and I included it out of interest more than necessity. You can use `if` statements instead, with one for 'a' and one for 'r'. However, in the event that you have a third or fourth (or more-th) mode then a switch-case statement, in my view, looks easier to read.


message:
Arduino wire can't send char

Hi I have problem with school project. I have 3 Arduino - 1 Transmiter with NRF; 2,3 - NRF receiver and wire slave receiver.
I can't send data via "Wire" library (in code char "datar") to receiver arduino. I won't get anything, but when I want to send like `Wire.write("blablabla");` it pass. But when in char is NRF data code crashing when go to "Wire.write".

    /*
    */
    #include <Wire.h>
    #include <SPI.h>
    #include "RF24.h"

    char datar = '';

    //Konfiguracja
    const uint64_t pipes[2] = {0xF1F2F3F0F7/*odbieranie*/, 0xF1F2F3F0F8/*wysylanie*/};
    RF24 radio(9, 10); //Piny nrf (SPI) 9 i 10
    //-- Konfiguracja

    void setup() {
      Serial.begin(9600);
      Serial.println("LOL");
      Wire.begin();
      radio.begin();
      radio.setPALevel(RF24_PA_MAX);
      radio.setDataRate(RF24_250KBPS);
      radio.openReadingPipe(1, pipes[0]);
      radio.openWritingPipe(pipes[1]);
      radio.setChannel(78);
      radio.setAutoAck(true);
      radio.startListening();
    }

    void loop() {

      int len;
      if(radio.available())
      {
      len = radio.getDynamicPayloadSize();
      radio.read(&datar, len);
      delay(5);
      Serial.println(datar);
      Wire.beginTransmission(7);
      Wire.write(&datar);
      Wire.endTran345smission();
      radio.printDetails();
      }
      delay(5);

    }

body: The  code crash because you pass an memory address to the write function if you look to the arduino doc you pass a variable to the function therefore just writing datar as argument will end your problem


body:
Your problem is here:

    char datar = '';

    ...

     len = radio.getDynamicPayloadSize();
     radio.read(&datar, len);

The variable "datar" is one byte long. You then find the payload size (presumably greater than one byte) and read into `datar` more than one byte. This overwrites other parts of memory and the program crashes. You need to make `datar` larger, eg.

    char datar [50];

The exact size would depend on your maximum payload size.


body:
I think the answer is a combination of Nick and Mathieu's answers.

Like Nick said you haven't assigned any memory to datar, so this is probably causing a crash because of buffer overrun.

Now to the call to read.  Mathieu said you are passing a pointer into the function when you probably didn't mean to.  But if you put Nicks change in then you **do** need to pass in a pointer to the character array.  You can do this by `radio.read(datar, len);` because the character array is a character pointer.
You **do not** want to pass a pointer to a character pointer `&datar` because that would mean the function was able to move the memory that you have allocated.

Also, you need to prevent buffer overflows in the "new improved" code by checking that the value of `len` is less than or equal to the value you allocated when you declared the data buffer (i.e. 50).  Because you are using a number in two places you should declare it as a constant at the top of the file.

    const int MaxBufferSize = 50;
    char datar[MaxBufferSize];
    ...
    len = radio.getDynamicPayloadSize();
    if (len > MaxBufferSize)
      len = MaxBufferSize;
    radio.read(datar, len);

Hope that helps.


message:
Decoding IR codes with IR sensor rather than IR receiver module

I'm looking for a library to decode RAW IR signals from an IR sensor (looks like a black LED, two legged) rather than an IR module (3 legged, rated for a particular frequency - such as 38kHz).

Is there a library that supports IR sensors?

A picture of the two possibilities can be seen [here]( http://www.instructables.com/id/How-to-use-IR-Sensor-using-Op-amp-and-Arduino/)

EDIT: This isn't a duplicate of [my previous post](https://arduino.stackexchange.com/questions/16361/a-c-doesnt-detect-ir-codes-sent-from-arduino), it is related to the same project however.
On my previous question I asked what could be the cause. I've found out what it is - frequency. My previous IR detector was an IR module and not an IR sensor. The difference could be seen [here]( http://www.instructables.com/id/How-to-use-IR-Sensor-using-Op-amp-and-Arduino/)

body:
> I'm looking for a library to decode RAW IR signals from an IR sensor

[AGirs][1] includes a comprehensive library designed to work with raw IR signals. I've used GirsLite in an Arduino and [IrScrutinzer][2] in Windows to do advance IR protocol snooping.

  [1]: https://github.com/bengtmartensson/AGirs
  [2]: https://github.com/bengtmartensson/harctoolboxbundle/tree/master/IrScrutinizer


body:
I had a similar project a few months back and spotted this Arduino Library:

https://github.com/z3t0/Arduino-IRremote

and it is invaluable.

For your instance, you want the RAW Data which you can achieve using an Example included in the Library named: IRrecvDemo.

The wiring is easy and straight forward

> An IR detector/demodulator must be connected to the input RECV_PIN.

Which is 11 by default but you can definitely change it :3

and the other two Legs of the IR detector/demodulator go to the power source.


body:
IRremote (already recommended) - but to save you some time, use the IRRecvDump example to grab the raw codes you need for `sendRaw()`. They need to be averaged out across 10-20 reads. I log the output to a file, and use a perl script to do it for me, since it is painful to type this into a calculator a million times. The resistor you connect to the sensor affects its sensitivity - I used 330ohm, and have ~10 metres range from a 3V3 remote inside, 4-5 metres outside in sunlight. I would give you the script, but it's on my desktop. Let me know if you need it - or just use python, which is so popular nowadays (indent-or-fail... feh. what about people who don't like setting up the tab-space continuum, and don't have fancy editors...mumblemumble)
Edit: my raw codes absolutely needed to be averaged out, or they were useless. Any negative values in the array can just be made positive, don't fret.


message:
Running Arduino code for Bluefruit LE on bare ATMega328

I need to hook up [Bluefruit LE Breakout][1] (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the [library provided][2] is for Arduino.

What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.

Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.

And this is where I need help:

How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).

And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).

Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.

UPDATE: Similar question: http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal

  [1]: https://learn.adafruit.com/downloads/pdf/getting-started-with-the-nrf8001-bluefruit-le-breakout.pdf
  [2]: https://github.com/adafruit/Adafruit_nRF8001/archive/master.zip

body:
The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.

You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.

You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of `Upload`, choose `Upload using Programmer` (in the `Sketch` menu).


message:
How to find the deferenced value of a transmit Port Register?

So I am working with the SoftwareSerial library. I'm looking at the write function and I see a *reg value being manipulate. I want to find the value of *reg so I traced the value by stepping into each function call.so here we go.

    *reg = _transmitPortRegister
    _transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D
Continuing...

    #define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )

    const uint16_t PROGMEM port_to_output_PGM[] = {
        NOT_A_PORT,
        NOT_A_PORT,
        (uint16_t) &PORTB,
        (uint16_t) &PORTC,
        (uint16_t) &PORTD,
    };

My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

Continuing on,

    #define PORTB _SFR_IO8(0x05)
    #define PORTC _SFR_IO8(0x08)
    #define PORTD _SFR_IO8(0x0B)

    #define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET)
    #define __SFR_OFFSET 0x20

    #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.

    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);
      b >>= 1;
    }

In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte"
and inside the if-else blocks, they're just oring *reg with reg_mask. How does that translate to sending a one?

Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know.

body:
> My first question is what is the point of (uint16_t) &PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int.

No.  You're mistaking the operator.  In this context `&` means *the address of*, so it is getting the address of the variable called `PORTD` and casting it to an unsigned 16-bit integer, which it's then storing in the array.

>Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.

Again, we're talking addresses.  The port register number is (for port D) 0x0B.  Add that to 0x20 and you get 0x2B which is the address of the register in memory.  Then comes the tricky bit:

    #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

Expand that out with 0x2B and you get:

    (*(volatile uint8_t *)(0x2B))

Now, working from the inside out we have:

    (volatile uint8_t *)(0x2B)

That says *this is a pointer to address 0x2B*.

Then that is de-referenced to get the value from that pointer with a `*` operator:

    *(volatile uint8_t *)(0x2B)

So you end up with "The value that is in the address 0x2B"

If we then feed that back into the first part of your question, so:

    PORTD = (*(volatile uint8_t *)(0x2B))

then `&PORTD` would be:

    &(*(volatile uint8_t *)(0x2B))

The initial & and * cancel each other out (you can think of them as opposites - one is get the address from a value, the other get a value from an address), so you effectively end up with:

    (volatile uint8_t *)0x2B


body:
    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);
      b >>= 1;
    }

> In that block of code, I am not quite sure why they are doing b & 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks,

The comment is: choose **bit**

First, variable `b` is the **byte** that is being set. Now, since async serial sends the least-significant bit first, at the start of the loop of 8 iterations, it takes the low-order bit to see if it is set or not:

      if (b & 1) // choose bit

If set, it sets the output port to HIGH (by ORing in the appropriate mask to the appropriate register), otherwise it sets the port to LOW (by ANDing in the appropriate inverted mask to the appropriate register). The inverted mask would be set to every bit **but** one.

Now look at this:

      b >>= 1;

That shifts the bits right one, throwing away the low-order bit. Now what was previously the second lowest-order bit is now the low-order bit. Then the loop repeats. Now the next bit is sent. And so on for 8 bits.

Imagine we were sending 0x39 (0b00111001). For the 8 iterations of the loop we would see:

    00111001  --> 1 sent, then "b" shifted right one
    00011100  --> 0 sent, then "b" shifted right one
    00001110  --> 0 sent, then "b" shifted right one
    00000111  --> 1 sent, then "b" shifted right one
    00000011  --> 1 sent, then "b" shifted right one
    00000001  --> 1 sent, then "b" shifted right one
    00000000  --> 0 sent, then "b" shifted right one
    00000000  --> 0 sent, then "b" shifted right one

You can see that the right-most bit is sent (the low-order bit) and then `b` is shifted right (introducing zeroes at the left), until all 8 bits are sent.


message:
2.8" tft screen arduino all pins used

I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: https://arduino.stackexchange.com/questions/12076/2-8-tft-touchscreen-prohibits-access-to-unused-pins)

However, they recommend a proto screw shield (show here: http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg==&gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&kpid=1480459155)

However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?

Thanks!

body:
You're confusing the idea of *using* all the pins to that of *plugging into* all the pins.

Yes, your shield may well have all the pins on it which then fill all the available holes.  Only some of them will actually be connected to anything on the circuit board though.

The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.

You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.


message:
Programming a motor with an RGB

*Please see the comments section if confused.*
I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V.
I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.

    void setup ()
    {
      pinMode(0,OUTPUT); //IB1
      pinMode(1,OUTPUT); //IA1
    ////  pinMode(2,OUTPUT); //IB2
    ////  pinMode(3,OUTPUT); //IA2
    //  pinMode(4,OUTPUT); //RGB
    //  pinMode(5,OUTPUT); //RGB
    //  pinMode(6,OUTPUT); //RGB
    //  pinMode(A0,INPUT); //lMotor
    ////  pinMode(A1,INPUT); //rMotor
    //  Serial.begin(9600);
    }

    void loop ()
    {
      digitalWrite(0,HIGH);
      delay(1000);
      digitalWrite(0,LOW);
      delay(1000);

    //  int lMotor = analogRead(A0);
    //  Serial.write(lMotor);
    ////  int lMotor = analogRead(A1);
    ////  Serial.write(lMotor);
    //
    //  if (lMotor>10)
    //  {
    //    digitalWrite(4,HIGH);
    //    digitalWrite(5,HIGH);
    //    digitalWrite(6,LOW);
    //  }
    //  else
    //  {
    //    digitalWrite(4,HIGH);
    //    digitalWrite(5,LOW);
    //    digitalWrite(6,HIGH);
    //  }
    }

And here's this:

    void setup ()
    {
      pinMode(0,OUTPUT);
      pinMode(1,OUTPUT);
    }

    void loop ()
    {
      digitalWrite(0,HIGH);
      delay(1000);
      digitalWrite(0,LOW);
      delay(1000);
    }

What do I need to do? Should I use a "while" loop? If so, how?
Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right.
Any help is appreciated, even if it doesn't answer all of my questions.
Thank you.

body:
Try this:

    void setup ()
    {
      pinMode(0,OUTPUT); //IB1
      pinMode(1,OUTPUT); //IA1
    //  pinMode(2,OUTPUT); //IB2
    //  pinMode(3,OUTPUT); //IA2
      pinMode(4,OUTPUT); //RGB red
      pinMode(5,OUTPUT); //RGB green
      pinMode(6,OUTPUT); //RGB blue
      boolean motorOn = false;
    }

    void loop ()
    {
      digitalWrite(0,motorOn);
      if(motorOn) {
        digitalWrite(4,HIGH);  // red on
        digitalWrite(5,LOW);   // green off
        digitalWrite(6,LOW);   // blue off
      }
        digitalWrite(4,LOW);   // red off
        digitalWrite(5,HIGH);  // green on
        digitalWrite(6,LOW);   // blue off
      }
      delay(1000);             // wait
      motorOn = !motorOn;      // toggle the status of the motor.
    }

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:

    void setup ()
    {
      pinMode(0,OUTPUT);   //IB1
      pinMode(1,OUTPUT);   //IA1
    //  pinMode(2,OUTPUT); //IB2
    //  pinMode(3,OUTPUT); //IA2
      pinMode(4,OUTPUT);   //RGB red
      pinMode(5,OUTPUT);   //RGB green
      pinMode(6,OUTPUT);   //RGB blue
      boolean motorOn = false;
    }

    void loop ()
    {
      motorOn = false;
      digitalWrite(0,motorOn);
      updateLEDs();            // update the LED status
      delay(1000);             // wait
      motorOn = true;          // toggle the status of the motor.
      digitalWrite(0,motorOn);
      updateLEDs();            // update the LED status
      delay(750);              // wait a different time
    }

    void updateLEDs(){
      // This routine updates the LEDs based on status of motorOn.
      if(motorOn) {
        digitalWrite(4,HIGH);  // red on
        digitalWrite(5,LOW);   // green off
        digitalWrite(6,LOW);   // blue off
      }
        digitalWrite(4,LOW);   // red off
        digitalWrite(5,HIGH);  // green on
        digitalWrite(6,LOW);   // blue off
      }
    }


message:
Cost-effective storage for prototyping

In my project I need to add some storage space and I don't want to use an SD card, because in the "final product" the user shouldn't be able to access the data on their own.

So I was considering the options here [http://playground.arduino.cc/Main/InterfacingWithHardware#Storage][1] but many of the technologies are either outdated, for example as reads [here][2] ADESTO is discontinuing production of dataflash, or they give too little memory, like the I2C EEPROM (which is 128KByte per chip and I would rather not go through the hassle of multiplexing lots of memory chips since I'd like to have 1MByte of storage at least), or are extremely overpriced and cannot be found on retail: some sites require you to buy 2000$ worth of chips or charge you 30$ for delivery, which kind of kills the fun of prototyping something.

I know I am being picky not wanting to use an SD for the prototype, but I would like to know if you ever faced this problem and how you solved it, or if you know some alternative solution which gives a good amount of memory (~1 or 2 MBytes at least) within reasonable costs.

  [1]: http://playground.arduino.cc/Main/InterfacingWithHardware#Storage
  [2]: http://forum.arduino.cc/index.php?topic=298022.0#msg2356709

body:
There are plenty of serial flash products available.  They are generally SPI chips (8 pin) and range in sizes up to about 64MBit (8MByte).  And they're cost effective.

Here's a selection: http://www.microchip.com/pagehandler/en-us/products/memory/flashmemory/sfhome.html

There are plenty of other manufacturers as well.  Your best bet is to hit your favourite online electronics store (mouser, digikey, etc) and shop around.


body:
You may not want to hear this, but the cheapest option would be an SD card, or a micro-SD card. You could solder it into place, thus making it quite hard for the end user to take it out and plug it into a reader.

Imagine you had this micro-SD card glued onto your board (making it hard to remove in the first place):

[![Micro-SD card][1]][1]

It isn't particularly obvious what it is, unless you recognize the shape. You could cover it with a blob of plastic to hide that. Then with the SPI wires soldered to the contacts, removing would be even harder.

That gives you gigabytes of storage, a file system, the works. And all for a few dollars.

A technically sophisticated user could probably prise it loose and get at the data (although if you used strong glue this could be quite hard) but they could also get at the contents of another storage chip too.

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


message:
Programming an ATMEGA2560 using FTDI

I want to know how exactly do I program (upload arduino sketches) an ATMEGA2560 which is boot loaded with an Arduino Bootloader using a FTDI programmer and an Arduino IDE, is there any capacitors/resistors required?

body:
If you have a bootloader, you just need to connect up four wires from the FTDI cable:

* Pin 1 (black) -> Ground
* Pin 2 (CTS)   -> not connected
* Pin 3 (Vcc)   -> 5V
* Pin 4 (TxD)   -> Rx (Mega pin D0)
* Pin 5 (RxD) -> Tx (Mega pin D1)
* Pin 6 (green) -> not connected

[![FTDI connections][1]][1]

This will not auto-reset, so you will have to press (and release) the Reset button on the board at the moment that the sketch starts to upload.

---

> How to make it auto reset?

What you *should* be able to do is connect RTS to Reset on the board, using a 0.1 µF capacitor (in series). I found in practice that this did not bring Reset low enough to trigger it - I'm not sure why, except maybe the board has a stronger pull-up resistor on /RESET than expected. That technique works for me on breadboard Arduinos.

Since it didn't work for me, I did not put it in my original answer. You could try that, and if it works, well and good.

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


message:
how to create a specific buffer when there is no buffer message in the data packet?

So I'm trying to understand a read method. In this method,

    // Read data from buffer
    int SoftwareSerial::read()
    {
    if (!isListening())
      return -1;

    // Empty buffer?
    if (_receive_buffer_head == _receive_buffer_tail)
      return -1;

    // Read from "head"
    uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
    _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
    return d;
    }

it looks it receives buffer head. But in the write only a 1 or 0 is being sent as the data packet's header. Nothing else. So how does the arduino know how big of an buffer to create?
also, there is no stop bit being transmitted, so how does it look at a buffer tail? Or is this all created regardless of the transmitter? and then, all the values just get read into the buffer, and then read again from there? Also I don't see a delay in this read method. Wouldn't that cause errors in the data flow? How is that being handled?

body:
That read method just retrieves bytes that have already been received from an internal buffer.

The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten.  You have to be sure to read your data from the buffer before it overflows.

The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:

    void SoftwareSerial::recv()
    {

    #if GCC_VERSION < 40302
    // Work-around for avr-gcc 4.3.0 OSX version bug
    // Preserve the registers that the compiler misses
    // (courtesy of Arduino forum user *etracer*)
      asm volatile(
        "push r18 \n\t"
        "push r19 \n\t"
        "push r20 \n\t"
        "push r21 \n\t"
        "push r22 \n\t"
        "push r23 \n\t"
        "push r26 \n\t"
        "push r27 \n\t"
        ::);
    #endif

      uint8_t d = 0;

      // If RX line is high, then we don't see any start bit
      // so interrupt is probably not for us
      if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
      {
        // Wait approximately 1/2 of a bit width to "center" the sample
        tunedDelay(_rx_delay_centering);
        DebugPulse(_DEBUG_PIN2, 1);

        // Read each of the 8 bits
        for (uint8_t i=0x1; i; i <<= 1)
        {
          tunedDelay(_rx_delay_intrabit);
          DebugPulse(_DEBUG_PIN2, 1);
          uint8_t noti = ~i;
          if (rx_pin_read())
            d |= i;
          else // else clause added to ensure function timing is ~balanced
            d &= noti;
        }

        // skip the stop bit
        tunedDelay(_rx_delay_stopbit);
        DebugPulse(_DEBUG_PIN2, 1);

        if (_inverse_logic)
          d = ~d;

        // if buffer full, set the overflow flag and return
        if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
        {
          // save new data in buffer: tail points to where byte goes
          _receive_buffer[_receive_buffer_tail] = d; // save new byte
          _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
        }
        else
        {
    #if _DEBUG // for scope: pulse pin as overflow indictator
          DebugPulse(_DEBUG_PIN1, 1);
    #endif
          _buffer_overflow = true;
        }
      }

    #if GCC_VERSION < 40302
    // Work-around for avr-gcc 4.3.0 OSX version bug
    // Restore the registers that the compiler misses
      asm volatile(
        "pop r27 \n\t"
        "pop r26 \n\t"
        "pop r23 \n\t"
        "pop r22 \n\t"
        "pop r21 \n\t"
        "pop r20 \n\t"
        "pop r19 \n\t"
        "pop r18 \n\t"
        ::);
    #endif
    }

To show you how the timing of the routine works, here is a little diagram:

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

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


message:
After moving project from Arduino Mega to Due, pushbuttons now erratically toggle multiple buttons

I've had a project running successfully for months on an Arduino Mega, and today I tried to swap the Mega for a Due to increase the speed. After making the change, the entire project is working successfully except for a strange problem with the pushbuttons.

I have 5 momentary pushbuttons that toggle different controls (they simply send a wireless signal to toggle different AC outlets). After moving the project to the Due, when 1 button is pressed, it ends up toggling 2 other buttons at the same time.

Originally I was using the internal pullups to detect when the buttons were low, but also I've tried connecting them to the Due's 3.3v to detect when they're high, and both times I experienced the exact same behavior.

Is there any reason why there would be this difference in pushbutton-reading behavior between the Mega and the Due? Could it be that the Due is more sensitive to noise? How could I fix this?

The wires connecting to the pushbuttons run about 8 feet. I never had a problem with this setup while running the sketch on the Mega.

Below is the relevant code that detects button presses:

    #include <Wire.h>
    #include <SPI.h>
    #include <Ethernet.h>
    #include <RCSwitch.h>
    #include <Servo.h>
    #include <Event.h>
    #include <Timer.h>
    #include <dht.h>
    #include "RTClib.h"

    const byte nl1ButtonPin = 40, nl2ButtonPin = 42, nl3ButtonPin = 44,  pumpButtonPin = 5, irButtonPin = 27,

    unsigned long buttonPressTime1, buttonPressTime2, buttonPressTime3, buttonPressTime4, buttonPressTime5;  // when the switch last changed state

    byte oldButtonState1 = HIGH, oldButtonState2 = HIGH, oldButtonState3 = HIGH, oldButtonState4 = HIGH, oldButtonState5 = HIGH;

    const unsigned long debounceTime = 100;

    void setup() {
      pinMode(nl1ButtonPin, INPUT_PULLUP); pinMode(nl2ButtonPin, INPUT_PULLUP); pinMode(nl3ButtonPin, INPUT_PULLUP); pinMode(pumpButtonPin, INPUT_PULLUP); pinMode(irButtonPin, INPUT_PULLUP);
    }

    void loop() {
     byte buttonState1 = digitalRead(nl1ButtonPin);
      if (buttonState1 != oldButtonState1)
      {
        if (millis () - buttonPressTime1 >= debounceTime)
        {
      buttonPressTime1 = millis ();  // when we closed the switch
      oldButtonState1 = buttonState1;  // remember for next time
      if (buttonState1 == LOW) {
        Serial.println("button1 LOW!");
        toggleLight1();
       }
     }
    }

       byte buttonState2 = digitalRead(nl2ButtonPin);
      if (buttonState2 != oldButtonState2)
      {
        if (millis () - buttonPressTime2 >= debounceTime)
        {
          buttonPressTime2 = millis ();  // when we closed the switch
          oldButtonState2 = buttonState2;  // remember for next time
          if (buttonState2 == LOW) {
            Serial.println("button2 LOW!");
            toggleLight2();
          }
        }
      }

    byte buttonState3 = digitalRead(nl3ButtonPin);
    if (buttonState3 != oldButtonState3)
    {
      if (millis () - buttonPressTime3 >= debounceTime)
      {
        buttonPressTime3 = millis ();  // when we closed the switch
        oldButtonState3 = buttonState3;  // remember for next time
        if (buttonState3 == LOW) {
          Serial.println("button3 LOW!");
          toggleLight3();
        }
      }
    }

    byte buttonState4 = digitalRead(pumpButtonPin);
    if (buttonState4 != oldButtonState4)
    {
      if (millis () - buttonPressTime4 >= debounceTime)
      {
        buttonPressTime4 = millis ();  // when we closed the switch
        oldButtonState4 = buttonState4;  // remember for next time
        if (buttonState4 == LOW) {
          Serial.println("button4 LOW!");
          togglePump();
        }
      }
    }

    byte buttonState5 = digitalRead(irButtonPin);
    if (buttonState5 != oldButtonState5)
    {
      if (millis () - buttonPressTime5 >= debounceTime)
      {
        buttonPressTime5 = millis ();  // when we closed the switch
        oldButtonState5 = buttonState5;  // remember for next time
        if (buttonState5 == LOW) {
          Serial.println("button5 LOW!");
          toggleHeater();
        }
       }
      }
    }
On the serial output, pressing one button shows 2 other buttons as low. So, for example, pressing button2 might show: "Button2 LOW!, Button4 LOW!, Button1 LOW!". There doesn't seem to be any clear patterns with which other 2 buttons get simultaneously pressed. Remember that this exact same code and hardware setup was working perfectly for months on the Mega, which makes me believe maybe it's something related to the Due (maybe 3.3v, maybe stronger PU resistors, etc).

body:
I finally got it working. The problem was with this 5-way tact switch being initially incompatible with the Due: http://www.ebay.com/itm/5-Channel-Way-Tactile-Switch-Breakout-Module-Converter-Adapter-Board-Arduino-/141745152805 . As you can see from the picture and the description on that page, the switch includes pullup resistors on the board. I measured those resistors at 10k Ohms. For some reason the switch worked perfectly fine with the Mega's pullup resistors, but didn't work with the Due's.

[![5-way tact switch][1]][1]

After much experimentation, I found that the switch will start working if I add a 14.7k resistor between the switch and ground. The Due's internal pullups still had to be activated, otherwise it seemed the switch was firing constantly. When I used a 10k resistor, the center button on the switch wasn't working. And when I used 20k and higher resistors, many of the buttons weren't working.

I posted this as an answer because the switch is finally working the way I want it to. But I'm still curious to know if anyone has a reason why there would be a necessity to have a 14.7k resistor on the ground of this switch in order to make it work with the Due. Note that I don't have anything connected to the VCC of the switch (though I have experimented with it before).

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


body:
I think I can explain this. You have set up a rather complex (and incorrectly wired) network of resistors. Your switch has pull-up resistors, clearly connected together, and then to the "+" pin. The other side of the switches would go to ground.

> Note that I don't have anything connected to the VCC of the switch ...

Right, so your setup looks like this:

[![Pull-up resistors][1]][1]

Now with no switch pressed they will all read high due to the Due's pull-up (which by the way is around 100 k compared to the Mega's 50 k.)

Now you press a switch. The naturally grounds that switch so it reads LOW. However it also pulls down neighbouring switches through the 10 k resistor network. So each switch now is in the middle of a voltage divider. There is 20 k going to ground and a couple of 100 k going to Vcc, like this:

[![Multiple presses][2]][2]

This voltage divider would be enough for that pin to register as LOW, and indeed that would be repeated for each pin.

Adding your carefully calculated resistor between the "-" pin and ground is just changing the voltages a bit.

The correct solution is to connect the "+" pin to Vcc so that it acts as a proper pull-up. And get rid of that resistor in series with ground.

---

It probably worked on the Mega because of the different pull-up resistance when you activated the internal pull-up which would have changed the calculations for the voltage divider.

I've worked out what I think the voltages will be. Note that the supposedly open switches will actually have 1.1 V on them, which as far as I can tell from the datasheet is in the "undefined" territory between LOW (max 0.99 V) and HIGH (minimum 2.31 V).

Reasoning: You can effectively consider that the 4 open switches have 4 x 110 k between them and 3.3 V in parallel. In other words, 27.5 k. With a voltage divider now between that and the 10 k to ground, you have:

    10 / (10 + 27.5) * 3.3 = 880 mV

So, there will be 880 mV on the common point (which is "+" on the board).

Now for each switch you have a voltage divider of:

    10 / 110 * (3.3 - 0.880) = 220 mV

Add to that the 880 mV at the common point and we have:

    0.88 + 0.22 = 1.10 V

  [1]: https://i.stack.imgur.com/ZDmo9.png
  [2]: https://i.stack.imgur.com/nZNKC.png


message:
WiFi module ESP8266 + Arduino Uno

I'm trying to connect a WiFi module, ESP8266-01 to an Arduino Uno. But, as I've understood, this module will only work with 3.3 V. Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

My questions are:

* Does anyone know if there already exists a tutorial that describes the way this WiFi module can be connected to an Arduino Uno?
* For a simple server, would I need to use several voltage regulators (since there are quite many pins)?
* Since Rx is the receiver, it would not need a voltage regulator because that pin can handle up to 5 volts?
* Is there any need for an external power source, such as a cell?

body:
> Since all of the data pins use 5 V, one of the solutions is to use a voltage regulator, such as LM2596.

You do not want a voltage regulator you need a **level shifter**.

You can buy them cheaply or make them up with a transistor or MOSFET.

I gather the ESP8266 has a Tx (transmit) **to** the Arduino. You probably don't need to level-shift that, as the Arduino Uno will interpret 3V upwards as a HIGH. For the Rx (receive) **from** the Arduino you need to level-shift the data pin (possibly a voltage-divider might work) since the 5V from the Arduino needs to be converted down to 3.3V.

The ESP8266 Vcc and CH_PD can go to the Arduino **3.3V** pin.

Disclaimer - I haven't done this, I am summarizing what I read on various web pages. Read some of the answers on the pages you get when you do a Google search for more details.

---

## References

* [Voltage divider - Wikipedia](https://en.wikipedia.org/wiki/Voltage_divider)
* [Level shifter - StackExchange](https://electronics.stackexchange.com/questions/42727/what-is-the-difference-between-level-shifter-voltage-regulator-and-dc-dc-conver)
* [SparkFun Logic Level Converter - Bi-Directional](https://www.sparkfun.com/products/12009)
* [4-channel I2C-safe Bi-directional Logic Level Converter - Adafruit](https://www.adafruit.com/products/757)
* [Bi-directional level shifter for I²C-bus and other systems - PDF](https://www.adafruit.com/datasheets/an97055.pdf)
* [ESP8266 Community Forum](http://www.esp8266.com/viewforum.php?f=25)


body:
Check out the ESP-Link project over on Github. It has a pretty decent implementation of communicating with an Arduino via UART. As mentioned in another comment you will need a 5v-3.3v level shifter. But if you want to make things a little less messy you could just get a 3.3v Arduino mini for probably around the same price as the level shifter. Esp-link is built with the esp-open-sdk so you will have to spend some time setting up the toolchain if you haven't already.

I'm working on a project right now using a Moteino + ESP-12E and it's working great. However I'm planning on porting the RFM69 library and removing the Arduino portion completely. I would recommend doing the same if you can. The link below shows how to use the ESP with a port-expander (using SPI) so you can have more GPIO with the ESP.
https://github.com/MetalPhreak/ESP8266_MCP23S17


body:
If you want a simplest solution, **you can just connect your 5V pin of Arduino to the 3.3V external power supply**. It will work just fine on 3.3V and all of its GPIO pins will be 3.3V too.

**Warning:** You must be careful because if you plug your Arduino to the USB wire, you will instantly get the 5V on all the pins, so you will burn your ESP. So you will have to disconnect ESP during programming.

The easiest (and safe) way for me in this scenario is to just use a standalone ATMEGA328P-PU chip on a breadboard and connect it manually. You just have to plug in 4 capacitors, a 16M oscillator and a resistor and upload sketch using a programmer (like USBasp) and "Upload using a programmer" button. You can then safely run everything on 3.3V because the programmer has a jumper and can work on 3.3V too and you don't have to use ANY level shifters and or voltage dividers. In my case they were not even working (I don't know why). You connect such "environment" once on a breadboard and you can safely work with it later. Let me know if you need more info on this.

**Warning:** If you work with SPI bus (MISO, MOSI, SCK), like an SD card reader for example, then you must secure the SPI lines of the device (card reader) with resistors, because you may also burn your chip if 2 opposite signals are directed to the same line by 2 separate devices. I've burned my 328P like this once.

**Warning:** Don't use a programmer for supplying power to your circuit. It can work for programming, but when your ESP starts connecting to WiFi it will require much more power than the programmer can provide! In best scenario it will just not work and hang up or reset.


message:
Do I need to solder wires to my tilt sensor?

[![enter image description here][1]][1]I am using the Arduino Starter Kit and I am on project 8. The picture of the sketch in the book is not clear because it shows the tilt sensor seemingly resting sideways, which is not the way that it connects. If you insert the pins into the board the sensor will always be standing and there will be no way to turn it. I was thinking you might have to solder wires to the pins. Does anyone know?
-Thanks
Edit: Perhaps this picture will help:

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

body:
I don't have the starter kit but I have a tilt ball sensor:

[![Tilt ball sensor][1]][1]

My guess is that there is a ball inside it, and it connects the wires, like this:

[![Tilt ball sensor design][2]][2]

This is confirmed by measurement.

---

I suggest you either solder wires to it, or push the wires into your breadboard. As you can imagine from the diagram, the contacts will be closed if the ball (or mercury or whatever it is) is downwards. In other words, if the leads are facing down. As you tilt it, the ball will move away from the two wires, breaking the connection. You may have to tilt it quite a lot for this to happen.

---

*(Edited to add)*

I see from the [Arduino Starter Kit page](https://www.arduino.cc/en/Main/ArduinoStarterKit) that the tilt sensor works like this:

[![Arduino Starter Kit tilt sensor][3]][3]

This shows that my guess was pretty accurate. :)

There are four pins, so I imagine that the ball would connect four of them if held upright, and various combinations if tilted forwards or sideways.

---

> If you insert the pins into the board the sensor will always be standing and there will be no way to turn it.

Well, you could tilt the breadboard, yes?

However I agree that if you want to tilt just the sensor, then soldering wires to it would seem quite sensible.

I think the starter kit is there to show you the concepts. There is nothing stopping you tilting the entire breadboard to see how it works. In practice you would mount the sensor in such a way that it activated when moved from position A to position B, whatever that is.

  [1]: https://i.stack.imgur.com/oEmYQ.jpg
  [2]: https://i.stack.imgur.com/VjBDl.png
  [3]: https://i.stack.imgur.com/ghQnl.png


body: I have the starter kit with the exact same tilt sensor. In my experience it does sorta work. In that you can plug it in the breadboard and it will sit snugly and have a stable connection, but two and two of the connectors will be shorted so you can't use all four independently. And it will respond to tilting the board, at least in one specific direction. So it does work without soldering, at least for learning/demonstration purposes.


message:
mcufriend 2.4 tft mega 2560

Please help me w/ my 2.4 mcufriend TFT on my Mega2560.

I've followed any instructions I can find, including:

https://arduino.stackexchange.com/questions/1138/2-4-tft-lcd-shield-isnt-working-on-arduino-mega/4537#4537

I still get a show white screen. I wonder if my TFT is different or is it broken? Mine looks like this:

[![TFT image][1]][1]

I did run the example code from SWtft. I got this output on serial:

    TFT LCD test

    LCD driver chip: 6TFT LCD test
    LCD driver chip: 6767
    Benchmark                Time (microseconds)
    Screen fill              1786024
    Text                     413024
    Lines                    2569212
    Horiz/Vert Lines         226196
    Rectangles (outline)     176972
    Rectangles (filled)      4682244
    Circles (filled)         2703104
    Circles (outline)        1119540
    Triangles (outline)      815028
    Triangles (filled)       2867288
    Rounded rects (outline)  469268
    Rounded rects (filled)   5733992
    Done!

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

body:
I have one of these TFT LCD shields, but mine is a ILI9335. It has taken me nearly 2 weeks to find a working Library and code for my 9335 driver and I am now setting about creating sketches based around my working Library.
  Library - TFTLCD using st7783 controller
Unfortunately most sellers of these shields (excluding good reputable companies) do not adivise of which Driver is onboard the shield and it becomes difficult to locate a working Library for the driver of the purchased shield.

ALSO, check that the Libraries you have are working for your version of Arduino IDE. Some of my libraries would not compile in v1.0.5 but will in v1.6.3 (and vice versa)
If there is no Library specific to your 6767 Driver (and I must say I have not seen one in my searches for the 9335 Driver) then you may have to download as many different Libraries to locate a sketch that works for yours.
Once you have a working Library then it is just a matter of modifying it for your purposes.

Good luck in finding a working solution for your shield.

Lance..


body:
There are several of these boards on sale (mostly from China).

The following IDs of the different chips are taken from a file named `mcufriend_kbv_2_8.txt` from an archive named `Mcufriend_kbv_2.8.zip` which provides a whole library(supposely an UTFT fork) supporting these PCBs. [Here in the Arduino.cc forum](https://forum.arduino.cc/index.php?topic=366304.0) is one of the download links.

    ----- HX8347-A 240x320  ID=0x8347 new Untested
    ILI9320  240x320  ID=0x9320
    ILI9325  240x320  ID=0x9325
    ILI9327  240x400  ID=0x9327
    ILI9329  240x320  ID=0x9329
    ILI9335  240x320  ID=0x9335
    ILI9341  240x320  ID=0x9341
    ILI9481  320x480  ID=0x9481
    ILI9486  320x480  ID=0x9486
    ILI9488  320x480  ID=0x9488
    LGDP4535 240x320  ID=0x4535
    RM68090  240x320  ID=0x6809
    R61505V  240x320  ID=0xB505
    R61505W  240x320  ID=0xC505 new Untested
    R61509V  240x400  ID=0xB509
    ----- S6D0139  240x320  ID=0x0139 removed due to lack of tester
    S6D0154  240x320  ID=0x0154
    SPFD5408 240x320  ID=0x5408
    ----- SSD1963  800x480  ID=0x1963 new Untested
    SSD1289  240x320  ID=0x1289
    ST7781   240x320  ID=0x7783
    ST7789V  240x320  ID=0x7789

A white screen is the result of choosing the wrong chip. Choose the right one (by ID) and it will work.


body:
 1. You need to modify these #define parameters of TouchScreen() from

        #define YP A3
        #define XM A2
        #define YM 9
        #define XP 8

    to

        #define YP A2
        #define XM A1
        #define YM 6
        #define XP 7

 2. Only insert the 4th line if (identifier == 0x6767) identifier = 0x7575;
into setup() as below

............

      tft.reset();

      uint16_t identifier = tft.readID();

      if(identifier==0x0101)
          identifier=0x9341;

      if (identifier == 0x6767)
          identifier = 0x7575;

      if(identifier == 0x9325) {

        Serial.println("Found ILI9325 LCD driver");

      } else if(identifier == 0x4535) {

        Serial.println("Found LGDP4535 LCD driver");

      }else if(identifier == 0x9328) {

        Serial.println("Found ILI9328 LCD driver");

      } else if(identifier == 0x7575) {

        Serial.println("Found HX8347G LCD driver");

      } else if(identifier == 0x9341) {

        Serial.println("Found ILI9341 LCD driver");

      } else if(identifier == 0x8357) {

        Serial.println("Found HX8357D LCD driver");

      } else {

        Serial.print("Unknown LCD driver chip: ");

        Serial.println(identifier, HEX);

        Serial.println("If using the Adafruit 2.4\" TFT Arduino shield, the line:");

        Serial.println("  #define USE_ADAFRUIT_SHIELD_PINOUT");

        Serial.println("should appear in the library header (Adafruit_TFT.h).");

        Serial.println("If using the breakout board, it should NOT be #defined!");

        Serial.println("Also if using the breakout, double-check that all wiring");

        Serial.println("matches the tutorial.");

        return;

      }

3. Try it.


message:
Why should I put a 10K resistor with an LDR?

I am wondering why should I put a 10K resistor with an LDR.

If I put a "stronger" resistor with another resistor (in this case the LDR), I'd get a lower voltage, and then I'd, too, get a lower value in the `analogRead()`. I'd like to know in what I'm doing wrong. Can someone help me?

body:
LDRs themselves come in a considerable range of resistances. Search LDR specs and you will see what I mean. For example, from eBay I found one:

> Bright Resistance(10Lux)(KΩ):20-230
>
> Dark Resistance: 2 MΩ

This particular one, for example, seems to range from around 20k to 2M ohms. A reasonable series resistor would then seem to be somewhere in the middle of that range, otherwise all your readings would be skewed at one end of the scale.

For example, in this case if you used 10k and the LDR had 20 k resistance in very bright light, then the voltage would be 3.33 V

    20000 / (20000 + 10000) * 5 = 3.33 V

Then if it got slightly darker and the LDR was 230 k, you would get:

    230000 / (230000 + 10000) * 5 = 4.79 V

And if it was really dark you would get:

    2000000 / (2000000 + 10000) * 5 = 4.98 V

You can see from those figures that you will never get a reading less than 3.33 V with this particular LDR and a 10k resistor. Thus a higher value resistor would give you a better range of readings.

However this totally depends on what resistance your particular LDR has.


body:
After you check the LDR specification you can use an online Ohm's Law calculator and calculate the resistance you need.  Be sure the power rating of the resistor is greater then what is shown.  Less it will smoke more is good but size is also important.

Gil


message:
Any disadvantages on using Particle Photon over an Arduino?

It seems to me like Photon is 'winning' on the price front and ease of programming and of course the cheap wifi connection.

I realize the cloud portion (even the local cloud server) could be considered a disadvantage, but what about things like ability to drive dc/stepper motors or some exotic sensor? Perhaps not enough analog and/or digital pins? etc..

One disadvantage I can think of is the lack of resources whereas the Arduino has a ton of references online with working with all kinds of motors and sensors.

body:
**Photon advantages:**

The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.

A photon  about 1/4 the size of an Arduino UNO

Photon is much cheaper than arduinos

**Arduino UNO advantages:**

Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt

Arduino has many resources while Photons don't since Photons are fairly new

Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)

UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital

UNOs have female pins, so no breadboards are necessary for small, simple projects.
Photons have male pins, and they need to be plugged into a breadboard or soldered.

*Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!*


message:
SoftwareSerial returns garbage when powered externally

I'm currently working on a project with the ESP8266 and Arduino Nano, and when I power the device via USB they talk to each other via SoftwareSerial just fine. I use the Arduino IDE Serial Monitor to monitor this communication. But when I power it with a 15 V wall wart to Vin it returns mostly garbage, again I can tell this with the Arduino IDE Serial Monitor (I know I shouldn't connect two power supplies at a time). When powered over 5 V USB everything is great. Why would I have a problem only when connected to an external power supply?

body: If you check the specifications they stat 12VDC is the max.  Your on board regulator is probably very hot and either shutting down or allowing the voltage to sag.  You can get a 9V wall Wart for under $5.  the 9V will keep the on-board regulator much cooler and add reliability.


message:
how much current does Arduino Nano draw when only using 8 digital pins?

I want to connect an Arduino Nano to an Intel Minnowboard Max (it's like a Raspberry Pi). I know Arduino can draw up to 500 mA current through the USB connection. Since I already need the USB to communicate the Arduino with the Minnowboard, it would be nice to not power the Arduino separately as well. However, I wouldn't want the current the Arduino draws from the Minnowboard to overheat Minnowboard's 2.5A 12V power supply.
I only have 8 buttons connected to the digital pins of the Arduino Nano. Nano sends the state of the buttons to the Minnowboard via USB (serial). How much current is Arduino drawing in this case?

body:
I would guess around 50 mA, to power the processor and the USB converter. I notice that [this question](https://electronics.stackexchange.com/questions/68938/power-consumption-of-arduino-nano-current-draw-low-power) suggests more like 20 mA.

To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.


message:
My mega only works on 1.0.1 IDE

My mega usb/serial adapter died some time ago, so I bought an external FTDI programer wich I got working on 1.0.1 IDE. I can load any program to the mega, even complex led matrix driver I wrote myself so the ATmega works fine and the external FTDI board does too. Strangely enough I if I want to update the IDE (tried once on 1.0.5 and yesterday downloaded 1.6.5) I get an

     avrdude: stk500v2_getsync(): timeout communicating with programmer

When this problem occurs, I see that the programmer board recieves something (it has Rx and Tx LED's) the Mega resets but never sends any data back, which does happen on 1.0.1 IDE.
This happens on my pc, and on a laptop son no pc related problems.
I'd keep using this version but now I got an OLED display I want to drive (SSD1306 from waveshare) but I can't compile u8glib on 1.0.1 but I can on 1.6.5, however I can't get a simple blink example to upload with this IDE.

I suspect the DTR pin (reset pin) is handled differently and that makes the mega stay resetting until it times out.
What can be the problem here? How can I get more info from the console to solve this?

body:
You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.

The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.


message:
FTDI breakout connection

I have been successfully programming UNO boards. I wanted to transfer the project to a Pro Mini. I am using a FTDI breakout. It wouldn't show the device port. I found the device driver I was using was supplied by MatterControl. So I updated the driver from FTDI.

When I connected it I see the port available, but cannot program it. I get

    not in sync: resp=0x01 avrdude: stk500_recv(): programmer is not responding

I checked in the device manager and see "USB Serial Port (COM5)" and properties shows "This device is working properly." the provider is FTDI.

body:
This error can come from a number of sources and you'll find this is a common question on arduino.stackexchange. The most likely reasons are:

- If the board wasn't reset, the bootloader didn't run;
- Rx & Tx connections between the FTDI and the board may be reversed;
- Avrdude may be using a different baud rate than the bootloader expects. 57600 baud used to be standard for Atmega328p bootloaders. More recent firmware is using 115200 baud. I've been bitten by this one regularly; my chips have older bootloaders and one of my PCs has a very recent Arduino IDE.


body:
The problem was resolved by changing "set RTS on close" in the device manager properties as stated here
https://electronics.stackexchange.com/a/87955/80377


body:
I made the board using the great tutorial by Nick Gammon  for the minimum Arduino board. I got the boot loader to load using Nick's tutorial and then spent a few evenings trying to use FTDI to upload sketches but could not get it to work. In the end, using various bits of inforamtion I found on the web, I made sure the reset signal was coming from the the FTDI (going to low) and then checked the settings of the FTDI and tried to make some changes. I found that the settings in my photos work. Mainly the bit rate 115200 and the latency (m/secs) time to 5 m/secs. The wires from FTDI starting from the top in looking at photo - brown (ground to ground), red (vcc to vcc) orange (tx to rx), Yellow (rx to tx), the other separate orange (was better I used another colour!) is from RTS to reset.
I selected Arduino uno as board and (in my case) COM 10. For me it ow works. I don't know if I would make many of these boars though because of the time and effort. However, itwas a good expeiance and I learnt a great deal. Particularly from Nick Gammon. Thanks Nick!

[![connections][1]][1]

[![settings][2]][2]

  [1]: https://i.stack.imgur.com/SiaRL.jpg
  [2]: https://i.stack.imgur.com/2KXme.jpg


message:
What Driver IC to use for 40v 2amp DC motor?

I am using a 40v 2amp 3300rpm DC motor for my motor control project via arduino. But i don't know what driver ic to use for driving the motor.any help would be appreciated..

body:
I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor.  By far the easiest way is to simply use a N-Channel logic level MOSFET.  Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground.  The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino.  The low side of the 40V power supply must be connected to the source of the MOSFET.

Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).

Carefully check your wiring; if it is ok you are ready to test it.  The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected.  The anode side connects to the drain of the MOSFET.  When the motor is turned on the LED will light, if it does not reverse polarity of the LED.  As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected.  Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.

1. This helps dampen oscillations
2. Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.
3. For the MOSFET you need at least 60V with a 10A rating.  This should work with a small heat sink.  If you go to a higher amp rating on the MOSFET it will operate cooler.

Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger)
The other side of the resistor goes to the gate of the MOSFET.
Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together.  The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V.  The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.

Good Luck,
Gil


message:
How can I do this sentence show me in arduino

."WARNING: Category 'USB' in library Mouse/keyboard is not valid.Setting to 'Uncategorized'

body:
Your question is unclear.

Note that [Mouse and Keyboard libraries](https://www.arduino.cc/en/Reference/MouseKeyboard) are suitable for use with Arduino Due and Zero boards, or with 32u4-based boards like Arduino Leonardo or Micro.   They are not relevant when using an Uno.


message:
Bluetooth distorts analog read?

I'm working to make a simple pedometer with Arduino, and after managing to find an algorithm that correctly finds the steps, I added a bluetooth extension (the overly popular and cheap JY-MCU) to check the steps via bluetooth.

I am facing a strange issue, though: when the bluetooth device is powered and waiting for a connection (red led blinking) the analog read function that reads data from the accelerometer goes crazy (thus the pedometer finds a step each second or so). When the bluetooth is powered down or connected to a device such as a mobile phone this doesn't happen.

Did anyone have this problem before? What could be the issue? My setup is easy, you can see it on the image.

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

I had other sensors as well but since the problem stays even when there are only those two connected I posted the bare minimum setup.
At first I thought I could use some kind of pull-ups to stabilise the signal, but I really have no idea on where to tie them and if they can really be helpful at all...

Any help is appreciated.

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

body:
You can try decoupling the power for the bluetooth:

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

The resistor value should be tiny - 10Ω is a good value to use - don't go much higher than that.  The capacitor should be nice and big - I have shown 100µF, but bigger is better - whatever you have that's nice and big.  (Make sure you wire it the right way round - check which pin is marked as -)  You might also want to add a small capacitor (say 100nF) in parallel with the large one.

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


message:
ATMega328 + Bluefruit LE stops working soon after power on (not consistently)

Now I am https://arduino.stackexchange.com/questions/16498/running-arduino-code-for-bluefruit-le-on-bare-atmega328 with 8MHz internal clock, with Bluefruit connected, pin 0 and 1 RX/TX unused, and AT42QT1011-based capsense circuits (logical input to pins 1, 2, 3).

There appeared one problem: when I try to switch the device ON (with 4.5 V batteries, but the same with 5 V USB power), it happens only after three or more attempts. Each time "loop" stops after a second of what appears to be correct operation. For example, if I touch one of the capsensors on the first second of operation, and LED is on, it stays ON, which means, the "loop" is not run.

I have tried to put back the Serial (it was in use in the original echoDemo example), tried to put pollACI after digitalWrite to LED pins. See pin assignments defined in the sketch, those were re-checked with actual circuit.

Measured power supply current and voltage - there were no significant changes in it, even if both LEDs were on. BLE module at startup or while transmitting, was not causing any brownouts. In addition, checked input current and voltage with oscilloscope, and there were no anomalies as well.

NB, this is atmega328, without "p", so for the record I am using 0x07 efuse, 0xE2 lfuse and 0xD9 hfuse.

Also, if the device starts up, it will work fine for at least an hour.

What could be other reasons for such random early failure? (in average, about four attempts to switch on, sometimes starts even on first, second time)

The sketch in question:

    /*********************************************************************
    This is an example for our nRF8001 Bluetooth Low Energy Breakout

      Pick one up today in the adafruit shop!
      ------> http://www.adafruit.com/products/1697

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

    Written by Kevin Townsend/KTOWN  for Adafruit Industries.
    MIT license, check LICENSE for more information
    All text above, and the splash screen below must be included in any redistribution
    *********************************************************************/

    //#define F_CPU 8000000

    #include <SPI.h>
    #include "Adafruit_BLE_UART.h"

    // Connect CLK/MISO/MOSI to hardware SPI
    // e.g. On UNO & compatible: CLK = 13, MISO = 12, MOSI = 11
    #define ADAFRUITBLE_REQ 10
    #define ADAFRUITBLE_RDY 2     // This should be an interrupt pin, on Uno thats #2 or #3
    #define ADAFRUITBLE_RST 7

    #define REDLED 8
    #define BLUELED 9
    #define LEFTPAD A2
    #define RIGHTPAD A3
    #define BADPAD A1

    Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

    unsigned int leftcnt, rightcnt;

    void setup(void)
    {
      pinMode(REDLED, OUTPUT);
      pinMode(BLUELED, OUTPUT);
      pinMode(LEFTPAD, INPUT_PULLUP);
      pinMode(RIGHTPAD, INPUT_PULLUP);
      pinMode(BADPAD, INPUT_PULLUP);
      digitalWrite(BLUELED, LOW);
      digitalWrite(REDLED, LOW);
      delay(300);
      BTLEserial.setDeviceName("MYUART"); /* 7 characters max! */
      BTLEserial.begin();
      digitalWrite(REDLED, HIGH);
      delay(300);
      digitalWrite(BLUELED, HIGH);
      leftcnt = 0;
      rightcnt = 0;
    }

    aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

    void loop()
    {
      BTLEserial.pollACI();

      if (digitalRead(LEFTPAD)) {
        leftcnt++;
        digitalWrite(BLUELED, LOW);
      } else {
        leftcnt = 0;
        digitalWrite(BLUELED, HIGH);
      }
      if (digitalRead(RIGHTPAD)) {
        rightcnt++;
        digitalWrite(REDLED, LOW);
      } else {
        rightcnt = 0;
        digitalWrite(REDLED, HIGH);
      }

      aci_evt_opcode_t status = BTLEserial.getState();

      if (status == ACI_EVT_CONNECTED) {
        boolean inp = false;
        while (BTLEserial.available()) {
          char c = BTLEserial.read();
          inp = true;
        }
        if (inp) {
          if (leftcnt > 5) {
            BTLEserial.print("LEFT");
          }
          if (rightcnt > 5) {
            BTLEserial.print("RIGHT");
          }
          if (digitalRead(BADPAD)) {
            BTLEserial.print("CENTRAL");
          }
        }
      }
    }

**UPDATE**: MCU's reset pin is pulled-up by a resistor. Bluefruit's RST connected to PD7 on atmega328 (also known as arduino digital pin 7). Also, 3.3 uF capacitor on the power lines near MCU's IC. (there are more near capsense circuits).

When I disconnect Bluefruit's power, the rest of the circuit (LEDs showing cap sensors state) works without failures after startup. So it looks like under some circumstances, control never leaves BLE code to return to the loop?

**UPDATE 2**: Found long list of reset causes (not sure yet whether relevant here): [Arduino/AVR ATmega microcontroller, random resets, jumps or variable/data corruption ...][1]

**UPDATE 3**: Added two 100nF bypass capacitors near GND / VCC pins on both sides. The problem is still there.

**UPDATE 4**: Performed all kinds of experiments, placing BLE module's power lines in different places, with different capacitors. Only in the case of separate power (common ground) the problems were different (but may be due to different times of turning module and MCU on).

**UPDATE 5**: May be relevant or not, but when I run MCU on 1MHz (8 MHz internal clock, divided by 8 - lfuse 0x62), success rate is better than 70%. The speed seem to be enough for my application, but of course near 100% turn-on success should be achieved.

**MAY BE IMPORTANT**: I have added watchdog to sketch (thanks to the "Make: Sensors" book by Karvinen & Karvinen, Valtokari):

      WDTCSR |= (1<<WDCE) | (1<<WDE);
      WDTCSR = 1<<WDP0 | 1<<WDP3;
      WDTCSR |= _BV(WDIE);
      MCUSR &= ~( 1 << WDRF);

And in the respective ISR red led is turned on or off once in about 8 seconds or so. And ISR code works (thus, MCU works all the time too, right?), even though the "loop" runs no longer.

Can this still be attributed to trouble with power or is it more likely control flow is stuck somewhere in the BLE library?

**UPDATE**: Well... As advised here, while trying out Serial (via microbot USB adapter), I understood, that it does not work reliably (if at all, sometimes eats characters, prints garbage, ...). Not sure whether SPI is sensitive to clock accuracy, but if it is, it may be the problem. Also, the circuit turns on always when powered from USB3 port 5V.

  [1]: https://stackoverflow.com/questions/23377948/arduino-avr-atmega-microcontroller-random-resets-jumps-or-variable-data-corrup

body:
The main problem cause was inaccurate internal clock. As soon, as external 8MHz crystal has been attached to XTAL pins (with a pair of 22pF capacitors to GND), problems with turning the board on disappeared.

Also, I found

    while(1);

loop in the Adafruit's nRF8001 library, which runs whenever problems with the Bluefruit LE board are encountered. That is possibly why interrupts worked fine, but the whole MCU never returned to the main loop.


message:
Why PJ0 and PJ1 are not reporting as PCINT pins

When the sketch shown at end-of-question is compiled and uploaded to an Arduino board, it is supposed to Serial-print a list of available digital pins, showing for each pin whether it supports PWM or PCINT.  (For the latter items, it should indicate whether it has timer-supported PWM, and whether it can cause a hardware-supported pin-change-interrupt.)  For example, for an ATmega-2560 board, the program's output includes lines like

      Pin# Port Mask  PWM  PCINT
      11   PB5  0x20  PWM  PCINT5  PCINT0_vect
      46   PL3  0x08  PWM
      52   PB1  0x02       PCINT1  PCINT0_vect

Using arduino 1.6.3 on my Ubuntu 14.04 system with an ATmega-2560 board, the program's output for pins 14 and 15 is:

      14   PJ1  0x02
      15   PJ0  0x01

As I understand it, those pins should be shown⁽¹⁾ as supporting PCINT9 and PCINT10, with vector PCINT1_vect, but the program doesn't report them as such.  What is this problem due to?

⁽¹⁾See, for example, table 13.3.9, Alternate Functions of Port J, in doc2549.pdf, the spec sheet for ATmega640/1280/1281/2560/2561.  Also see [Why is my interrupt code not working?](https://arduino.stackexchange.com/q/9481).

Sketch pinsList.ino:

    /*  pinsList -- JW, 4 October 2015 --
     *
     *  Displays a list of Arduino pin numbers for current kind of Arduino
     *  board, along with port codes, pin-change-interrupt numbers, and
     *  pin-change-interrupt vector numbers.
     *
     *  Here are two examples of output lines for pin 11, the first for an
     *  Uno, the second for a Mega:
     *
     *        11   PB3   0x04   PWM   PCINT3  PCINT0_vect
     *        11   PB5   0x20   PWM   PCINT5  PCINT0_vect
     */
    //-----------------------------------------------------------
    // Given a value with 1 bit set, return bit #.  Else return 9.
    byte getBitfromBV (byte m) {
      byte b=0, v=1;
      while (v) {
        if (m==v)
          return b;
        ++b; v <<= 1;
      }
      return 9;
    }
    //-----------------------------------------------------------
    void processPinNumber(byte pin) {
      char buffi[128];  // We create text-to-write in buffi
      byte nbuff=0;   // #chars used in buffi
      byte nPCICR;   // 0, 1, or 2 for mask-register #
      byte bitInByte;  // 0 to 7 for bit in I/O mask
      byte pinPort;   // pin's port #, in range 1 to 12
      byte PCInum;   // PCINT# if pin is a PCI pin
      char *portLet = "?ABCDEFGHIJKL";

      if (pin >= NUM_DIGITAL_PINS) return;

      pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12
      bitInByte = getBitfromBV(digitalPinToBitMask(pin));

      nbuff = snprintf(buffi, sizeof(buffi), "  -   P%c%d  0xx",
         pin, portLet[pinPort], bitInByte, 1<<bitInByte);

      // Indicate if it's a PWM pin
      if (digitalPinHasPWM(pin)) {
        nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "  PWM");
      } else {
        nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, "     ");
      }

      // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector #
      if (digitalPinToPCICR(pin)) {   // Is it a PCint pin?
        nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit#
        PCInum = nPCICR*8 + bitInByte;
        nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff,
           "  PCINT%d  PCINT%d_vect",  PCInum,  nPCICR);
      }
      Serial.println(buffi);
    }
    void setup() {
      delay(50);
      Serial.begin(115200);
      delay(50);
      while (!Serial) ;             // wait for serial stream to connect
      Serial.println("\nPin#  Port  Mask  PWM   PCINT");
      for (byte p=0; p<NUM_DIGITAL_PINS; ++p)
        processPinNumber(p);
      Serial.end();
    }

    void loop() {
    }

body:
It's because of this entry in the board's pins_arduino.h file:

    #define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                      (((p) >= 50) && ((p) <= 53)) || \
                                      (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Basically your program isn't reporting what the pins can do - it's reporting *what the Arduino system has been programmed to support for those pins*.  Basically it hasn't been programmed to support PCINT on those pins.


body:
Majenko was *very close* but seems to have missed the explanatory comment from the source code:

    // (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
    // Pins: 10, 11, 12, 13,  50, 51, 52, 53,  62, 63, 64, 65, 66, 67, 68, 69

    #define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                      (((p) >= 50) && ((p) <= 53)) || \
                                      (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.

As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file [in commit f179794][1]  in response to [issue 490][2]:

> The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins.  We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.

Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins_arduino.h, but rather moved code **originally written as part of the software serial library** to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes).  It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...

It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless.  But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX & TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.

Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.

  [1]: https://github.com/arduino/Arduino/commit/f179794a45c33edcb48c493bc03fb0e39dba11db
  [2]: http://code.google.com/p/arduino/issues/detail?id=490