body:
I'm trying to read either high or low from a pressure switch, I do have a pulldown resistor attached but even if I plug in a wire with nothing on it i get a false high. I've changed pins, tried adding `INPUT_PULLUP` to the program but it it reads false.

The code i'm using is:

    const int mainPump = 2;
    const int prePump = 3;
    const int idleValve = 4;
    const int chemTankLow = 5;
    const int chemTankHigh = 6;
    int pressure = 8; //7 originally removed const
    const int chemValve = A7;
    const int mem2 = A6;
    const int mem3 = A5;
    const int mem4 = A4;
    const int mem5 = A3;
    int tankLow = 0;
    int tankHigh = 0;
    int pressureFault = 0;
    int lpe = 0;
    int maxlpe = 2;
    unsigned long timer[10]; //number of timers needed
    byte timerState[10]; //store timers
    int goNoGo = 0;
    int readVoltage = 0;
    int var = 0;

    void setup() {

      pinMode(idleValve, OUTPUT);
      pinMode(prePump, OUTPUT);
      pinMode(mainPump, OUTPUT);
      digitalWrite(mainPump, HIGH);
      pinMode(pressure, INPUT);   //removed _PULLUP after input
      pinMode(chemTankLow, INPUT);
      pinMode(chemTankHigh, INPUT);
      pinMode(chemValve, OUTPUT);
      pinMode(mem2, OUTPUT);
      pinMode(mem3, OUTPUT);
      pinMode(mem4, OUTPUT);
      pinMode(mem5, OUTPUT);

      digitalWrite(mem2, HIGH);
      digitalWrite(mem3, HIGH);
      digitalWrite(mem4, HIGH);
      digitalWrite(mem5, HIGH);
      digitalWrite(chemValve, HIGH);
      digitalWrite(idleValve, HIGH);
      digitalWrite(prePump, HIGH);
      digitalWrite(prePump, HIGH);
      digitalWrite(idleValve, HIGH);
    }
    void loop()
    {

           tankLow = digitalRead(5);
       tankHigh = digitalRead(6);

      if (tankLow == LOW && tankHigh == LOW){ //start day tank refill
       digitalWrite(A7, LOW);
      }
      if (tankLow == HIGH && tankHigh == HIGH){
        digitalWrite(A7, HIGH);
      }
      static int state = 1; // initial state is 1, the "idle" state.
      static unsigned long ts;

      switch (state)
      {
        case 1:
        ts = millis();

      if (delayMilliSeconds(1, 6000)){//600000

      digitalWrite(prePump, LOW);

      goNoGo = digitalRead(mainPump);
      if (goNoGo == LOW) {

        digitalWrite(idleValve, HIGH);
      }
        else {
          digitalWrite(idleValve, LOW);
              digitalWrite(mem2, LOW);
        digitalWrite(mem3, LOW);
        digitalWrite(mem4, LOW);
        digitalWrite(mem5, LOW);
        }

            readVoltage= digitalRead(idleValve);
        if(readVoltage==LOW){

        delay(4000); // wait time motors to stablize
        // read the input on analog pin 0:
        int sensorValue = analogRead(A0);
        // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
        float voltage = sensorValue * (4.83 / 1023.0);

        if (voltage >= 2.00)
        {
          state = 2;
        }

        else {
          delay(56000); //on time for test
        //  if (delayMilliSeconds(2, 51994)){
        digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);

         digitalWrite(idleValve, HIGH);
          digitalWrite(prePump, HIGH);
          digitalWrite(mainPump, HIGH);
        }
        }

    }
    //} for if timer
    break;

        case 2:
           ts = millis();
          digitalWrite(mainPump, LOW);
          digitalWrite(idleValve, HIGH);
           digitalWrite(mem2, HIGH);
            digitalWrite(mem3, HIGH);
            digitalWrite(mem4, HIGH);
            digitalWrite(mem5, HIGH);
            delay(20000);
            state = 3;

            break;

            case 3:

          digitalWrite(mainPump, LOW);
          digitalWrite(idleValve, HIGH);
           digitalWrite(mem2, HIGH);
            digitalWrite(mem3, HIGH);
            digitalWrite(mem4, HIGH);
            digitalWrite(mem5, HIGH);

          pressureFault = digitalRead(pressure);
      if (pressureFault == HIGH){

        state = 4;
      }
       if (millis() - ts > 3600000){
        state = 5;
      }

       break;

       case 4:
       digitalWrite(mainPump, HIGH);
       digitalWrite(prePump, LOW);
       digitalWrite(idleValve, LOW);
          digitalWrite(mem2, LOW);
        digitalWrite(mem3, LOW);
        digitalWrite(mem4, LOW);
        digitalWrite(mem5, LOW);
        delay(3000);
        digitalWrite(mainPump, HIGH);
       digitalWrite(prePump, HIGH);
       digitalWrite(idleValve, HIGH);
          digitalWrite(mem2, HIGH);
        digitalWrite(mem3, HIGH);
        digitalWrite(mem4, HIGH);
        digitalWrite(mem5, HIGH);
        delay(600); //60000
        state = 1;

        break;

        case 5:
        ts = millis();
            digitalWrite(idleValve,LOW);
            digitalWrite(prePump,LOW);
             digitalWrite(mainPump, HIGH);
               delay(60000); //60000 for standard
               digitalWrite(mem2, LOW);
               delay(60000);
               digitalWrite(mem2, HIGH);
               digitalWrite(mem3, LOW);
               delay(60000);
               digitalWrite(mem3, HIGH);
               digitalWrite(mem4, LOW);
               delay(60000);
               digitalWrite(mem4, HIGH);
               digitalWrite(mem5, LOW);
               delay(60000);
               digitalWrite(mem5, HIGH);

               delay(1000);   // leave this time
             digitalWrite(idleValve, HIGH);
             digitalWrite(mainPump, LOW);
           state = 2;
             break;
             default:

             state = 1;

             break;

      } //switch
    } //loop

    int delayMilliSeconds(int timerNumber,unsigned long delaytime){
      unsigned long timeTaken;
      if (timerState[timerNumber]==0){    //If the timer has been reset (which means timer (state ==0) then save millis() to the same number timer,
        timer[timerNumber]=millis();
        timerState[timerNumber]=1;      //now we want mark this timer "not reset" so that next time through it doesn't get changed.
      }
      if (millis()> timer[timerNumber]){
        timeTaken=millis()+1-timer[timerNumber];    //here we see how much time has passed
      }
      else{
        timeTaken=millis()+2+(4294967295-timer[timerNumber]);    //if the timer rolled over (more than 48 days passed)then this line accounts for that
      }
      if (timeTaken>=delaytime) {          //here we make it easy to wrap the code we want to time in an "IF" statement, if not then it isn't and so doesn't get run.
         timerState[timerNumber]=0;  //once enough time has passed the timer is marked reset.
         return 1;                          //if enough time has passed the "IF" statement is true
      }
      else {                               //if enough time has not passed then the "if" statement will not be true.
        return 0;
      }

    }

As for wiring it is as basic as it gets 3.3v pin off the arduino to a pressure switch and then back to the arduino . but i'm not even making it to the switch before i have an issue literally plug in a 3ft wire not connected to anything and it goes to case 4
I've tried setting the code up to go to case 4 if it detects a LOW but hasn't changed my issue.

title: I am having an issue reading a HIGH LOW signal from a pressure switch

Answers: 1

body:
As a hint.  Start by removing the stuff you added an just try to detect a grounding of your input pin (I'm assuming digitalRead(pressure) is the standard read the digital value of a pin and not some funky function you've written)

Use some code like this to test your hard ware

    int    pressure;

    void setup()
    {
        Serial.begin(9600);  //Start a serial monitor to see the results
        pressure = 4;  // Assumes your pressure input is pin 4
                       // change if need be
        pinMode(pressure,INPUT_PULLUP);  //Sets put to input with pullup
        digitalWrite(pressure,HIGH);      //Activates pullup
    }

    void loop()
    {
         if (digitalRead(pressure))
         {
              Serial.println("Pin is High");
         }
         else
         {
              Serial.println("Pin is low");
         }
         delay(1000);
      }

Now compile, upload and activate the serial monitor.  Every second you will get the read of the pin on the monitor.  See if grounding the pin is detected.  If not, you may have popped the port.

BTW.  3 ft of wire will need some filtering and protection.  That will pick up a lot of noise.

Cheers


body:
It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB.

When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...

I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.

I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again!

Does anyone know why it's doing this? What did I see smoking? Is it repairable?

title: Fried two Arduino Nano's but works when powered

Answers: 1

body:
Judging by your list of observations:

* Cannot power through USB
* Can power from external source
* Can program through USB

it is most likely that the power feed from the USB to the +5V rail has been interrupted.  There is only one component in that link - the diode D1 (an MBR0520).  That is rated at an absolute maximum constant forward current of 0.5A and most USB ports these days are capable of providing far more than that.  A short circuit on the +5V to ground would draw considerably more current than that diode can handle and the Magic Smoke™ would escape.

The diode is on the underside of the Micro and close examination may show a small crack in the surface of it.  That is if it's still there.  I have used a similar PIC32 based board with 0.5A rated diodes on it, and a short of the power rail when powered from USB caused the diode to completely vaporise (at least I could find no trace of it afterwards).


body:
I want to make an AIR mouse using Arduino
and accelerometer, for this i used USB to TTL
converter i have done everything successfully
but can anyone tell me how use it in computer.
I mean i don't know how to make computer
application for this mouse. please suggest me
any application for this. And give any idea for
"how can i use Bluetooth for this."

title: is any windows application available for accelerometer based computer mouse

Answers: 1


body:
I have searched the Internet and found the following circuit to use with my phototransistor but it is not working, I can say so because all analog input i get is 1023 even if i have covered it totally, I have include the phototransistor and the diagram can anyone tell why is it not working!
I used this webpage to check my sensor and it works-[I used this page][1]

I have used 10kohm resistor.

![Image of circuit][2]

[This is my phototransistor][3]

![enter image description here][4]

  [1]: https://learn.adafruit.com/ir-sensor/testing-an-ir-sensor
  [2]: https://i.stack.imgur.com/lGika.jpg
  [3]: http://xmghdm.en.ec21.com/IR_LED_Infrared_LED_IR--3179904_3180358.html
  [4]: https://i.stack.imgur.com/JnfIZ.jpg

title: How do I use a 3 legged phototransistor?

Answers: 2

body:
A reasonably generic data sheet is [**HERE**](http://www.datasheetarchive.com/dl/Datasheets-SL3/DSASL0044436.pdf)
That is for an AT156 but yours may be an AT138/HT138 based on an ad some years ago from the same seller when they said they had 10,000 for sale.

Basic information here and more in the data sheet.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/qUQZ2.jpg
  [2]: https://i.stack.imgur.com/iMyu8.jpg

body: First that is not even a photo resistor 2nd you have to put one wire positive and the other negitive and the last one plug it into any other gpio pin


body: I want to make an AIR mouse using Arduino and accelerometer, for this i used USB to TTL converter i have done everything successfully but can anyone tell me how use it in computer. I mean i don't know how to make computer application for this mouse. please suggest me any application for this. And give any idea for "how can i use Bluetooth for this."

title: is any windows application available for accelerometer based computer mouse

Answers: 1

body:
try "remotemouse.exe"
its a open source application you can modify the codes according to your requirement


body:
I'm looking for a common "wireless gadget" with a rotary encoder that can be accessed by an Arduino. Background: I need a portable rotary encoder to create a simple way to control model railway locomotives. The only one I have found so far is a wireless mouse where the scroll wheel can be easily used as rotary encoder.

But they usually are using USB on the PC side which is not that easy to handle by Arduino. Does anybody knows about other common "wireless gadgets"?

title: Common wireless gadget with rotary encoder to connect with Arduino

Answers: 2

body:
That sounds like a candidate for building your own.  It shouldn't be too hard.

There's plenty of low-cost Arduino-compatible wireless modules available.  My choice for this would probably be the nRF24L01 - dirt cheap, reasonable range, well supported.

Attach that to an Arduino Mini or Arduino Nano (for instance) and connect a rotary encoder of your choice.  Write the sketch.

Add another nRF24L01 to your main Arduino to receive whatever you send.

Due to the way the nRF24L01 works you could quite easily have a number of remote modules talking to the Arduino through the same channel.  I'm sure you could think of other things you could do with that wireless channel :)

body:
In addition to @Majenko,

If your device is going to talk to a PC/Laptop (or cellphone!), then HC05 or HC06 bluetooth serial module may be a better fit. You will still need to write software to receive the data, but you won't need another Arduino at the other end.


body:
I am designing a smart (or at least I hope so) onboard bicycle light system. The system will have an Arduino (currently prototyping with UNO) and a subsystem composed of a "panel" of buttons and leds.

This panel should stay at the handlebar, connected by multi-wire cable to the Arduino located elsewhere on the bicycle.

In order to read an arbitrary number of push-buttons, I plan to use CD4021 IC with `shiftIn()` function. And, in order to turn an arbitrary number of leds on and off, I plan to use 74HC595 IC and the `shiftOut()` function.

My doubts are: what should I consider in order to do so?

 1. How many wires should I need to connect an arduino to the panel circuit containing the ICs? I believe it is 8 wires (two for the power, three for shifting in [latch, clock, data], and three for shifting out), right?

 2. Can I use any pin I want? Or is it required to use specific pins?

 3. Is that the "right way" of doing this? Any suggestion or improvement is welcome!

title: Using shiftin() and shiftout() with the same circuit - what to consider?

Answers: 1

body:
I have a post here about using an I2C 16-port port-expander: http://www.gammon.com.au/forum/?id=10945

That would use 4 wires for I2C (power, ground, SDA, SCL) or there is an SPI version which would require an extra wire (power, ground, SCK, MOSI, MISO).

I'm not sure about noise over your cable runs, on a bicycle presumably electrical noise is low, so either one might suit. This is the chip that  Ignacio Vazquez-Abrams mentioned in his comments. Any of the 16 ports can be configured as inputs or outputs as you desire, plus it can raise an interrupt on a change on an input pin.

You might find that the maximum current limits for output may not be adequate for your LEDs (the datasheet says maximum of 25 mA per output pin, plus a maximum of 125 mA for the whole chip). You could work around this with driver transistors on the chip output, but this is more complexity.

There are higher-powered shift registers (eg. TPIC6B595) which can handle more per pin than the 74HC595.

> Can I use any pin I want? Or is it required to use specific pins?

If you want to use I2C there are two specific pins dedicated to the I2C hardware. If you want to use SPI there are dedicated hardware pins as well (different ones) but you can also "bit-bang" SPI if you want.

See:

http://www.gammon.com.au/i2c

http://www.gammon.com.au/spi

>  Is there a through-hole version of that?

All the chips I mention here have through-hole versions.


body:
No matter how I rearrange this, the increment compare always returns false....

I have even taken it out of the if, and put it in its own if:

    int buttonFSM(button *ptrButton)
    {
        int i;
        i = digitalRead(ptrButton->pin);
        switch(ptrButton->buttonState)
        {
        case SW_UP:
            if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
            {
                ptrButton->buttonState = SW_DOWN;
                ptrButton->debounceTics = 0;
                return SW_TRANS_UD;
            }
            ptrButton->debounceTics = 0;
            return SW_UP;
        case SW_DOWN:
            if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up
            {
                ptrButton->buttonState = SW_UP;
                ptrButton->debounceTics = 0;
                return SW_TRANS_DU;
            }
            ptrButton->debounceTics = 0;
            return SW_DOWN;
        }
    }

title: Increment in switch statement not working

Answers: 3

body:
Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC_TICS is set to, but I'm assuming it's > 1.

ptrButton->debounceTics will never be greater than 1 because you always:

        ptrButton->debounceTics = 0;

body:
The error is due to wrong expectations on operators precedence:
++ and -> have the same precedence, so they are evaluated left to right.
See http://en.cppreference.com/w/c/language/operator_precedence .

Overall, the lack of parenthesis makes the readability poor.

The code can be improved by dropping the switch and simply checking that the current value is equal to the previous value through the duration of the sampling period.
Then read the value and decide if it's high or low.

But even this might be a poor choice, because it simply samples the value periodically and can miss changes that are not intercepted by the sampling.

Depending on the application, it might be preferrable (certainly it is more precise) to use interrupts on both edges (rising and falling) and a timeout: reset the timer at every interrupt. If the timer expires undisturbed, use the level read at the last interrupt.

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

      if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
        {
            ptrButton->buttonState = SW_DOWN;
            ptrButton->debounceTics = 0;
            return SW_TRANS_UD;
        }
        ptrButton->debounceTics = 0;

I'm going to agree with user3877595 but explain why, as his/her answer got a downvote.

`DBNC_TICS` has to be > 1, right? Otherwise what is the point?

We want to debounce after "x" ticks, and let's assume that the number of ticks is initially zero.

If `DBNC_TICS` is == 1 then this is always true:

    ++ptrButton->debounceTics == DBNC_TICS

Therefore that test is useless.

If `DBNC_TICS` > 1 then it will not execute the "if" block and execute this instead:

        ptrButton->debounceTics = 0;

So `ptrButton->debounceTics` is back to zero, and we are back to square 1.

Therefore the test will always be false.

> No matter how I rearrange this, the increment compare always returns false....

As stated in the question.


body:
I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing.

I have been using this board for many weeks with no problem and just now I have been getting this error:

    avrdude: stk500_getsync()

And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset.

title: How does the reset button work on the Arduino?

Answers: 1

body:
The reset button does pretty much the same as unplugging the board and plugging it back in.  It restarts your program from the beginning.

The same thing happens when you program the board - the USB interface presses the reset button for you.  That then enters the bootloader for a second or two so it can try and program it.

When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in.  If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

* If you have anything else plugged into the Arduino then unplug it.
* Try powering the Arduino from different power supplies.
* If you have another Arduino or an AVR programmer try re-flashing the bootloader.


body:
I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for `analogRead()`.
https://www.arduino.cc/en/Reference/AnalogRead

I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno,
yields a resolution between readings of: 5 volts / 1024 units or, .0049.

My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?

Shouldn't the analog read be 2^8 or 256?

title: how does an 8-bit AVR do 10-bit analog read?

Answers: 1

body: It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC.  The CPU register size doesn't dictate what it can communicate with, either internally or externally.  The only thing it dictates is how big a number it can cope with at any one time.  Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.


body:
Goodafternoon,

I want to read values form a microphone (Adafruit MAX9814) connected to the Analog port A0 from Arduino and store the values that are incoming inside an array.

After the values are stored in the array, I want to read out the values and store the number that is repeated most time in a variable. Is this possible and how to achieve this?

I came up with the following:

    const int micPin = A0;
    int soundArray[10];

    void setup() {

      Serial.begin(9600);
      pinMode(micPin, INPUT);

    }

    void loop() {

      int micValue = analogRead(micPin);
      Serial.println(micValue, DEC);
      //delay(400);

      for (int i = 0; i > 10; i++) {
        soundArray[i] = micValue;
        Serial.println(soundArray[i]);
      }
      delay(1000);
      Serial.println("End of for loop");

    }

The problem now is that a value of the microphone will be repeated 10 times. So I will receive 10 times the number 234 for example. See image.

This is not what I want. I want to get different numbers in the array of that moment.
![enter image description here][1]

Hope someone can help me out.
Thanks in advance.

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

title: How to store values inside an empty array and get the average integer? [UPDATED QUESTION]

Answers: 2

body:
The error message is correct. You did not define the size of the array.
You have 3 choices:

1. Declare it with a constant length

    int foo[10];

2. Declare it and initalize it

    int foo[] = {0,1,2,3,4,5,6,7,8,9};

3. Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)

    int *foo;
    int size = 10;
    foo = (int*)malloc(size * sizeof(int));
    free(foo);

As reference:
http://www.arduino.cc/en/pmwiki.php?n=Reference/Array

body:
There are three main sorts of "average" used normally in Maths:

* Mean: This is the most common meaning of Average. It is the mathematical average of all the values in the set - the sum of all the values divided by the number of values.
* Mode: This is the "most common" value in a set of values.  For the set {1, 2, 3, 4, 3, 5, 3, 1, 7, 3} the "mode" would be 3 since there are more 3's than any other number.
* Median: This is the middle value of a set of values.  If there are 5 values and they are sorted into ascending order the "median" would be the third (middle) value.

By your comments it sounds like "mode" is what you are after - the most common number in your set of values.

It's quite easy to work out which is the most common number in a set if you are willing to loop through that set enough times.

I have an [Average library](https://github.com/MajenkoLibraries/Average) that can do it for you.  The main part of the `mode()` function of that library looks like this:

    most = _store[0];
    mostcount = 1;
    for(pos = 0; pos < _count; pos++) {
        current = _store[pos];
        currentcount = 0;
        for(inner = pos + 1; inner < _count; inner++) {
            if(_store[inner] == current) {
                currentcount++;
            }
        }
        if(currentcount > mostcount) {
            most = current;
            mostcount = currentcount;
        }
        // If we have less array slices left than the current
        // maximum count, then there is no room left to find
        // a bigger count.  We have finished early and we can
        // go home.
        if(_count - pos < mostcount) {
            break;
        }
    }
    return most;

Basically two loops, one inside the other.  The outer one steps through each number, and the inner one counts the number of times than number appears in the set (actually just from the current outer loop position to the end of the set - no point in counting numbers we've already looked at).  If the count is greater than the current "mode" count then store that as the "mode" count and also store the value as the "mode" value.  Move on to the next number.

To use the Average library it's quite simple:

    const int micPin = A0;

    // We want to be able to store 10 int values here.
    Average <int>sounds(10);

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

    void loop() {
        // Push 10 values into the Average buffer.  Any old values will drop
        // off the bottom.
        for (int i = 0; i < 10; i++) {
            sounds.push(analogRead(micPin));
        }
        Serial.print("Mode value is: ");
        Serial.println(sounds.mode());
        delay(1000);
    }


body:
I bought an [Arduino 9 Axes Motion Shield][1] without looking at the pinout. I'm worried it won't work with my [Adafruit Motor Shield v1][2].

It seems the 9 axes shield uses I2C, a reset pin and several other pins for the TinkerKit Input, Output and TWI connectors. Does anyone have a list of specific ports used by the shield on the Arduino UNO?

It also seems that my Arduino UNO r1 only has the original analog pins for I2C, while the 9 axes shield uses the new pins next to the digital pins.

_update: I asked support from arduino.org on twitter and on their forums, no reply yet and it seems their twitter account has been suspended. Should have bought a Genuino I guess._

  [1]: http://www.arduino.org/products/arduino-9-axes
  [2]: https://www.adafruit.com/products/81

title: Pinout of Arduino 9 Axes Motion Shield

Answers: 1

body:
The I2C pins on the V3 shield are just copies of A4 & A5 - so just run a jumper wire some way.

BTW that Motion shield looks like it only uses 1 interrupt pin in addition to I2C, so you may be ok.

The motor board does have a library at https://learn.adafruit.com/adafruit-motor-shield/downloads and you can look at the code to see what it uses.

I personally use the mpu6050 - same kind of thing, I2C one interrupt but only 6DoF (which is plenty).  The 6050 has been superseded with the 9150, 9DoF.  6050 break out boards sell for $6 (or less).  Actually I put all this together on one piece (http://www.spiked3.com/new-products/)


body:
**Consider this question closed, found my answer through the answers I had**

I am trying to make a position profile curve depending on Looptime, accelerationloops,Setposition,Currentposition(position) and velocity.
The curve should look like this:

![enter image description here][1]

Is someone able to check what is wrong with my code?

    float array[30];

    struct Formula {
      int LoopTime = 1000;
      int AccelerationLoops = 11;
      float VelocityLoop = 0;
      float VelocityFactor = 0;
      int TotalLoops = 0;
      float DeltaPosition = 0;
      int Setpoint = 0;
      int Iteration = -1;
      float EndOne = 1.25;
    }Formula;

    float SetPosition = 1404;
    float Position = 0;
    float Velocity = 36;

    void setup() {
      Serial.begin(115200);
      for(Formula.Iteration ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
        ProgFormula();
        Serial.println(Formula.Iteration);
        if(Formula.Iteration >= 0) {array[Formula.Iteration] = Formula.Setpoint;}
      }
      for(Formula.Iteration = 0 ; Formula.Iteration <= Formula.TotalLoops; Formula.Iteration++){
        //Serial.println(array[Formula.Iteration]);
      }
    }

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

    }

    void ProgFormula(){
      if(Formula.Iteration == -1) {
        Formula.DeltaPosition = SetPosition - Position;
        Formula.VelocityLoop = Velocity / (1000 / Formula.LoopTime);
        Formula.TotalLoops = Formula.DeltaPosition / Formula.VelocityLoop + Formula.AccelerationLoops;
        Formula.VelocityFactor = Formula.VelocityLoop * 0.5 / Formula.AccelerationLoops;
        Formula.EndOne = (Formula.VelocityFactor*pow(Formula.AccelerationLoops,2));
      }
      else if (Formula.Iteration >= 0 && Formula.Iteration <= Formula.AccelerationLoops) {
        Formula.Setpoint = Formula.VelocityFactor * pow(Formula.Iteration,2);
      }
      else if (Formula.Iteration > Formula.AccelerationLoops && Formula.Iteration <= (Formula.TotalLoops - Formula.AccelerationLoops)) {
        Formula.Setpoint = Formula.VelocityLoop * Formula.Iteration - Formula.EndOne;
      }
      else if (Formula.Iteration >= (Formula.TotalLoops - Formula.AccelerationLoops) && Formula.Iteration <= Formula.TotalLoops) {
        Formula.Setpoint = -Formula.VelocityFactor * pow((Formula.TotalLoops - Formula.Iteration),2) + Formula.DeltaPosition;
      }
      else {
        Formula.Setpoint = Formula.Setpoint;
      }
    }

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

title: Strange phenomenon when declaring double

Answers: 1

body:
OK, this may not be a proper answer. I'm just having a hard time reading
your code, and I cannot understand why you make it so complicated. If
you know the acceleration profile, computing the position profile is
just a matter of integrating twice. Here is an example, not for Arduino
but for a PC. It should not be very different on an Arduino, you just
wouldn't use `printf()`:

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

    /* Compute position for any acceleration profile. */
    void compute_profile(float (*acceleration)(int), int max)
    {
        float x = 0, v = 0;

        for (int t = 0; t <= max; t++) {
            v += acceleration(t);
            x += v;
            printf("%d\t%f\n", t, x);
        }
    }

    /* Your particular acceleration profile. */
    float VttgJ(int t)
    {
        if (t <  7) return t;
        if (t < 13) return 12 - t;
        if (t < 40) return 0;
        if (t < 46) return 39 - t;
        else        return t - 51;
    }

    int main(void)
    {
        compute_profile(VttgJ, 50);
        return 0;
    }


body:
I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment.
Any help would be appreciated!

example of what i want the Serial Monitor to write:
Count:0
Count:1
Count:2 ....

What it is currently doing:
Count:0
Count:0
Count:0

    const int pingPin = 7;

    void setup() {
      // initialize serial communication:
      Serial.begin(9600);
    }

    void loop()
    {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm, count;

      // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
      pinMode(pingPin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);

      // The same pin is used to read the signal from the PING))): a HIGH
      // pulse whose duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      pinMode(pingPin, INPUT);
      duration = pulseIn(pingPin, HIGH);

        // convert the time into a distance
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);
    // count = 1;

     if (inches > 5)
    {
      Serial.print("Count: ");
      Serial.print(count);
      Serial.print('\n');
      delay(1000);
            count++;

    }

    }

    long microsecondsToInches(long microseconds)
    {
      return microseconds / 74 / 2;
    }

    long microsecondsToCentimeters(long microseconds)
    {

      return microseconds / 29 / 2;
    }

title: Counter using Ultrasonic Sensor (self.arduino)

Answers: 1

body:
Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

**Global**

    long count = 0;

    void loop()
    {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;

**Static**

    void loop()
    {
      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;
      static long count = 0;

Both will do the same job, but the `static` form is preferred since it is always better to keep a variable's scope as narrow as possible.  It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.


body:
I am using an Arduino Uno and have used up all it's pins so I have plugged up a Nano to a couple of the Uno's pins and using the Uno's 5v and ground to power the Nano. Is this ok?

It's been working fine until recently. My Uno will no longer allow me to upload code but everything still powers fine and runs on the existing code I had uploaded before. The reset button on the Uno does not work so I assume it's bricked, but it does still operate fine on the code it has, as I said.

Anyway, my question, is it ok to run the Nano like this? Is it using too much of the Uno's current... because the Nano's pins are also all being used. I'm no good at regulating current and just want to make sure that the Nano isn't eating up a bunch of current from the Uno by lighting it's LED's and it's other operations.

title: How to use Arduino Nano with Arduino Uno

Answers: 3

body:
Be careful not to power any sort of motor directly from an Arduino (or any of it's siblings directly) without a transistor or H-bridge in between, unless you know exactly how much current your motor draws, peak, and how much your arduino can supply on any given pin. The same applies to any other high-draw device too.

If you are using LEDs, make sure you have a resistor in series with the LED - google "LED resistor calculator" to help you figure out which resistor you need.

Also, when you upload the program, it uses two of the pins - rx and tx, should be digital pins 0 & 1 on a Uno (any other, check your docs).

body:
Maybe it is a very good idea to connect Arduino UNO's only one DIGITAL out point among other digital output pins. This pin can trig Arduino Nano's analog input pins so that you can work your task for further you needed. But you have to seperate your shields or your motors or other things. Like this:

![enter image description here][1]

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

By the way, if you get an upload error, please plug out your shileds or motors or LEDs then try to upload your code again into Arduino UNO.

body: try to connect uno and nano with I2C or serial, with I2C it connected to SCA/SDL pin (analog 4/5) or with serial it connected to tx rx. Make sure you use a pull up resistor. From the main site of arduino there's a tutorial in there but forgot to set up a pull up resistor.


body:
So I'm trying to hook up this [BLE breakout board][1] to an Arduino Uno. SparkFun has a [hookup guide][2] which seems to be great for someone who has an FTDI SmartBasic that is mentioned in the article. I don't have the SmartBasic board, and would like to see if this is possible without it.

I have hooked up the board to my Uno with the following pinouts:

    GRN -> Reset
    RXI -> RX (tried with TX as well)
    TXI -> TX (tried with RX as well)
    VIN -> Tried 5V and 3.3V
    CTS -> GND
    BLK -> (No Connection)

I use their [example code][3] they have provided, uploaded without the RX and TX pins hooked up because, from what I notice, you cannot upload a program through the USB serial when these ports are in use. So after I upload the program through USB, I power the board with a battery and connect the RX and TX pins to the BLE board.

Has anyone either successfully hooked these up without the use of a SmartBasic? I'm a programmer by trade so I do my best to understand this side of the spectrum.

  [1]: https://www.sparkfun.com/products/13019
  [2]: https://learn.sparkfun.com/tutorials/bc118-ble-mate-2-hookup-guide?_ga=1.207897426.1342547721.1435176975
  [3]: https://github.com/sparkfun/SparkFun_BLE_Mate2_Arduino_Library

title: BLE Mate 2 bluetooth module to Arduino Uno without FTDI SmartBasic

Answers: 1

body:
So I found out what I was doing wrong, and want to smack myself for it -.-

The answer was to simply hook up the BLK connection (which I guess is also ground) to a GND pin on the Arduino Uno.

Hope this ends up helping someone out.


body:
Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.

    unsigned long previousMillis1 = 0;
    unsigned long currentMillis1 = millis();
    unsigned long previousMillis2 = 0;
    unsigned long currentMillis2 = millis();
    unsigned long previousMillis3 = 0;
    unsigned long currentMillis3 = millis();

    bool timer1(int preset){
      unsigned long currentMillis1 = millis();

      if(currentMillis1 - previousMillis1 >= preset ){
        previousMillis1 = currentMillis1;
        return true;
      }
      else{
        return false;
      }
    }

    bool timer2(int preset){
      unsigned long currentMillis2 = millis();

      if(currentMillis2 - previousMillis2 >= preset ){
        previousMillis2 = currentMillis2;
        return true;
      }
      else{
        return false;
      }
    }

    bool timer3(int preset){
      unsigned long currentMillis3 = millis();

      if(currentMillis3 - previousMillis3 >= preset ){
        previousMillis3 = currentMillis3;
        return true;
      }
      else{
        return false;
      }
    }

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

    void loop() {
      if(timer1(1000)){Serial.println(1);}
      if(timer2(2000)){Serial.println(2);}
      if(timer3(3000)){Serial.println(3);}
    }

title: Timer function without the use of a library

Answers: 5

body:
 1. Those lines like

    currentMillis1;

    are completely useless

 2. You do not really have "timers", especially if your goal is to be more efficient. What you have done is to create some convoluted way to perform a test that could be done as:

    int PERIOD = something;
    for (int target = millis() + PERIOD; millis() < target;);

 3. If you really care about efficiency and timed actions, check some library that deals with timer interrupts.

 4. Start reading the code of existing libraries and try to understand it.
    Chances are that who wrote them knew a great deal more than you know. You will learn much more from first reading the code than trying to accomplish something that is clearly too much beyond your current knowledge (the fact you think what you did is an optimization proves it).

body:
It depends on what kind of efficiency you want. In coding we can often between better execution speed and less memory required. And in the case of Harvard-architected machines such as the AVR devices, which have separate memories for code and data, there may be a further balance between those, too.

But it looks like you're trying to reduce your code space requirement. So notice how alike your three timer functions are. I'd combine those into one, and pass another argument that indicates which timer value to operate on.

Secondly, (and this is probably a bug more than an inefficiency), you have three globals that are not being used (in your example, anyway): `long currentMillis1`, ..2, & ..3. You have redeclared each of those names as a local variable in the respective timer function, which, within that function over-rides (hides) the global declaration. There is no code that uses those globals.

body:
Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.

Here it is easy: the only difference between your timer functions is
that they use a different `previousMillis` variable. Also, the name of
the `currentMillis` variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a _reference_ to
the relevant `PreviousMillis`.

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

    bool timer(unsigned long &last_time, unsigned long period)
    {
      unsigned long now = millis();
      if (now - last_time >= period) {
        last_time = now;
        return true;
      }
      return false;
    }

And you use it like this:

    void loop() {
      static unsigned long previousMillis1;
      static unsigned long previousMillis2;
      static unsigned long previousMillis3;

      if (timer(previousMillis1, 1000)) Serial.println(1);
      if (timer(previousMillis2, 2000)) Serial.println(2);
      if (timer(previousMillis3, 3000)) Serial.println(3);
    }

I took the liberty of making all the `previousMillis` local to `loop()`,
since they are only used there. Making them `static` means their values
are remembered between call to `loop()`, much like global variables.

In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are _explicitly_ manipulating
addresses, while this is implicit with references:

    bool timer(unsigned long *last_time, unsigned long period)
    {
      unsigned long now = millis();
      if (now - *last_time >= period) {
        *last_time = now;
        return true;
      }
      return false;
    }

    void loop() {
      /* [...] */
      if (timer(&previousMillis1, 1000)) Serial.println(1);
      /* [...] */
    }

The next step in code modularity would be to wrap this timer function,
together with the associated data (`last_time` and `period`), inside a
class:

    class Timer
    {
    public:

      Timer(unsigned long _period)
      : period(_period), last_time(millis()) {}

      bool shouldRun() {
        unsigned long now = millis();
        if (now - last_time >= period) {
          last_time = now;
          return true;
        }
        return false;
      }

    private:
      unsigned long period;
      unsigned long last_time;
    };

Then, you would use it like this:

    Timer timer1(1000);    // period = 1000 ms
    Timer timer2(2000);    // period = 2000 ms
    Timer timer3(3000);    // period = 3000 ms

    void loop() {
      if (timer1.shouldRun()) Serial.println(1);
      if (timer2.shouldRun()) Serial.println(2);
      if (timer3.shouldRun()) Serial.println(3);
    }

body:
You can simplify **a lot** by using arrays. The example code below just uses a single variable (array) to store all the time intervals you are interested in.

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

    const int NUMBER_OF_TIMERS = 5;

    unsigned long intervalStarted [NUMBER_OF_TIMERS];

    void resetTimer (const int whichTimer)
      {
      if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
        return;   // sanity clause
      intervalStarted [whichTimer] = millis ();
      }  // end of resetTimer

    // interval in milliseconds
    bool timeUp (const int whichTimer, const unsigned long whatInterval)
      {
      if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
        return false;   // sanity clause
      return  millis () - intervalStarted [whichTimer] >= whatInterval;
      }  // end of timeUp

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.println (F("Starting ..."));
      }  // end of setup

    void loop ()
      {

      if(timeUp(0, 1000))
        {
        Serial.println(1);
        resetTimer (0);
        }  // end of if timer 0 up

      if(timeUp(1, 2000))
        {
        Serial.println(2);
        resetTimer (1);
        }  // end of if timer 1 up

      if(timeUp(2, 3000))
        {
        Serial.println(3);
        resetTimer (2);
        } // end of if timer 2 up

      }  // end of loop

I have allowed for 5 "timers" in the code but only used 3 to be consistent with the original post. You can see that you can have as many as you want (until you run out of RAM) with only an overhead of 4 bytes per "timer".

Two functions are provided. One checks if a nominated interval is up, the other one "resets" the timer by setting its start time to now. The checking function should work correctly even during millis() wrap-around, providing you are not trying to time more than 4294967296 milliseconds in one hit (49.71 days).

Note that the timer numbers are zero-relative, so the first timer is timer 0. You could make them one-relative if you prefer that with a slight adjustment to the two functions.

You could also, if you chose to, put the resetTimer function call inside the timeUp function (if the time is up) so that the timer automatically resets. I didn't do that because I think starting timing, and detecting the end of a period could be two different things. For example, when you boil an egg, you start timing from the time the egg goes onto the boil, not from when you last cooked an egg.

body:
Happened across [this page][1] which explains Arduino timer interrupts with out using any libraries.  The Atmel timer hardware is discussed and the sketches not only control the hardware directly but also include the actual interrupt service routine.  So addresses the OP's question very well.

  [1]: https://oscarliang.com/arduino-timer-and-interrupt-tutorial/


body:
I want to skip all `'\r'` and `'\n'` chars and I have IF statment:

    char c = Serial.read();
    if (c != '\r' || c != '\n') { // <- This line interesting
       mAnswer[mAnswerLength] = c;
       mAnswerLength++;
    }

VS

    char c = Serial.read();
    if (c != '\r' && c != '\n') { // <- This line interesting
       mAnswer[mAnswerLength] = c;
       mAnswerLength++;
    }

What is better and what is the difference?

title: Simple question about && vs ||

Answers: 3

body:
|| means logical OR

&& means logical AND

body:
Think about it "logically" (pun intended...):

You read a character.  Say it's "A".  You then compare it to both '\r' and '\n'.

    char c = Serial.read();
    if (c != '\r' || c != '\n') { // <- This line interesting
        mAnswer[mAnswerLength] = c;
        mAnswerLength++;
    }

That is saying "If A is not CR or A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR or CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  If it's OR, then if either part is true then it will be true.  So since CR is not LF it will add it.

Now:

    char c = Serial.read();
    if (c != '\r' && c != '\n') { // <- This line interesting
        mAnswer[mAnswerLength] = c;
        mAnswerLength++;
    }

That is saying "If A is not CR and A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR and CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  Just as before.  However, if it's AMD, then if BOTH parts are true then it will be true.  So since CR is CR it won't add it.

In summary, the first one will ALWAYS be true since one half is always going to be true.  The second one will ONLY be true if BOTH parts are true.  So the first one just plain isn't going to do what you want.

body:
You can rewrite first condition to be more obvious

    if (c != '\r' || c != '\n') {
as

    if (!(c == '\r' && c == '\n')) {

Which is always true (`c` have only one value), i.e. it makes no sense.


body:
I have situation where I need to read RFID cards. There is already installed Roger security system, Roger gate control board and two rfid readers in parallel. By default board and RFID readers communicate in RACS(some sort of coded protocol) but at the moment system is configured to communicate in Wiegand26. Earlier I used chinese wiegand26 reader with Arduino with no problem.

With Arduino I need to read card read by RFID readers.
Then I process data and make HTTP POST request.
Arduino is supplied from Roger board ~13.5V DC I do not get anything in arduino, even if I connect RFID readers directly to arduino.

 - CLK is D0 to Arduino Nano pin 2
 - DTA is D1 to Arduino Nano pin 3

This question is not related only to Arduino.

I want to ask is it possible to do? To read data maybe I need some additional electronics?

What i also noticed that when Arduino is connected in parallel the Roger board not always reads the card from RFID readers.

Roger [PR402-BRD][1]
And two readers [PRT62LT][2]
![enter image description here][3]

This is copy of [Electronics.stackexchange][4]

  [1]: http://www.roger.pl/en/products-to-be-discontinued/760-pr402-brd-access-controller.html
  [2]: http://www.roger.pl/en/access-control/readers/proximity-readers-em-125-khz/805-prt62lt-proximity-reader-em-125-khz.html
  [3]: https://i.stack.imgur.com/z7IBI.png
  [4]: https://electronics.stackexchange.com/q/177168/58967

title: Parallel connection to Wiegand 26bit RFID readers

Answers: 2

body:
It looks to me like the Wiegand interface is an open-collector interface (like I2C), which is why they can be wired in parallel like that.

As long as the Arduino has both connections set to `INPUT` (not `INPUT_PULLUP` and certainly NOT `OUTPUT`) it shouldn't interfere at all.

By the way, for Wiegand, the two signals are DATA0 and DATA1.  To transmit a 0 the DATA0 line is pulled low. To transmit a 1 the DATA1 line is pulled low.

You should also check that the idle voltage on the lines is indeed 5V as it should be.  Anything more than that could cause the Arduino to chip the voltage to 5V through its internal ESD protection diodes.

Also you must ensure that the Arduino has its ground pin connected to the ground connection of the Wiegand system (which it should be since you are powering it from that).

body:
If you would like to use more than 1 Wiegand reader, technically it should be possible to use **AVR pin change interrupt**. In this case you can use ANY 2 pins, even analog pins.

For example, see http://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/

**UPD:** There is informationon Wiegand timing, might be useful:
http://proxclone.com/wiegand.html


body:
I am trying to set up a CAN-bus with its two nodes on the same Arduino. By Using an Arduino DUE without any transceivers. As my first experiment, I want to send a message from one CAN unit to the other. But so far I have not been successful to see any signal on the bus. (I am using an Oscilloscope)

**Here is the detail of my effort:**

I have used this(1) library, and I want to run the CAN_EchoTest example(2).
As for the physical layer, I have created a circuit, according to a Method that is suggested here(3), here(4), and here(5). I set the transmission rate to 5Kbps, (lowest possible value provided by the library), to make sure that noise and propagation effects are minimal.

I implemented this mentioned Method to the Arduino board, using the Board's Schematics(6). In other words, I assumed that:

    CANTX1 in the schematics, refers to PIN with the label '53' on the board.
    CANRX1 in the schematics, refers to PIN with the label 'DAC0' on the board.
    CANRX0 in the schematics, refers to PIN with the label 'CANRX' on the board.
    CANTX0 in the schematics, refers to PIN with the label 'CANTX' on the board.

And I assumed the library that I am using configures the mutual PINS (DAC0 and 53), in a way that CAN controllers will be using them exclusively. I am not sure about the pair of diodes that I used: Vishay SS34A.

what is missing/wrong? Please be patient regarding any rookie mistakes. I can Provide further information if requested.

Thank you in advance

  (1) [github.com/collin80/due_can][1]

  (2) [github.com/collin80/due_can/tree/master/examples/CAN_EchoTest][2]

  (3) [www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf][3]

  (4) [electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus][4]

  (5) [www.keil.com/download/files/canprimer_v2.pdf][5]

  (6) [www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf][6]

  [1]: http://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf
  [2]: http://github.com/collin80/due_can/tree/master/examples/CAN_EchoTest
  [3]: http://www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf
  [4]: https://electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus
  [5]: http://www.keil.com/download/files/canprimer_v2.pdf
  [6]: http://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

title: CAN Bus without Transceivers

Answers: 1

body:
You will have to play some games to make it work.  CAN is a bus with dominate and recessive states.  This is how it arbitrates.  When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive.  At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.

You can simulate this with a few transistors (not real CAN but will work).  Monitor the bus with the receive side and drive it with the transistor with a pull up resistor.  When the transistor is on that is the dominate state when the transistor is off that is the recessive state.  This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send.  Transceivers are very cheep on eBay and they have the Maxim chip which is very good.
Good Luck,
Gil


body:
I've got an Arduino Micro, and a MAX4466 ECM / AMP breakout board (https://www.adafruit.com/product/1063). I'm powering the Arduino Micro from the USB port.

On the MAX4466 (to the Arduino), I've wired VCC to 3.3v, GND to GND, and OUT to A0. I've also wired 3.3v to AREF.

Using the following code, I'm noticing significant noise spikes on the output, as shown in the graph below.

I'm not entirely sure what I've done wrong here, and would appreciate any input / criticism that could lead to getting a clean signal.
<!-- language-all: lang-cpp -->

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

    void loop()
    {
       Serial.println(analogRead(0));
    }

![enter image description here][1]

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

title: Arduino Micro + Max4466 - Noise on A0

Answers: 2

body:
The OP itself solve it:

> Ok - so I suspected that it was the Arduino at fault.. Turns out it's
> a cheap Chinese clone. After purchasing an official Micro, and wiring
> up the same component, I'm getting a nice clean signal (bar a small
> amount of acceptable noise), which is reflecting input tones
> accurately. Thanks again for all the input!

body: Interesting plot. Gives me the impression that your reference is sagging, consider adding some local storage (tant/ceramic capacitors) across the cpu's power in pins and across the cpu's Reference pin. Would also be interesting to know if adding more delay between measurements would improve performance. Thanks for sharing you issue.


body:
I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with `analogWrite()` to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.

P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.

title: Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?

Answers: 3

body:
No, you can't.  As it says in the Arduiuno [reference page][1] for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."

You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs.  They cannot be used for PWM(digital)-output.  Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).

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

body:
You can't do it with the analogWrite function as that is reliant on physical binding beween certain pins and hardware timers inside the AVR. But you can always use [SoftPWM][1] because the the analog pins can generally be used as digital pins just as well.

  [1]: https://www.pjrc.com/teensy/td_libs_SoftPWM.html

body:
You can use multiplexers if you are running out of digital pins or SPI PWM drivers for the motors. There are many multichannel drivers out there like [TLC5940][1], put a power stage after them and you're done.

*Use Soft SPI on the analog pins to control the driver.

  [1]: http://www.ti.com/lit/ds/symlink/tlc5940.pdf


body:
I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a `status` pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.

The algorithm I wrote is very simple:

    Set pinTest to input, no pullup.
    Is pinTest high?
        Yes - pinTriState is HIGH, done.
    Set pinTest to input with pullup.
    Is pinTest high?
        Yes - pinTriState is HiZ, internal pullup causes high reading.
        No - pinTriState is LOW, 'cancelling out' internal pullup.

However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno->Micro and Micro->Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time `pinTriState` stays at in a given state to keep `pinTest` guessing, but it's ultimately only an elaborate way of cycling through the three states.

    #define pinTest 2
    #define pinTriState 3

    int state = 0;
    char stateCh = '?';

    int sect1;
    int sect2;
    int sectMax;

    void setup()
    {
        Serial.begin(9600);
        randomSeed(analogRead(A0));
        sect1 = random(1, 20);
        sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
        sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
    }

    void loop()
    {
        // PART (1) Code to toggle three states of a tri-state pin
        if (state == 0)
        {
            pinMode(pinTriState, OUTPUT);
            digitalWrite(pinTriState, HIGH);
            stateCh = 'H';
        }
        if (state == sect1)
        {
            pinMode(pinTriState, OUTPUT);
            digitalWrite(pinTriState, LOW);
            stateCh = 'L'
        }
        if (state == sect2)
        {
            pinMode(pinTriState, INPUT);
            stateCh = 'Z';
        }

        // PART (2) Code to determine state of tri-state pin
        Serial.print(stateCh);     // Shows what it *should* be
        pinMode(pinTest, INPUT);
        if (digitalRead(pinTest))
            Serial.println(" - HIGH");
        else
        {
            pinMode(pinTest, INPUT_PULLUP);
            if (digitalRead(pinTest))
                Serial.println(" - HiZ");
            else
                Serial.println(" - LOW");
        }

        (state == sectMax ? state = 0 : state++);
    }

The necessary pins are connected with a single wire. If I upload the code to two boards I remove *PART (2)* on the 'triState' board and *PART (1)* on the 'testing' board. In this case, `stateCh` has no function.

For a single-board setup, I get the following output:

    H - HIGH
    H - HIGH
    ...
    L - LOW
    L - LOW
    ...
    Z - HiZ        <-- the first Z is correct 95% of the time
    Z - HIGH
    Z - HIGH       <-- the remaining Zs are a mixture, biased heavily towards HIGH.
    Z - HiZ
    ...
    H - HIGH       <-- H always gives HIGH
    ...

It makes no difference if I change the operating order of `pinState`. I've thrown in `delay(100);` between almost every other line, again to no avail.

I tried with a 22k, a 33k, and a 47k *external* pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. *Part (2)* becomes:

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be
    pinMode(pinTest, INPUT);
    pinMode(pinPullup, INPUT);    // connected to pinTest via resistor
    if (digitalRead(pinTest))
        Serial.println(" - HIGH");
    else
    {
        //pinMode(pinTest, INPUT_PULLUP);   <-- not anymore
        pinMode(pinPullup, OUTPUT);
        digitalWrite(pinPullup, HIGH);    // pulls pinTest to Vdd
        if (digitalRead(pinTest))
            Serial.println(" - HiZ");
        else
            Serial.println(" - LOW");
    }

Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!

title: Testing tri-state pin - erroneous results with internal pullup

Answers: 4

body:
The internal pull-up is around 50k. So, install an external pull-**down** (to ground) of a somewhat higher value, like 1M.

Now:

Go to input mode, no pull-up. Get a reading. Turn on the internal pull-up. This should overpower the pull-down. If the reading **changes**, it was tri-state. Otherwise, if the reading doesn't change the external device is overpowering both pull-up and pull-down and you have the actual reading.

You may need a slight delay to allow the low-value pull-down to change the pin state.

---

Amended code to demonstrate:

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

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be

    pinMode(pinTest, INPUT);
    delayMicroseconds (100);
    byte firstReading = digitalRead(pinTest);
    pinMode(pinTest, INPUT_PULLUP);
    delayMicroseconds (10);
    byte secondReading =  digitalRead(pinTest);

    if (firstReading != secondReading)
      Serial.println(" - HiZ");
    else if (secondReading == HIGH)
      Serial.println(" - HIGH");
    else
      Serial.println(" - LOW");

(Only showing the part that detects the pin state, the rest is the same).

Output:

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

    H - HIGH
    L - LOW
    Z - HiZ
    Z - HiZ
    Z - HiZ
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    L - LOW
    Z - HiZ
    Z - HiZ
    Z - HiZ
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    H - HIGH
    L - LOW
    Z - HiZ
    Z - HiZ
    Z - HiZ
    H - HIGH
    H - HIGH
    H - HIGH

As you can see, working perfectly. I needed a longer delay after turning the internal pullup **off** because the fall time was around 100 µs. This actually sounds reasonable, because the 1 megohm resistor will take time to discharge the capacitance on the pin.

So:

* 10 µs delay after turning the internal pull-up **on**

* 100 µs delay after turning the internal pull-up **off**

---

**Theory for the delays**

The Atmega328 pin is specified as having a maximum capacitance of 10 pF (10e-12). It is considered charged/discharged after 5 time-constants, where `T = R.C`.

Thus for an internal pull-up resistance of 50k and a capacitance of 10 pF, charging should take:

    50e3 * 10e-12 * 5 = 2.5e-006 (0.0000025) -> 2.5 µs

And to discharge through 1M (1e6) ohms, discharging should take:

    1e6 * 10e-12 * 5 = 5e-005 (0.00005) -> 50 µs

My observed results were about 2.5 µS for the charge, but more like 100 µs for the discharge, however I probably had considerable stray capacitance in the wires used in the test circuit.

body:
Another option is to use an analog input pin instead of a digital input pin.

Create a balanced voltage divider using equal high value resistors (say 100KΩ each).  Attach the mid-point to the ADC pin, and one end to each of Vcc and GND.  The incoming status signal goes to the ADC pin:

![enter image description here][1]

Perform an analogRead() on the pin.  You will get one of 3 results:

* Close to 0 = LOW
* Close to 1024 = HIGH
* Close to 512 = HiZ

When the pin is in HiZ the resistors will hold the voltage at around 50% of Vcc.  When the pin goes HIGH it will pull the pin up and override the resistors, giving a high value reading.  Similarly, when the pin goes low, the resistors will be overridden and a low value reading will be given.

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

body: For the 1M pulldown solution, turning off the internal pullup at the end of the pin check routine MIGHT give enough time for the pin to discharge, and it might not if the code can conditionally do very little else between pin checks.  If you want to leave out the 100 us delay, take care to ensure that your code will always do something that takes sufficient cycles for the pin to discharge between checks.

body:
Nick Gammon's answer seems the most straightforward solution to your
problem, given that you cannot spare an analog input. It has however the
drawback of needing a delay of ≈ 100 µs. This may not be an
issue, but I just figured out a scheme that allows a faster read, and
may be of interest to some: instead of pull-ups or pull-downs, put just
a 10 kΩ resistor _in series_ between the MPC73831's output and you
Arduino input. When you want to read the state:

1. Take a first reading with the pin in INPUT mode:
* if you read HIGH, then your MPC is either HIGH or HI\_Z
* if you read LOW, then it's either LOW or HI\_Z
2. Now, switch the pin to OUTPUT, write the _opposite_ of what you just
   read, switch back to input and take a second reading:
* if you read what you just wrote, then your MPC is in the HI\_Z state
* if you read the same as before, then it's either HIGH or LOW.

Here is the implementation of this scheme:

    #define HI_Z 2

    /*
     * Read a 3-state pin.
     * Put a 10 kOhm resistor between the output and input pins.
     */
    int read3state(int pin)
    {
        int reading1 = digitalRead(pin);
        pinMode(pin, OUTPUT);
        digitalWrite(pin, !reading1);
        pinMode(pin, INPUT);
        int reading2 = digitalRead(pin);
        if (reading1 == reading2)
            return reading1;
        else
            return HI_Z;
    }

I have tested this a few 104 times with an Arduino sending to
itself a pseudo-random sequence of LOW, HIGH and HI\_Z. It works
reliably for me.

**Caveat**: This scheme relies on the pin being capacitively coupled to
GND or Vcc, and this coupling being stronger than couplings with other
signals in your circuit. If you fear this might not be the case, you can
put something like 100 pF from the pin to ground, but then you
should better wait a couple of microseconds before taking the second
reading.


body:
I am just getting started with my Uno via the Vilros Ultimate Starter Kit. I've done all of the sample circuits and played around with a few other things.

Today I connected the Ethernet shield with the intention of building a temperature logger. I am finding that the output I get from the included TMP36 temperature sensor is much different with the Ethernet shield installed.

The kit's sample circuit #7 for the temperature sensor connects the sensor directly to 5V and GND and the sensor output to A0. The loop code (compressed a bit for pasting here) looks like this:
<!-- language-all: lang-cpp -->

    float voltage, degreesC, degreesF;
    voltage = analogRead(temperaturePin) * 0.004882814;
    degreesC = (voltage - 0.5) * 100.0;
    degreesF = degreesC * (9.0/5.0) + 32.0;
    // Write to serial; omitting for brevity
    delay(1000);

*Without* the Ethernet shield installed, a typical output I get from this looks like:

    voltage: 0.81  deg C: 30.57  deg F: 87.02

That might be a little high but it feels close enough for what I'm going for at the moment (I don't have a reliable thermometer with me, but it's a warm day here). It's close enough, and is stable across readings.

*With* the shield installed, the exact same circuit and sketch outputs this:

    voltage: 0.96  deg C: 46.19  deg F: 115.14

It's still very stable across readings but obviously way off. What could cause this and how can I fix it? I am not expecting the sensor to be perfectly accurate but the major discrepancy I'm seeing makes this unworkable.

title: Uno Ethernet shield and TMP36 reading

Answers: 0


body:
I spent a significant part of today developing a sprite movement library for a 30-pixel NeoPixel strip using my Arduino Duemilanove (ATmega 168). It works like a charm. However, if I change `N_LEDS` to a significantly higher value, the program seems not to run. I can't get it to run on the Duemilanove for a strip of longer than 50.

In fact, (see the below code) a relatively high `N_LEDS` value won't even allow the test patterns to run as defined in `setup()`. This leads me to believe that inexplicably the constructor for `Adafruit_Neopixel` is failing.

A friend of mine (who has the ultimate application for this) is hoping to drive a strand of 750 LEDs using this code on an Arduino Due. I can't imagine memory would be an issue with the Due, so what's going on here?

Headers:

    #include <Adafruit_NeoPixel.h>

    #define PIN    6
    #define N_LEDS 30      // <-- If this number is > ~50, nothing happens
    #define MAXSPRITES 5
    #define MIN_UPDATE_INTERVAL_IN_MS  15
    #define MAX_UPDATE_INTERVAL_IN_MS  40
    #define SENSOR_TIMEOUT_IN_MS  2000
    #define SCANNER_WIDTH  9

Strip declaration:

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

`setup()` and `loop()`:

    void setup() {
        randomSeed(analogRead(0));

        strip.begin();

        darkenStrip();

        manager = new SpriteManager();
        manager->Add(new TestPatternSprite(0, 0xff0000));
        manager->Add(new TestPatternSprite(5, 0x00ff00));
        manager->Add(new TestPatternSprite(10, 0x0000ff));
    }

    loop() {
        ...
    }

Are there any coding mistakes in the above that wouldn't allow us to run this code on the Due? Or is this a known limitation?

title: Can't drive long NeoPixel strips with Due or Duemilanove?

Answers: 1

body:
Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.

750 LEDs sounds like pushing it for the low-RAM Arduinos.

You might want to look at [NeoPixels Revealed: How to (not need to) generate precisely timed signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/) The author managed to drive over 1000 NeoPixels with a Duemilanove.

I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.


body:
Hy guys,

I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.

I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.

Here's my code

    // ESC_Calibration.ino
    #include <Wire.h>
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <Servo.h>

    #define WHITE 0x7

    Servo firstESC;
    Servo secondESC;
    int throttlePin = 2;
    int firstESCPin = 2;
    int secondESCPin = 3;

    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

     lcd.begin(16, 2);
     lcd.setBacklight(WHITE);
     lcd.setCursor(0, 0);
     lcd.print("throttle:");

     firstESC.attach(firstESCPin);
     secondESC.attach(secondESCPin);
    }

    void loop() {
     int throttle = analogRead(throttlePin);
     throttle = map(throttle, 0, 1023, 0, 179);

     lcd.setCursor(0, 1);
            Serial.println(throttle);
            lcd.setCursor(0, 1);
     lcd.print(throttle);

     firstESC.write(throttle);
     secondESC.write(throttle);

     delay(500);
    }

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?

Thanks for your help in advance! :-)

title: LCD-Display showing wrong numbers

Answers: 1

body:
As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.

That means, as the numbers increase you get, say,

    4
    10
    48
    89
    194
    309

etc.

When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:

    309 (309)
    194 (194)
    894 (89 - the 4 remains from before)
    484 (48 - the 4 remains from before)
    104 (10 - the 4 remains from before)
    404 (4 - the 04 remains from before)

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.

To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay.  There's two common ways of doing this:

1. Append enough spaces after the number to force an overwrite:
````
    lcd.print(throttle);
    lcd.print("   "); // 3 spaces should be enough for 3 extra digits
````

2. Format the data with `snprintf()`:
````
    char temp[5]; // enough room for 4 numbers and one NULL character
    snprintf(temp, 5, "M", throttle); // M = 4 digits, right aligned
    lcd.print(temp);
````

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned.  Also arbitrarily adding spaces after the number could overwrite things you want to keep.

You could also achieve a similar result doing it manually:

    if (throttle < 10) lcd.print(" "); // 0-9 add one space
    if (throttle < 100) lcd.print(" "); // 0-99 add one space
    if (throttle < 1000) lcd.print(" "); // 0-999 add one space
    lcd.print(throttle);

Just like with cats, there's many ways to skin this problem...


body:
`Hello,`

I am currently working on a DIY project and I would like to know the Maximum Wattage of a Arduino Nano with a ATmega328 processor. If anyone know what it is it would be a great help.

`Ricky`

title: What is the Arduino Nano maximum wattage?

Answers: 0


body:
I recently built an RC car from scratch and I am using a PS4 controller to control it.  I have an ESC of course but my problem is I barely touch the joystick and the motor is going so fast I cannot control the car. Here is the code and any help would be much appreciated.

    /*
     Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
     For more information visit my blog: http://blog.tkjelectronics.dk/ or
     send me an e-mail:  kristianl@tkjelectronics.com
     */

    #include <PS4BT.h>
    #include <usbhub.h>
    #include <Servo.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB Usb;
    //USBHub Hub1(&Usb); // Some dongles have a hub inside
    BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
    Servo servo1;  //Steering Servo
    Servo servo2;  //DC Motor

    /* You can create the instance of the PS4BT class in two ways */
    // This will start an inquiry and then pair with the PS4 controller - you only have to do this once
    // You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
    PS4BT PS4(&Btd, PAIR);

    // After that you can simply create the instance like so and then press the PS button on the device
    //PS4BT PS4(&Btd);

    bool printAngle, printTouch;
    uint8_t oldL2Value, oldR2Value;

    void setup() {
      Serial.begin(115200);
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); // Halt
      }
      Serial.print(F("\r\nPS4 Bluetooth Library Started"));

      pinMode (3, OUTPUT);
      pinMode (5, OUTPUT);
      servo1.attach (3);
      servo2.attach (5);
    }
    void loop() {
      Usb.Task();

      if (PS4.connected()) {

        {
        servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
           //map values from the x-axis of the right analog stick
        servo2.write(map(PS4.getAnalogHat(LeftHatY), 0, 255, 0, 180));
           //map values from the y-axis of the left analog stick
        }}

        else

        {
          servo1.write (25);  // set servo motor to 0 point
          servo2.write (90);  // Turn DC motor off
        }

title: PS4 controller too touchy on the arduino RC car i built

Answers: 0


body:
I'd like to make a chess-board with the ability to detect the position of each piece.

The solution that occurs to me would be to put an RFID reader under each square and put RFID tags on the bottoms of each piece.

However, apart from the obvious cost (64 readers!) I'm concerned that:

1. Maybe RFID readers are too large for the squares of an ordinary chessboard
2. RFID reader range is too large, so a reader might pick up pieces on neighbouring squares
3. How the hell would I connect 64 readers anyway? Could an Arduino handle it?

So, questions.

Is this just stupid? And is there a better technology to use for this kind of application?

If RFIDs are basically a sane solution, what are the issues/suggestions? E.g. which RFID readers should I go for? (Based on size, energy, convenience for this application). What boards would let me handle this number of them?

title: Smart Chess-board (possibly using RFIDs?)

Answers: 1

body: As I read your post an idea came to me that must be obvious in its simplicity.  Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base.  Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field.  We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.


body:
I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.

I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

- GND -> Breadboard GND
- 5v -> Breadboard + rail
- TXO -> IC pin 2
- RXI -> IC pin 3
- GND (GRN) -> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.

Any ideas on what might be the problem?

title: Breadboard Arduino not loading sketches

Answers: 2

body:
1. Make sure you have a 16Mhz crystal attached to your board at the XTAL locations properly.

2. If you dont have one already, connect a 0.1uf capacitor (ceramic or metal film) to the reset pin for auto reset capabilities.

3. The `avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00` issue is probably due to reset problems, where the arduino is not communicating to the computer. However, there are other possible reasons for this error. http://forum.arduino.cc/index.php?topic=28223.0

4. Double check that TX on the arduino is connected to Rx on the computer and Rx on the arduino is connected to Tx on the computer

If problems keep persisting, post more information so we can help you more.

body:
To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial  connection:

 - you need to have a bootloader flashed on the chip

 - you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader

 - your programming software must use the same baud rate as the bootloader is expecting

 - you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader.  The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno.  You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.


body:
I want to program Attiny88 with Arduino IDE 1.6.5. I chose Attiny88  because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins. I found a library that support Attiny88 (https://github.com/TCWORLD/ATTinyCore) but it seams it does not support IDE 1.6.5 and generates errors when I burn bootloader or during ISP.

Is there any library to program Attiny88 with Arduino 1.6.5?

title: Attiny88 programming with Arduino

Answers: 2

body:
Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy  Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.

https://github.com/SpenceKonde/ATTinyCore

body:
I went through the same problem finding the cores for the attiny 88 and found this

http://forum.arduino.cc/index.php?topic=320742.0

https://arduino.stackexchange.com/questions/13011/programming-attiny88-attiny828-with-arduino

However, I have not yet found the core for the attiny88 at 12mhz (http://co.mouser.com/ProductDetail/Atmel/ATTINY88-AU/?qs=sGAEpiMZZMvqv2n3s2xjscfa4zIkTHJI8r77%2bczQD%2bE=)


body:
Hey all I am trying to convert a string into a uint8_t with the following code:

    String data = "#255101987";
    String tmp1 = data.substring(1, 3);

    uint8_t first  = (String)tmp1;

I am getting the error of:

>cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

Any help would be great as I thought adding **(String)** in front of the varible would solve the issue but it hasn't as you can tell.

title: Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

Answers: 1

body:
    uint8_t first  = atoi (tmp1.substring(1, 3).c_str ());

Or even:

    String data = "#255101987";
    uint8_t first  = atoi (data.substring(1, 3).c_str ());


body:
i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF.
I have Arduino, usb cable, external power supplier(adapter of 12V).

Can any one please suggest me how do i proceed for this ??

title: How to read AC Voltage in arduino uno with 12V adaptor and usb cable.?

Answers: 1

body:
If your battery voltage is lower than 12 but sufficiently high to power the arduino (let's say 9V), you could put a white LED on the 12V line and a red LED on the battery line, like this:

             WHITE       RED
      _______|>|_________|<|________
     |             |                |
    _|_          Arduino           _|_
     - 12V         |                -   Battery
     |_____________|________________|

This should work, as long as the LEDs can withstand the reverse voltage.
And you do not need to drive them from the Arduino.
If you still want to know the status fro mthe Arduino (mains or battery) you can sample the voltage level across the Arduino.


body:
I want to use CapacitiveSensor library in order to make my own aluminum keys piano. I have seen many videos online showing projects like the one I'm trying to do, but for some reason mine doesn't work.

Here's my cuircit:
![enter image description here][1]

Here's my code:

    #include <CapacitiveSensor.h>

    CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);  // 10M resistor between pins 7 & 6, pin 6 is sensor pin

    void setup()
    {
       //cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
       Serial.begin(9600);
    }

    void loop()
    {
        long start = millis();
        long total1 =  cs_7_6.capacitiveSensor(5);

        Serial.print(millis() - start);        // check on performance in milliseconds
        Serial.print("\t");                    // tab character for debug windown spacing

        Serial.print(total1);                  // print sensor output 1
        Serial.println("\t");

        delay(10);                             // arbitrary delay to limit data to serial port
    }

This happens whenever I touch the aluminum foil:

![enter image description here][2]

First nothing happens (for ~1 sec), then it prints -2 as the capacity value, and when I release my finger from the foil it prints a very high value.

Anyone knows the reason for it? I'm searching for an answer for a long time and still can't find a solution...

  [1]: https://i.stack.imgur.com/zq7rx.png
  [2]: https://i.stack.imgur.com/foltu.png

title: Capacitive Sensor gets stuck

Answers: 1

body:
The problem is that you're touching the foil.

The "capacitive sensing" used in that library is crude at best.

If you read [the Arduino Playground page for the Capacitive Sensing Library](http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) it discusses a lot of the problems with the library, including grounding.  Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.

Also they talk about the value of resistor and the sensitivity.  With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil.  That's the value you're seeing as you remove your finger.  While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current).  For "absolute touch" it recommends no more than 1MΩ.

Of course, as I mentioned, that method is rather crude.  To do it properly you need to:

1. Discharge an analog input pin through a MOSFET to ground (low impedance).
2. Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
3. Remove the current and measure the voltage on the ADC input.
4. Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - *Charge Time Measurement Unit*.  If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.

Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them.  The sensor should also be insulated from direct touch.


body:
I am working on a project and got stuck on a point, and I hope somebody will guide me. I have a hardware device which has different color LEDs (green, red and yellow) and I have to calculate how many times each color LED glows for each mode of operation.

The LEDs that are connected to the device are pretty small and will blink only for a couple of seconds, ao I am looking for a very sensitive light sensor.

So what kind of light sensor do I have to use with Arduino UNO to achieve this?

Should I go for BH1750 or do you have any other suggestion?

Thanks in advance.

title: Highly sensitive light sensor to calculate number of times each color LED blinks

Answers: 1

body:
Like the OP wrote, you can use very simple sensors, like a phototransistor.
Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.

**edit:**

A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.

3DU5C [ebay link][1]  and  [datasheet][2]

It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.

OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.

  [1]: http://www.ebay.com/itm/3DU5C-Silicon-Phototransistor-Transistor-2-feet-Metal-Package-/251556003565?pt=LH_DefaultDomain_0&hash=item3a91e7feed
  [2]: http://www.uctronics.com/download/3DU5C_spec.pdf


body:
I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address.

Now onto the question. The library's .h file has the following statement:

`#define H3LIS331DL_MEMS_I2C_ADDRESS     0x18//0x32`

Is the 0x32 simply commented out or am I missing something here?

Thanks,

Emach

title: Arduino C++ library syntax

Answers: 1

body: It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.


body:
I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050.
I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.

    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr[2] * 180 / M_PI);

    pitch_angle = (ypr[1] * 180 / M_PI) + 90;
    roll_angle = (ypr[2] * 180 / M_PI) + 90;

    Serial.print(pitch_angle);
    Serial.print("\t");
    Serial.println(roll_angle);

    pitchServo.write((int)(pitch_angle));
    rollServo.write((int)(roll_angle));

Without servo being connected everything works well.
But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted.

    100 95
    ypr 12.21 10.51 5.49
    100 95
    ypr 12.23 10.31 5.48
    100 95
    ypr 12.25 10.15 5.45
    100 95
    ypr 12.27 10.02 5.45
    100 95
    ypr -13.31 30.81 55.76
    120 145
    ypr 20.53 -21.36 -52.59
    68 37
    ypr 64.96 35.38 10.25
    125 100

I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.

**EDIT:**
Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base.
Wiring is very simple:

![enter image description here][1]

Any idea? Thanks

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

title: RC servo misbehave using arduino and MPU6050

Answers: 2

body:
So a couple of ideas.

1) you need to be real careful with the MPU and overflows. You do not show all your code, but you must check for overflows, and ignore the data if one has occurred. I see in your print a stray negative value, that tells me you are not skipping bad data.

2) I dont know how 'tight' your loop is. You need to service the MPU a lot. In fact the sample you used, uses an interrupt to do so. I think the default update rate is about 100 times per second.  That may be too fast to make large changes in servo positions.  You will need to think about moving slower from point A to B if the difference is more than the servo can handle at that speed.

3) You are adding 90. With the numbers you have shown that is probably ok, but in your final code you need to be careful you do not exceed a servos range, 0 to 180.  the map() function is probably something you will want to use, instead of just adding 90.

4) My guess is that since it works for a second or 2, it is indeed over flowing data, and then goes to heck. Especially since you do not skip errors.

5) it takes the 6050 30 seconds or so to settle - so you will see large gyro drift (including PitchRollYaw) until it does. Probably not what your code is expecting.

body:
At the end two pull-up resistors and one capacitor solved the problem.

I followed instruction here:

http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/

Now it works well.. Thank you all.


body:
I found some information that the attiny88 and attiny828 can be programed from an arduino, similar to the programing of the attiny85/45, simply connecting the right pins. https://electronics.stackexchange.com/questions/98970/how-to-program-atmel-attiny88-not-45-or-85

However, what I have not been able to find out are the arduino cores (drivers) for the attiny88 and attiny828.
I wonder if the cores (or drivers) to program the attiny88 and attiny828 from an arduino are available somewhere or would they have to be constructed?.

title: programming attiny88 & attiny828 with arduino

Answers: 0