body:
i am following Jeremy blum's tutorial on youtube. [link](http://youtu.be/5bHPKU4ybHY) i have done the exact same circuit design as he has.
![circuit](https://i.stack.imgur.com/EOjS3.png)

but the dc motor just makes a continuous beep sound when i run this code.

    int motorPin = 9;

    void setup()
    {
        pinMode(motorPin, OUTPUT);
    }

    void loop()

    {
        for(int i = 0; i <= 255; i++)
        {
            analogWrite(motorPin, i);
            delay(10);
        }

        delay(500);

        for(int i = 255; i >= 0; i--)
        {
            analogWrite(motorPin, i);
            delay(10);
        }

        delay(500);
    }

I am clueless as to why this is happening. would be glad if someone could help me out here.

title: DC motor makes noise but does not rotate

Answers: 4

body:
analogWrite uses PWM. Is the motor you are using designed for pulsed operation? Try using

    digitalWrite(motorPin, HIGH);

body:
I'm wondering if a 10 ms delay between steps is long enough for the motor to respond, especially with a cap across its terminals.  Besides that the whole thing is over in 5 seconds.

It seems to me that AnalogWrite generates a PWM signal of about 500hz or about 2ms wave period.  So in 10 ms you get 5 pulses of the same amplitude and smoothed by the cap.  At low values of "i", say i=10, then the pulse is only 10/255*2ms wide or about 78uS. At low values of i, a 180deg rotation has to occur in the time you apply the pulse for the motor to rotate, well not exactly but close enough.

Most small DC motors are 2 pole, so you're expecting at least one 180degree rotation in 5x78uS or about in 400uS.  That would be a full rotation in about 800uS, say 1mS, or 1000 rotations in 1 second, or 60000rpm, from a standing start if the duty cycle was held constant.  You have very little power at low "i" so I'd be surprised if there is enough to overcome friction and inertia.  On higher values I guess it's still not enough to overcome the inertia.

The motor well may run at the higher values of "i" but then the program immediately counts down again.

So I suggest you start the counter at say 125 or even higher. Also make the delay between counting up and counting back down much longer so you can actually see the effect before it counts down again. I would also want to make the delay between counts higher so there is more time for current to flow in the motor's (inductive) windings.  Remember an inductor resists a change in current. Now that I think about it, this is probably more important than the inertia and friction.

So here is a challenge... Change the delay between counts first, and report your results here.  Then reset that and change a different parameter, and so on. Eventually make a number of changes together...I'm curious to see the outcome.

By the way, I suspect the sound is from the motor laminations changing shape at high frequency.

Cheers
P

body: I had the same issue, turns out that i had configured the BJT wrong. I had confused the drain for the collector.

body: For the benefit of anyone reading Jeremy Blum's Exploring Arduino book who is having the same issue- he has labelled the transistor wrong in the book so the collector and emitter are back to front. Turn the transistor around to face the other way and your issue will be resolved.


body: I am trying to use the MakeyMakey with the Arduino (not as an Arduino) and then use a USB to TTL module to send the keys pressed to the Arduino. Is this possible? Do I have to reprogram?

title: MakeyMakey + Arduino

Answers: 1

body:
one possibility is to use HOST SHIELD
http://www.circuitsathome.com/products-page/arduino-shields

Arduino is now as host
Makey is keyboard


body:
I'm using the [ArduinoJson](https://github.com/bblanchon/ArduinoJson) library. There is a [great example](https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonParserExample/JsonParserExample.ino) for parsing a single JSON object in the source code. I am attempting to iterate over an array of JSON objects:

    #include <JsonParser.h>

    using namespace ArduinoJson::Parser;

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

      char json[] = "[{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}, \
        {\"sensor\":\"gps\",\"time\":1351824140,\"data\":[50.756080,21.302038]}]";

      JsonParser<32> parser;
      JsonArray root = parser.parse(json);

      if (!root.success()) {
        Serial.println("JsonParser.parse() failed");
        return;
      }

      for (JsonArrayIterator item = root.begin(); item != root.end(); ++item) {
        // unsure of what to do here.

        Serial.println((*item)["data"]);
        // results in:
        // ParseJsonArray:21: error: call of overloaded
        //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous

        JsonObject something = JsonObject(*item);
        Serial.println(something["sensor"]);
        // results in :
        // ParseJsonArray:26: error: call of overloaded
        //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous
      }
    }

    void loop() {}

item is of type JsonValue. I would like to treat it as a JsonObject and pull some data out of it.

title: Parsing JSON on the Arduino

Answers: 2

body:
Got it! Initially, casting the retrieval of the item from the JsonObject before printing was enough.

    JsonObject something = JsonObject(*item);
    Serial.println((char*)something["sensor"]);

Although, I think this looks better.

    char* sensor = (*item)["sensor"];
    Serial.println(sensor);

body:
This is how I would write this loop:

    for (JsonArrayIterator it = root.begin(); it != root.end(); ++it)
    {
      JsonObject row = *it;

      char*  sensor    = row["sensor"];
      long   time      = row["time"];
      double latitude  = row["data"][0];
      double longitude = row["data"][1];

      Serial.println(sensor);
      Serial.println(time);
      Serial.println(latitude, 6);
      Serial.println(longitude, 6);
    }

And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):

    for (auto row : root)
    {
      char*  sensor    = row["sensor"];
      long   time      = row["time"];
      double latitude  = row["data"][0];
      double longitude = row["data"][1];

      Serial.println(sensor);
      Serial.println(time);
      Serial.println(latitude, 6);
      Serial.println(longitude, 6);
    }


body:
I try to build custom controller and now searching for bluetooth hid module. Which BT HID module compatible with arduino? (not bluetooth serial)

List of some modules:

-  BlueSMiRF HID - from sparkfun, expensive (based on rn-42, also available RN-42-EK evaluation board) ✔ compatible
- HM-10 bluetooth module - around $10 (aliexpress), based on cc2540 ht
tp://www.ti.com/product/cc2540
- HC-05 Transceiver Module  - less $10, maybe supports HID after firmware upgrade(??)
- Bluegiga wt12
- Bluefruit EZ-HID from Adafruit ~$20 (suggested by [mwwalk][1]) ✔ compatible

Thanks

  [1]: https://arduino.stackexchange.com/a/3715/3332

title: Bluetooth HID module

Answers: 2

body: I'm not entirely sure from your question if you want just the module or a whole breakout board.  If the latter, try this from adafruit. It can very easily do his either as mouse or keyboard and is well documented and supported so I think this would be much easier to get running initially. http://www.adafruit.com/products/1535

body:
HC-05 HC-06 and, for example, RN-42 HID are the same looking on hardware design.

Only difference is in firmware.

For educational purposes you can dump firmware from RN42HID and flash HC-05/06 module and you've got a HID module.

The difference in costs of the HID modules is that CSR IDE costs $3000 per licence  + developer seat, and when someone invests in developing wants the incomes to come.

Byron's blog will guide you, you need a SPI programmer, but you can use Arduino as programmer/debugger. And you will need blueflash software to backup some info from Your module (calibration of crystal for example, and IDS/MAC/serial) than you can flash the RN firmware, and you have exact copy of RN, last thing is to restore the settings saved from your original firmware.

Just Google it, here is not much place to put all the data and images.

But yes it is possible.


body:
I am doing my CBT, and i need help...
I need a Webservice in C#, and it will send commands to my Arduino( Mega 2560 + Ehternet Shield )...
My Webservice will recibe commands from Android and Web

![][1]

**EDIT**

I wanna know what kind of C# WebService Project I have to create...

![enter image description here][2]

  [1]: https://i.stack.imgur.com/w6oUy.png
  [2]: https://i.stack.imgur.com/Qm2ax.png

title: Arduino + Web Service

Answers: 0


body:
I am wondering if its possible to program a board that is developed using SIM900 and GPS module to make http rest calls.

I found [this library][1]. My question is, will I need a microcontroller for this ?

  [1]: https://stackoverflow.com/questions/23842394/c-c-http-client-library-for-embedded-projects

title: SIM900 + GPS Module making http rest calls

Answers: 2

body:
> My question is, will I need a microcontroller for this ?

**Yes.** There are certain things that you need a "man in the middle" to control. Without a microcontroller, how will you tell it what site to visit? How often to send the HTTP request? How to format the HTTP request? Is there any other thing you need this to do?

People often hope that they can hook up two **complex** devices that are almost setup to be slaves (like shields, sensors, and outputs) to a microprocessor. Unless the two were specifically designed to work together (or they use a standard, very specific protocol), your chances of building this without a microchip is like trying to build a skyscraper with popsicle sticks. It's possible, but there are cheaper and much easier/more efficient ways to doing that.

*Well, they're both SPI/I2C/UART/USB/Serial! Why not?* Well, although we're all humans and we use verbal communication as a protocol, do we all understand each other? Not really... For those protocols, they're designed to have a "master" and a "slave." A master would be powerful and have control over all the slaves. Hooking a GSM and GPS shield together is like hooking two slave devices together. It's not going to work out (unless you're aiming for blue smoke...)

**tl;dr:** you trying to mix two things that don't mix. Buy an Arduino Nano clone for $8 and have your circuit actually work.

body:
I partially agree to [Anonymous Penguin's][1] answer.

But if you want go for a deep dive, actually SIM900 / SIM800 GSM modules also have a facility called Embedded AT. Just Google it using "SIM900 Embedded AT". They have a pdf [here][2] at the time of writing this.

According to this application note, SIM900 is actually ARM core and using Embedded AT you can utilize most of things you do in External MCU. So if you are thinking of some application, which can be developed into SIM900, Yes you can avoid using external MCU. You can give AT Commands from your application to SIM900 core using API. You even get 1 UART to interface GPS chip with SIM900. If you move to SIM800 family they have more UARTs.

PS: I haven't used it.

  [1]: https://arduino.stackexchange.com/a/3468/19127
  [2]: http://www.mt-system.ru/sites/default/files/sim900_embedded_at_application_note_v1.01.pdf


body:
I read the following online:
If you plug in both USB power (say from a pc) and external power via the 2.1mm jack, the Arduino chooses power source automatically.

If the external 2.1mm DC is providing greater than 6.6V, the Arduino will take power from it instead of the USB.

Firstly, is this accurate?

Secondly, my real question:
If I am powering my Arduino via external DC, can I still communicate with my Raspberry Pi using serial via the USB?

title: Can I use an external power supply and still communicate with my computer over Serial?

Answers: 1

body:
Yes you can. It still leaves the data/ground lines intact, it just doesn't bridge the 5V line.

[Arduino Uno Schematic v.3](http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf):

![][1]

The `USBVCC` is directly from the 5V on the USB jack (well, technically there's a fuse there). It then goes through a transistor (`T1`) that only allows power through when there is no power coming from the 5V regulator (that regulates the VIN voltage).

*The USB jack:*

![][2]

You can see pin 1 of the USB jack (5V) goes through the fuse to `USBVCC`. The next ones `D+`/`D-` are the data lines that go through resistors to the ATMEGA16U (used for USB to UART). The last one just ties into ground.

  [1]: https://i.stack.imgur.com/wVZoy.png
  [2]: https://i.stack.imgur.com/Ms8IE.png


body:
I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance.

***UPDATE***:

Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this [link][1]. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again.

**Arduino**

    #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14); //Serial.write(buf, len)
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        #ifdef OUTPUT_ACCEL_STR_RAW
            mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

            String accelGyroRaw = "STX,";
            accelGyroRaw += ax;
            accelGyroRaw += ',';
            accelGyroRaw += ay;
            accelGyroRaw += ',';
            accelGyroRaw += az;
            accelGyroRaw += ',';
            accelGyroRaw += gx;
            accelGyroRaw += ',';
            accelGyroRaw += gy;
            accelGyroRaw += ',';
            accelGyroRaw += gz;
            accelGyroRaw += ',';
            accelGyroRaw += "ETX";

            Serial.println(accelGyroRaw);

        #endif

**C# Code**

    class Program
    {
        static SerialPort port = new SerialPort("COM7", 115200);
        //static int serialCount = 0;
        //static int aligned = 0;
        //static char[] teapotPacket = new char[14];
        //static float[] q = new float[4];

        static void Main(string[] args)
        {

            Console.WriteLine("****** Serial Console Read ********");
            port.Open();
            port.DataReceived += port_DataReceived;

            Console.Read();
        }

        static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            string s = port.ReadLine();
            string[] accelGyroVals = s.Split(',');
            string[] accl = new string[3];
            string[] gyro = new string[3];

            if (accelGyroVals[0] == "STX" && accelGyroVals[accelGyroVals.Length - 1] == "ETX\r")
            {
                accl[0] = accelGyroVals[1];
                accl[1] = accelGyroVals[2];
                accl[2] = accelGyroVals[3];

                gyro[0] = accelGyroVals[4];
                gyro[1] = accelGyroVals[5];
                gyro[2] = accelGyroVals[6];

                Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]);
            }

        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            if (port.IsOpen)
            {
                port.Close();
            }
        }
    }

Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you.

  [1]: http://www.i2cdevlib.com/devices/mpu6050#source

title: Sending MPU6050 data over serial to Java/C# Program

Answers: 1

body:
You may find RXTX java library helpful.

You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values.

http://playground.arduino.cc/interfacing/java

Hope this helps


body:
I am using MPU6050 IMU for getting accelerometer and gyro data. I could read the data using the code from the [I2Cdev library][1] here, but the problem I have is that I can't use this data in a meaningful manner. As an example I want to define the motion of an object in x,y,z axis using accelerometer data. Although I get a set of values, I can't understand how to use it.

If I could convert these values to ms<sup>-2</sup> units, I hope I would be able to achieve this

Could you provide me some advice, code or reference to work on this?

I also tried the code [here][2] to get the raw values.

  [1]: http://www.i2cdevlib.com/devices/mpu6050#source
  [2]: http://playground.arduino.cc/Main/MPU-6050?action=sourceblock&num=1

title: Problem with interpretting and using the IMU data

Answers: 1

body:
You may want to take a look of freeimu library which take care of all needed processing and present filtered and data-fused data (not just raw data) in easy to use roll, pitch and yaw format.

http://www.varesano.net/projects/hardware/FreeIMU

see demo video in which the on screen data mirror physical motion of the sensor
http://www.youtube.com/watch?feature=player_embedded&v=rFvX3vZJHTQ

hope this helps


body:
I'm working with the Arduino Due ans I used the following code:

    // period of pulse accumulation and serial output, milliseconds
    #define MainPeriod 100
    long previousMillis = 0; // will store last time of the cycle end
    volatile unsigned long duration=0; // accumulates pulse width
    volatile unsigned int pulsecount=0;
    volatile unsigned long previousMicros=0;

    void setup()
    {
      Serial.begin(19200);
      attachInterrupt(6, myinthandler, RISING);
    }

    void loop()
    {
      unsigned long currentMillis = millis();
      if (currentMillis - previousMillis >= MainPeriod)
      {
        previousMillis = currentMillis;
        // need to bufferize to avoid glitches
        unsigned long _duration = duration;
        unsigned long _pulsecount = pulsecount;
        duration = 0; // clear counters
        pulsecount = 0;
        float Freq = 1e6 / float(_duration);
        Freq *= _pulsecount; // calculate F
        // output time and frequency data to RS232
        Serial.print(currentMillis);
        Serial.print(" "); // separator!
        Serial.print(Freq);
        Serial.print(" ");
        Serial.print(_pulsecount);
        Serial.print(" ");
        Serial.println(_duration);
      }
    }

    void myinthandler() // interrupt handler
    {
      unsigned long currentMicros = micros();
      duration += currentMicros - previousMicros;
      previousMicros = currentMicros;
      pulsecount++;
    }

to measure the frequency.

I can measure frequencies higher than 1.5kHz accurately, but I can't seem to measure lower frequencies.

How can I measure lower frequencies, say 400Hz and above?

Thanks.

title: Measure square wave frequency

Answers: 1

body:
It seems you have a problem of concurrent access to `duration` and `pulsecount` variables which are inter-related; with your code, it is possible that (and I guarantee that it will):

1. `loop()` reads `duration` value (in line `unsigned long _duration = _duration;`) but gets interrupted before executing the next line
2. `myinthandler()` changes both `duration` and `pulsecount` (it cannot be interrupted as it is already triggered by an interrupt)
3. `loop()` proceeds to where it was interrupted (after `myinthandler()` returns) and executes line `unsigned long _pulsecount = pulsecount;`: the values in `_duration` and `_pulsecount` do not match anymore!

To protect the access to `pulsecount` and `duration` variables, you have to disable interrupts inside `loop()` just for the time you get their values:

    void loop() {
        ...
        // Disable interrupts while we get and reset duration and pulsecount
        cli();
        unsigned long _duration = duration;
        unsigned long _pulsecount = pulsecount;
        duration = 0; // clear counters
        pulsecount = 0;
        // Now we can re-enable interrupts again
        sei();
        ...
    }

  [1]: http://arduino.stackexchange.com/questions/2947/if-statement-behaves-erratically/2958#2958


body:
I want to have a LED turn on when I push a button and go off when I push the button a second time.

This code doesn't work:

    const int buttonPin = 4;
    const int motorPin =  10;
    const int ledPin = 6;
     int x = 1;
    // variables will change:
    int buttonState = 0;

    void setup() {
      // initialize the LED pin as an output:
      pinMode(motorPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
    }

    void loop(){
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH && x==1) {
         digitalWrite(motorPin , 1);
         x=0;
        }
      if (buttonState == HIGH && x==0){
        digitalWrite(motorPin, 0);
        x=1;
      }
      delay(1);
    }

What could be wrong?

title: How to toggle LED on button press?

Answers: 10

body:
Don't forget to turn ON the LED:

 digitalWrite(ledPin, HIGH);
And OFF:

    digitalWrite(ledPin, LOW);

body: You are not handling debouncing at all. Mechanical buttons typically bounce for a few milliseconds after an "on" press. Arduino software (or some specialist hardware) needs to handle this. This really matters when you expect a button to toggle some output pin.

body:
At the moment, you've got two main problems. Firstly, both your `if` statements are being triggered one after the other. This is because the first `if` statement sets `x` to 0, which is part of the condition the second `if` statement looks for.

The second problem is that you're not monitoring the previous state of the button. `buttonState` will appear `HIGH` every time round loop, even if the button has been held down for several seconds. The result is that the output pin will be quickly getting turned on and off all the time.

What you need to do is store the last known state of the button. On every iteration of the main loop, only respond to the button if it's currently `HIGH`, *and* if it was `LOW` last time round the loop. You also need to make sure your two `if` statements are mutually exclusive; i.e. if you trigger one then don't trigger the other by mistake too, or it will cancel it out.

Something like this should work better:

<!-- language: cpp -->

    // This will store the last known state of the button
    int oldButtonState = LOW;

    void loop()
    {
      // Get the current state of the button
      int newButtonState = digitalRead(buttonPin);

      // Has the button gone high since we last read it?
      if (newButtonState == HIGH && oldButtonState == LOW) {

        if (x == 0) {
          // Toggle on
          digitalWrite(ledPin, HIGH);
          x = 1;

        } else {
          // Toggle off
          digitalWrite(ledPin, LOW);
          x = 0;
        }
      }

      // Store the button's state so we can tell if it's changed next time round
      oldButtonState = newButtonState;
    }

As noted elsewhere, you still need to debounce the button, otherwise you're likely to get some false-positives. That can be done in hardware or software. A really simple way to get around it temporarily is to put in a delay of several milliseconds every time you detect the button changing state. It's not perfect, but it might be enough to get you started.

body:
hello sachleen try this code it working I edited from your code

    // This will store the last known state of the button
    const int buttonPin = A15;   // change as per your button attached.
    const int motorPin =  12;   //
    const int ledPin = 13;
     int x = 1;
    // variables will change:
    int buttonState = 0;
    int oldButtonState = LOW;

    void setup() {
      // initialize the LED pin as an output:
      pinMode(motorPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
      // Get the current state of the button
      int newButtonState = digitalRead(buttonPin);

      // Has the button gone high since we last read it?
      if (newButtonState == HIGH && oldButtonState == LOW) {

        if (x == 0) {
          // Toggle on
          digitalWrite(ledPin, HIGH);
          x = 1;

        } else {
          // Toggle off
          digitalWrite(ledPin, LOW);
          x = 0;
        }
      }

      // Store the button's state so we can tell if it's changed next time round
      oldButtonState = newButtonState;
    }

body:
I just grabbed the version from the ones above here and made is somewhat smaller in terms of code. Feel free to use it in your Arduino app.

    // This will store the last known state of the button
    int lastButtonState = LOW;

    void loop()
    {
      // Get the current state of the button
      int currentButtonState = digitalRead(buttonPin);

      // Has the button gone high since we last read it?
      if (currentButtonState == HIGH && lastButtonState == LOW) {
         // Switch the state of the output
         digitalWrite(ledPin, !digitalRead(ledPin));
      }

      // Store the button's state so we can tell if it's changed next time round
      lastButtonState = currentButtonState;
    }

body:
Pinouts, pullups and logic errors have been addressed elsewhere, so I will focus on switch debouncing.  Debouncing, in my opinion, is best handled in software (rather than hardware) for large volume production costs and lazy programmers (like me).  For small projects a simple pullup / cap circuit offers better reliability and improved speed, but I'm just lazy in my old age.  Also keep in mind that switch bounce worsens significantly over the life of a switch.  I've seen new PB's with bounce < 20 ms worsen to over 300 ms with reasonable usage, so keep that in mind with projects that become semi-permanent.

Here's what I use for a software solution on a fairly bouncy SPST NO pushbutton. In this case, I'm using NO PB to GND with 1K external pullups, since I personally don't want to depend on whether or not the internal pullup still works on older devices I may have abused in a former life.... Of course, arguments could be made for various areas still needing cleanup, improved encapsulation, quicker response, higher quality, etc., but this works for me for now.

inSw.h:

    class inSw
    {
    private:
     volatile boolean swState;   // current state ( 0 / 1 ) of switch

    public:
     uint8_t  pinNum;
     volatile unsigned long lastPush; // Time (millis() ) when last switch push detected
     unsigned long debTime = 30;   // Time (micros() ) required to debounce switch

     void init(uint8_t sw);
     boolean readState(void);
    } ;
inSw.cpp:

    void inSw::init(uint8_t sw) {
     pinNum = sw;
     pinMode(sw, INPUT);
     swState = 0;
     lastPush = millis();
    };

    boolean inSw::readState() {
    // swState = digitalRead(pinNum);
 return swState;
    }
    void setupSwitches(void) {
     swS1.init(I2C_SOA);  // pin D20
     attachInterrupt(digitalPinToInterrupt(swS1.pinNum), swS1Press, FALLING);
    }

Interrupt Service Routines are placed outside Setup() and Loop(), with the attachInterrupt (above) called from inside Setup().  This allows the switch to break long-running routines, such as Stepper.step(10000) which bangs against the limit switch on step 14....

    void swS1Press() {
     unsigned long now = millis();
     if (swS1.lastPush < (now - swS1.debTime)) { // if newly pushed
      RunStop.toggle();
      swS1.lastPush = millis();  // sw last pushed now

      if (RunStop.val == RS_RUN)
       digitalWrite(LED_PIN, HIGH);   // set the LED on
      else
       digitalWrite(LED_PIN, LOW);   // set the LED off
     }
    }

Lastly, just remember to check the switch state at various points inside loop().  I use this switch as an emergency stop switch, and the onboard LED to ensure it triggers.

body:
    // When first time program launches it confused to press push button twice. Well replace it with this

    if (x == 1) {
        // Toggle on
        digitalWrite(ledPin, HIGH);
        x = 0;
    } else {
        // Toggle off
        digitalWrite(ledPin, LOW);
        x = 1;
    }

body:
You don't need a separate variable to store the state of the LED. The output pin register does that already. So you can toggle the LED simply with

        digitalWrite(ledPin, !digitalRead(ledPin));

or if you prefer

        if(digitalRead(ledPin))
           digitalWrite(ledPin, 0);
        else
           digitalWrite(ledPin, 1);

In you code the loop executes many times while the key is bouncing. If you delay by at least 50mS after the key press is first detected, and you have toggled the led and turned on the motor, then you have effectively debounced the button. If you hold the key down continously the led will toggle every 50mS (plus a little overhead)

body:
success case tested OK,modified from arduino examples.UNO r3,atmega 328
try it !!!!!

    /*  The circuit:
      - pushbutton attached to pin 2 from +5V
      - 10 kilohm resistor attached to pin 2 from ground
      - LED attached from pin 13 to ground (or use the built-in LED on most
        Arduino boards)
    */

    // this constant won't change:
    const int  buttonPin = 2;    // the pin that the pushbutton is attached to
    const int ledPin = 8;       // the pin that the LED is attached to

    // Variables will change:
    int buttonPushCounter = 0;   // counter for the number of button presses
    int buttonState = 0;         // current state of the button
    int lastButtonState = 0;     // previous state of the button

    void setup() {
      // initialize the button pin as a input:
      pinMode(buttonPin, INPUT);
      // initialize the LED as an output:
      pinMode(ledPin, OUTPUT);
      // initialize serial communication:
      Serial.begin(9600);
    }

    void loop() {
      // read the pushbutton input pin:
      buttonState = digitalRead(buttonPin);

      // compare the buttonState to its previous state
      if (buttonState != lastButtonState) {
        // if the state has changed, increment the counter
        if (buttonState == HIGH) {
          // if the current state is HIGH then the button went from off to on:
          buttonPushCounter++;
          Serial.println("on");
          Serial.print("number of button pushes: ");
          Serial.println(buttonPushCounter);
        } else {
          // if the current state is LOW then the button went from on to off:
          Serial.println("off");
        }
        // Delay a little bit to avoid bouncing
        delay(10);
      }
      // save the current state as the last state, for next time through the loop
      lastButtonState = buttonState;

      // turns on the LED every four button pushes by checking the modulo of the
      // button push counter. the modulo function gives you the remainder of the
      // division of two numbers:
      if (buttonPushCounter % 2 == 0) {
        digitalWrite(ledPin, LOW);
      } else {
        digitalWrite(ledPin, HIGH);
      }
    }

body:
check this code. I have made some changes in your code. its working.

    const int buttonPin = 2;
    const int motorPin =  6;
    const int ledPin = 13;
    int x = 1;
    // variables will change:
    int buttonState = 0;

    void setup() {
      // initialize the LED pin as an output:
      Serial.begin(9600);
      pinMode(motorPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);
    }

    void loop() {

      buttonState = digitalRead(buttonPin);
    //  Serial.println(x);
      if(buttonState == LOW && x == 1)
      {
        Serial.println("buttonState == HIGH && x == 1");
        digitalWrite(ledPin, HIGH);
        delay(500);
        x = 0;
        Serial.println("x == 0");
      }
      else if (buttonState == LOW && x == 0)
      {
        Serial.println("buttonState == HIGH && x == 0");
        digitalWrite(ledPin, LOW);
        delay(500);
        x = 1;
        Serial.println("x == 1");
      }
      delay(1);
    }


body: I am working on Fall Detection in humans. A system that would raise alarm when a person falls. For this I plan to use acceleration to see if it is a fall and orientation change to reduce false positives. I was trying to get angle of orientation using gyroscope,accelerometer and magnetometer. According to what I have googled I shouldn't use gyroscope alone as when we integrate to get angle the result is not accurate and I should use sensor fusion and filter using kalman filter or complementary filter. I can't use accelerometer  as during a fall the acceleration won't be only from gravity. I am a newbie so I don't know how to proceed. Correct me if I have understood anything wrong till now.

title: How can I implement sensor fusion using a gyroscope and a magnetometer to find the orientation?

Answers: 2

body:
Such system, some even has airbag, has been around in university/research/papers for many years.  Presumably, falling means a marked change in 'data values'. One can easily log some data (accel and gyro) by falling on bed and plot the values.

May you find some inspiration in followings

http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0CEMQFjAC&url=http://courses.daiict.ac.in/mod/resource/view.php?id=2430&redirect=1&ei=Ls_WU5-cOob_8QW3v4KoCA&usg=AFQjCNEDUyJKTNYFCi71rX13RMlxoHL8kg&bvm=bv.71778758,d.dGc

https://www.google.com/search?q=human+fall+detection+system&safe=off&tbm=vid&source=lnms&sa=X&ei=ps3WU6jGMYyE8gWxo4LYCA&ved=0CAoQ_AUoAw&biw=1577&bih=800&dpr=1#q=elderly+fall+detection+airbag&safe=off

Hope it helps

body:
The magnetometer will be very difficult to use because you have no idea what the local magnetic field will look like around the user.

The gyroscope can help you keep track of angular orientation data during accelerations, but unless you know exactly how this is going to be attached to the human it will not help because you cannot orient the relative angles to the subject. A person can fall with or without rotating in the air as well, so I don't see it helping much anyway.

Kalman filters are great, but overkill; you are not doing inertial navigation over long distances, so don't bother. Simple averaging will suffice.

The accelerometer should be able to detect falls by itself. The only way it will ever "Zero out" is in freefall, and if that zeroing is long enough and then followed by a very hard acceleration against the direction of gravity (the crash) you can call it a fall. Unless the person has some kind of engine to produce thrust, or is going so fast air resistance is a factor, there will be no accelerations in the air. Simplely calibrating of the threshold for being in freefall, the time necessary to call it a fall, and the necessary strength of the following crash should be able to detect falls or jumps with almost no false positives.

For instance if you want to track short falls where the object is never fully off the ground, a large dip in acceleration data will still be seen, so just set the "zero" threshold high.


body:
I am working on a human fall detection system using accelerometer and gyroscope which raises alarm in case of a fall. In all the papers I have read people have used net acceleration magnitude and compared it with a threshold and coupled it with change in orientation to detect fall. My question is would it be better to use acceleration in z-axis(normal to earth's surface) and compare it to threshold as compared to net acceleration as it might reduce false positives as net acceleration can exceed threshold in case of running but that won't happen if i take only acceleration in z-axis. Is my approach right?

https://arduino.stackexchange.com/questions/3480/how-can-i-implement-sensor-fusion-using-a-gyroscope-and-a-magnetometer-to-find-t

title: How do I proceed with a fall detection sensor?

Answers: 1

body: Find the derivative of acceleration over time, also known as **jerk**. Falling will have a specific jerk pattern, whereas normal shaking and banging will have a completely differrent pattern.


body:
I am currently trying to communicate between 3 Arduinos using I2C. One of them acts as a master, while the rest act as slaves.

I can request data correctly from the master. But if I were to do 2 consecutive requests, I will only get data for the last request. Please assist.

Master:

    #include <Wire.h>

    #define BLUNO_SLAVE 0x09
    #define BLUNO_SLAVE_2 0X0A

    void setup() {
      Serial.begin(115200);
      Wire.begin();
      Serial.println("Initialized as Master");
      Serial.println("Reading from slave 1 now..");
      //Wire.beginTransmission(BLUNO_SLAVE);
      Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
      //Wire.endTransmission();
      Serial.println("Reading from slave 2 now..");
      Wire.requestFrom(BLUNO_SLAVE_2, 30);
    }

    void loop () {
      while(Wire.available()) {
        char c = Wire.read();
        Serial.print(c);
      }
    }

Slave 1:

    #include <Wire.h>

    void setup() {
      Serial.begin(115200);
      Wire.begin(0x09);  //slave address
      Serial.println("Serials initialized");
    }

    void loop() {
      Wire.onRequest(returnData);
    }

    void returnData() {
      Wire.write("received master's request");
    }

Slave 2:

    #include <Wire.h>

    void setup() {
      Serial.begin(115200);
      Wire.begin(0x0A);  //slave address
      Serial.println("initialized!");
    }

    void loop() {
      Wire.onRequest(returnData);
    }

    void returnData() {
      delay(60000);  //60 * 1000 = 60 seconds
      Wire.write("Lat: 103.123456, Lon: 1.098765");
    }

Output on the master:

    Initialized as Master
    Reading from slave 1 now..
    Reading from slave 2 now..
    Lat: 103.123456, Lon: 1.098765

On top of that, I do not understand why the 1 minute delay was not executed before the slaves write the GPS coordinates.

I figured out from http://playground.arduino.cc/Main/WireLibraryDetailedReference
that each call to the `requestFrom()` method, RESETS the read buffer. I looked at my code back and I saw a silly mistake on the master code. So, I corrected the master code:

    #include <Wire.h>

    #define BLUNO_SLAVE 0x09
    #define BLUNO_SLAVE_2 0X0A

    void setup() {
      Serial.begin(115200);
      Wire.begin();
      Serial.println("Initialized as Master");
      Serial.print("Slave 1: ");
      Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
      readData();
      //each call to requestFrom, RESETs the read buffer index
      Serial.println();
      Serial.print("Slave 2: ");
      Wire.requestFrom(BLUNO_SLAVE_2, 30);
      readData();
    }

    void loop () {
    }

    void readData () {
      while(Wire.available()) {
      char c = Wire.read();
      Serial.print(c);
     }
    }

But still, I don't understand why slave2 writes the data immediately instead of waiting for 1 minute?

title: Cannot read from 2 I2C slaves consecutively

Answers: 1

body:
I recommend you to just set a semaphore inside your handler. When your handler is called, set it, nothing more. In your main loop, poll for this semaphore and do your communication when true. When you receive this semaphore you can easily wait as long as you like without breaking interrupt handling. As interrupt service routines should always be as short as possible, both in terms of time and code, it is generally a bad idea to do complex communication from within or wait for something.

And don't forget the "volatile" keyword for your semaphore.


body:
I am using atmega 328pu instead of atmega328p-pu. I am trying to upload the bootloader using AVR pocket programmer.

I have changed signature from `0x1e 0×95 0x0F` to `0x1e 0×95 0×14`.

*([Relevant link][1])*

    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

![circuit diagram][2]![error report][3]

  [1]: http://www.crash-bang.com/resource/bootload-atmega328/
  [2]: https://i.stack.imgur.com/j3vxm.jpg
  [3]: https://i.stack.imgur.com/Mw3Zl.jpg

title: arduino boot loader problem

Answers: 3

body:
> (Note for the Arduino Uno: you'll need to add a 10 uF capacitor
> between reset and ground.)

From http://arduino.cc/en/Tutorial/ArduinoISP

body:
It sounds as if you are using the Arduino IDE to "Upload using Programmer". If so; in the preferences enable Verbose output for upload. From this you should see all of the avrdude output. Not just the error message. Hopefully with this you will see signature of the chip you actually read. You will also see the full and exact avrdude.exe command that is being executed. Note the path/filename of the avrdude.conf, to ensure it is the one you changed.

Using this you can attempt it manually, and tweak it. Try adding the -F to it. Or execute the equivalent to :

    avrdude -b 19200 -p atmega644p -C avrdude.conf -c stk500v1 -P COM4 -n

where the "-n" is "Do not write anything to the device." just read the signature.

I prefer to use a GUI in front of avrdude. [Yuki's GUI](http://translate.google.com/translate?hl=en&sl=ja&u=http://yuki-lab.jp/hw/avrdude-GUI/&prev=/search?q=avrdude+gui+yuki+lab&client=firefox-a&hs=YOU&rls=org.mozilla:en-US:official&channel=sb) is a good example. Just need to point it to the EXE and have a copy of the conf file in the same directory.

----------

I should mention the Arduino way of doing this, is to create a new boards.txt file with this chip and add (not change) the avrdude.conf file. This will allow programing either from selecting the correct board. but that is another subject.

body:
This sounds like the programmer is not seeing the ATMega328 MCU, or the Arduino IDE is not seeing the programmer. Changing the signature won't be of any help as the IDE (or AVRDude) is not seeing the ATmega328.

I would suggest that you double-check your connections, and set the options in the IDE to verbose output - then repost the info here.


body:
I am really interested in IoT (enthusiastic noob) and I would like to use the arduino board. Here are the steps according to me, with my queries:

 - User goes to example.com/arduino_switch
 - Interacts with an HTML form to toggle an action
 - Sends the data over the Internet (This is the part I have problem understanding)
 - Arduino receives the data point (how can we do this? polling a url or can we actively send it)
 - performs the action (easy to do for me)

Any and all help will be appreciated, even if its just pointing me to the right resources.

title: Arduino Control over the internet

Answers: 2

body:
You have two choices:

 1. The Arduino regularly communicates with an external web server, sending data and asking if there is anything to do. This is the way Mitsubishi heatpumps can be controlled from the web. The advantage is that your internet connection does not need to publish a web server. Drawback is that the communication is slow (being dependent on the polling interval), plus the need for a web server to talk to. For instance, to control your Mitsubishi heatpump, you need to create an account on one of their servers for the purpose.
 2. The Arduino exposes a web interface that is then exposed to the internet. This needs configuration of your internet router and preferably a static IP address on the internet. Security is a problem, and I'm not sure that even the Due can do HTTPS plus some form of authentication. I used this method, but fronted my Arduino with an old laptop running Linux and Apache web server. The laptop does the authentication and HTTPS processing. Advantage is near real-time control; disadvantage is the amount of hardware and configuration required.

body:
kiwiron has a great answer, but I have a few things to add:

 - **You don't have to risk security...** you can create a VPN to your network *or* you could just stay inside local LAN. It's just if you want to access it from outside
 - If you can't get a static IP for your network from your ISP, you can use something like [No-IP](http://www.noip.com/) to give you a name like `example.no-ip.biz` that's easier to remember and it will change the IP when your IP changes. I've used them before...
 - A Raspberry Pi might be a good partner in crime to work with the HTTPS connection with a web server like Nginx and with PHP to run a script. I personally like the Arduino better for interfacing with the actual components since it is 5V and has 40 mA per pin, but it's possible that you could use the GPIO pins on a Pi for your server. This might be a little cheaper since you can remove the ethernet shield and replace that with USB.
 - For the approach of polling a web server, it might be better to have the web server send a GET request to the Arduino and then the Arduino can respond ASAP.

For this, you might want to learn the basics of [HTTP headers](http://en.wikipedia.org/wiki/List_of_HTTP_header_fields) and try to figure out what goes on behind the scenes.

> (how can we do this? polling a url or can we actively send it)

Assuming you're using the Arduino directly, here's roughly what would happen:

 - The client would request the Arduino for the content for the homepage using HTTP requests
 - The Arduino would send the content and close the connection
 - In the HTML there's a little attribute to the form that tells it to send the data via post to `response.php`. The client hits "submit" and it sends the data via POST to that URL.
 - The Arduino sees that it's sending data to that URL and reads the data and then process it accordingly. The socket is closed.


body:
I bought a CC3000 Wifi Shield from Sparkfun and attached it to Arduino Uno board.

As first thing I tested the board with the board test example:

> SparkFun CC3000 - Board Test

> CC3000 initialization complete

> Firmware version: 1.24

> MAC address: 70:FF:76:01:30:1E

> Finished board test

---

Then I scanned the networks:
> SparkFun CC3000 - Scan Test

> CC3000 initialization complete

> Scanning APs. Waiting for scan to complete.

> Access Points found:

> SSID: dnhm MAC address: 20:AA:4B:08:AA:CC RSSI: 58 Security: WPA2

> SSID: dnhm-guest MAC address: 20:AA:4B:08:AA:CE RSSI: 58 Security: Unsecured

> Finished scan test

---

I set the SSID and the password and tried to connect:

> SparkFun CC3000 - Connection Test

> CC3000 initialization complete

> Connecting to: dnhm

> Error: Could not connect to AP

> Error: Could not obtain connection details

> Error: Could not disconnect from network Finished connection test

---

> SparkFun CC3000 - Connection Test

> CC3000 initialization complete Connecting to: dnhm-guest

> Error: Could not connect to AP

> Error: Could not obtain connection details

> Error: Could not disconnect from network

> Finished connection test

It did not connect none of the available connections, I reserved an IP address on the router for the mac address, but nothing changed.

I turned on logs on the router (Linksys e2500) and nothing appeared in logs as if the device never tried to connect. (I can see relevant logs when I re-connect with my notebook)

I use wpa2 so I kept the security setting as it is. I also have a 5ghz SSID and it does not show up in the scan. So I did not try to connect to it.

I also tried the smart config example with my ipad and it did not work either, the output:

> SparkFun CC3000 - SmartConfig

> CC3000 initialization complete

> Starting SmartConfig

> Send connection details from app now!

> Waiting to connect…

> Error: Could not connect with SmartConfig

> Error: Could not obtain connection details

> Looking up IP address of: www.sparkfun.com

> Error: Could not lookup host by name

> Pinging 0.0.0.0 3 times…

> Error: no ping response

> Error: Could not disconnect from network

> Finished SmartConfig test

Obviously the board works (It can scan/find the networks), but cant connect them. What should I do as next step to troubleshoot the issue?

Here is the sample I used for connection testing: (I double checked the protocol from router's wifi settings to make sure I'm using the correct one)

     /****************************************************************
 ConnectionTest.ino
 CC3000 Connection Test
 Shawn Hymel @ SparkFun Electronics
 January 30, 2014
 https://github.com/sparkfun/SFE_CC3000_Library

 Connects to the access point given by the SSID and password and
 waits for a DHCP-assigned IP address. To use a static IP
 address, change the #define USE_DHCP from 1 to 0 and assign an
 IP address to static_ip_addr in the Constants section.

 NOTE: Static IP is not working at this time.

 The security mode is defined by one of the following:
 WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA, WLAN_SEC_WPA2

 Hardware Connections:

  Uno Pin    CC3000 Board    Function

  +5V        VCC or +5V      5V
  GND        GND             GND
  2          INT             Interrupt
  7          EN              WiFi Enable
  10         CS              SPI Chip Select
  11         MOSI            SPI MOSI
  12         MISO            SPI MISO
  13         SCK             SPI Clock

 Resources:
 Include SPI.h and SFE_CC3000.h

 Development environment specifics:
 Written in Arduino 1.0.5
 Tested with Arduino UNO R3

 This code is beerware; if you see me (or any other SparkFun
 employee) at the local, and you've found our code helpful, please
 buy us a round!

 Distributed as-is; no warranty is given.
 ****************************************************************/

 #include <SPI.h>
 #include <SFE_CC3000.h>

 // Pins
 #define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
 #define CC3000_EN       7   // Can be any digital pin
 #define CC3000_CS       10  // Preferred is pin 10 on Uno

 // IP address assignment method
 #define USE_DHCP        1   // 0 = static IP, 1 = DHCP

 // Connection info data lengths
 #define IP_ADDR_LEN     4   // Length of IP address in bytes
 #define MAC_ADDR_LEN    6   // Length of MAC address in bytes

 // Constants
 char ap_ssid[] = "SSID";                  // SSID of network
 char ap_password[] = "PASSWORD";          // Password of network
 unsigned int ap_security = WLAN_SEC_WPA2; // Security of network
 unsigned int timeout = 30000;             // Milliseconds
 //const char static_ip_addr[] = "0.0.0.0";

 // Global Variables
 SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

 void setup() {

  ConnectionInfo connection_info;
  int i;

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("---------------------------------");
  Serial.println("SparkFun CC3000 - Connection Test");
  Serial.println("---------------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
   Serial.println("CC3000 initialization complete");
  } else {
   Serial.println("Something went wrong during CC3000 init!");
  }

 #if (USE_DHCP == 1)
  // Connect using DHCP
  Serial.print("Connecting to: ");
  Serial.println(ap_ssid);
  if(!wifi.connect(ap_ssid, ap_security, ap_password, timeout)) {
   Serial.println("Error: Could not connect to AP");
  }
 #elif (USE_DHCP == 0)
  // Connect using static IP
  // ***TODO: Connect using static IP
 #endif

  // Print out connection details
  if( !wifi.getConnectionInfo(connection_info) ) {
   Serial.println("Error: Could not obtain connection details");
  } else {
   Serial.println("Connected!");
   Serial.println();

   // Print MAC address
   Serial.print("CC3000 MAC Address: ");
   for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
    if ( connection_info.mac_address[i] < 0x10 ) {
     Serial.print("0");
    }
    Serial.print(connection_info.mac_address[i], HEX);
    if ( i < MAC_ADDR_LEN - 1 ) {
     Serial.print(":");
    }
   }
   Serial.println();

   // Print IP Address
   Serial.print("IP Address: ");
   printIPAddr(connection_info.ip_address);
   Serial.println();

   // Print subnet mask
   Serial.print("Subnet Mask: ");
   printIPAddr(connection_info.subnet_mask);
   Serial.println();

   // Print default gateway
   Serial.print("Default Gateway: ");
   printIPAddr(connection_info.default_gateway);
   Serial.println();

   // Print DHCP server address
   Serial.print("DHCP Server: ");
   printIPAddr(connection_info.dhcp_server);
   Serial.println();

   // Print DNS server address
   Serial.print("DNS Server: ");
   printIPAddr(connection_info.dns_server);
   Serial.println();

   // Print SSID
   Serial.print("SSID: ");
   Serial.println(connection_info.ssid);
   Serial.println();
  }

  // Disconnect
  if ( wifi.disconnect() ) {
   Serial.println("Disconnected");
  } else {
   Serial.println("Error: Could not disconnect from network");
  }

  // Done!
  Serial.println("Finished connection test");

 }

 void loop() {

  // Do nothing
  delay(1000);

 }

 // Print out an IP Address in human-readable format
 void printIPAddr(unsigned char ip_addr[]) {
  int i;

  for (i = 0; i < IP_ADDR_LEN; i++) {
   Serial.print(ip_addr[i]);
   if ( i < IP_ADDR_LEN - 1 ) {
    Serial.print(".");
   }
  }
 }

title: Connection issues with TI CC3000 & Arduino Uno

Answers: 0


body:
I am working with Arduino and Android. I am interested in connecting Arduino (Mega 2560 ADK) to my Android tablet (Nexus 7) wirelessly. The chepaest option is via bluetooth but the communication in not reliable. Now I would like to connect it via WiFi. But I don't want to use WiFi shield on my Arduino.

As Arduino can send the information to my laptop via serial USB connection will it be possible to put this information on my home WiFi network and get it on my Android device by connecting it to the same WiFi network?

title: Connecting Arduino Android Wirelessy

Answers: 1

body:
Yes, if the laptop and tablet are on the same network communication will be possible. One way to implement this would be to have a client/server setup that communicates over TCP/IP.

The laptop can act as a TCP/IP server and also communicate through the serial interface to your arduino. Many languages will be able to do this, Java, C/C++, Python, whatever you're comfortable with.

The android tablet can then connect to the TCP/IP server as a client and send and receive data through your WiFi. Have a look at [the android documentation][1].

This would a simple solution but for a more permanent solution you could also setup a web server on your laptop, look into the apache webserver. Your tablet would be able to communicate with the web server through http requests. The web server can then start further scripts to send data to the arduino or maintain a serial connection depending on your implementation.

  [1]: http://developer.android.com/reference/java/net/Socket.html


body:
I am trying to communicate with my Arduino Duemilanove via an RS232 cord. I simply want to be able to send a byte (or char) to my Arduino from a desktop application.  The Arduino is plugging into USB COM5 on my computer.  I have the RS232 plugged into COM1, and then I have pins 2, 3 and 5 on the other end of the RS232 connected to Arduino pins TX, RX, and GND, respectively.

I found a serial comm class for C++ at the following link: [Arduino and C++ (for Windows)][1]

I have added the .h and .cpp files from the above example as `Serial.h` and `Serial.cpp` (I think the example uses `SerialClass.h` and `SerialClass.cpp`, I just changes the names).

-----------------------------

On my Arduino, I have the following code running:

    // ARDUINO
    char incomingByte = 0;

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

    void loop() {

            // send data only when you receive data:
            if (Serial.available() > 0) {
                    // read the incoming byte:
                    incomingByte = Serial.read();

                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incomingByte, HEX);
            }
    }

----------------------------------

And my C++ program is the following:

    // C++
    #include <iostream>
    #include <Windows.h>
    #include "Serial.h"

    using namespace std;

    int main(void)
    {
     Serial port("COM1");

     char* msg = "Hello Arduino!";
     int msgLen = strlen(msg);
     bool writeSuccess = port.WriteData(msg, msgLen);

     cout << "\n\n";
     system("PAUSE");
    }

-----------------------------

When I use the Arduino's serial port viewer to see what is bring printed, I'm getting very strange values that don't match what I'm sending (as far as I can tell).

When I send "Hello Arduino!", the arduino prints the following:

    I received: FFFFFFAB
    I received: 3A
    I received: 3A
    I received: A
    I received: FFFFFFFA
    I received: FFFFFFEB
    I received: 6D
    I received: 37
    I received: 15
    I received: 2D
    I received: 23
    I received: 21
    I received: FFFFFFBD
    I received: 0

This does not appear to be the correct hex for "Hello Arduino!", but I have no idea why it's not correct.  Does anyone have any clue what I'm doing wrong?

  [1]: http://playground.arduino.cc/Interfacing/CPPWindows

title: Serial communication between PC and Arduino via RS232 using C++

Answers: 2

body:
You need some voltage converter between arduino and pc. PC uses "real" RS232 and arduino uses TTL level RS232. Check more in this [site][1]. You need something like this [RS232 to TTL][2].

  [1]: https://www.sparkfun.com/tutorials/215
  [2]: https://thepihut.com/products/max202-rs232-to-ttl-converter-for-arduino?utm_medium=cpc&utm_source=googlepla&variant=27740639121&gclid=CjwKEAjw387JBRDPtJePvOej8kASJADkV9TLrvFCR1ojUcDxoG2ovz9obF6ZOuv5A-CZ9-VrwkPmjRoCkLvw_wcB

body:
It because that in your c++ application you haven't explicitly mentioned serial port speed.
Mention the same baudrate which you have used in arduino here(c++).

Assuming that you have used rs232 to ttl converter, as you are getting some output,
Which in other case wouldn't as you would have already burned your mcu.


body:
Background:

I have been working on an exoskeleton project with a group of friends, and I need help.  I made another post on the robotics.stackexchange site for the drive system: https://robotics.stackexchange.com/questions/4323/exoskeleton-drive-system-help.  You can also check out our first prototype on youtube: https://www.youtube.com/watch?v=NL_aCwJSRiE&feature=youtu.be

The device is going to be controlled by an iPad that we created via bluetooth.  We are using the adafruit bluefruitLE

We are attempting to control 4 motors (2 knee motors and 2 hip motors) from an Arduino Mega.  We will be using 2 Roboclaw 2x60A motor controllers.  We are trying to get the motors to mimic the graph (see attached).
![Gait Graph][1]

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

The graph is in degrees per percent cycle (a gait cycle).  We are using 50 gait cycles per minute for tests but we hope to make it adjustable.
We can change percent cycle to time in milliseconds using dimensional analysis (ie) 50 cycles/min = 8.333x10^-4 cycles/ms  —->  1/8.333x10^-4 cycles/ms is approx. 1200 ms/cycle.  So if you multiply the cycle times 1200 you get millisecond for a certain percent of the cycle (ie) 0.5cycles(50 percent of cycle) * 1200ms/cycle = 600 ms.

We will have a position feedback system incorporated in the drive system but because it is a prototype and I wanted to make the code as versatile as posible I created a function: getDegrees(int jointNum), so if I change the position feedback system I only have to change the getDegrees method.

In order to mimic the graph we broke the graph up into sections.  Each section represents a different velocity.  We are going to run a correction algorithm so far we have just done the P in PID, we have used a modifier of 1.5.  Then we saved the value that the section ended on so next gait cycle when it runs that section the algorithm will start off closer to the target value.

My question:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.  While the device is running we need to be able to constantly check for a bluetooth message from the iPad.  The bluetooth messages come in via SPI from the adafruit bluefruitLE.

What I have done so far:

I have been able to run a single joint by using a while statement (ie)

    int i = 0;
    void loop(){
    targetAngle = nextAngle[i]; //nextAngle is an array of points so nextAngle[0] through nextAngle[1] represents one section of the graph.
    i++
    if (getDegrees(1)< targetAngle){
 double deg = getDegrees(1);
 while (deg<targetAngle){
 /*
 *
 *Execute drive code
 *
 */
 deg = getDegrees(1);
    }else{
 double deg = getDegrees(1);
 while (deg>targetAngle){
 /*
 *
 *Execute drive code
 *
 */
 deg = getDegrees(1);
    }
    }
    }
The main problem with that code is its like using the delay() function instead of millis() is that it stops the program while its executing the code, and I cannot run multiple motors and check for bluetooth messages.

Major Challenges:

The drive commands must be based off of angle and not time.  It is ok if we tell it do 50 cycles per minute and it does 52 or 48 but its not okay if it only does 97% of the motion.

Possible solutions I have come up:

Using one arduino for each joint, and making them all slaves of a master arduino and the master arduino would act as the middle man sort of between the joints, making sure that they are synced up.  That way each arduino could use code similar to what I have already tried and confirmed to work.  But I would prefer to run it all from one arduino.

Conclusion:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.

Is this the right forum for this question?  Or is it more of a Stack Overflow or Robotics question?

Any help will be greatly appreciated,

--
Joel

title: Exoskeleton Motor Control Code

Answers: 2

body:
Here's what I came up with:

 - You have a certain percent of the gain cycle equal one "step" (step may be a bad term in this situation, but I'm using it because of stepper motors).
 - You have a **blocking** function that will move the motors and control all the P(ID) logic
  - Before this function is called, the main code will use a variable to store the desired time to do the next "step."
  - It will have a loop with "substeps." So it would look kinda like this:

<!--Here for pesky editor :D-->

    void function nextStep(int var1, int var2) {
        //Read sensors and put into variables
        until(condition == true) { //Condition to see if the motors are at the right degree
            //Adjust motors not in the right place
            delayAndCheckBT(10); //Look at the bottom for this function
        }
    }

You could also have it accept a few percent of variance as tolerance so it's not shakey, but that's more of the PID control than anything. You'll have to make sure that many 'steps' doesn't make the PID controller unstable.

 - When that code is done, the main function will check to see if the desired time for the next step has passed (or if it's now). If it's passed/now, then it will execute. Otherwise, it will not execute the next step and continue executing the main loop.

Great? No. The problem is you need to check for bluetooth! To do this, I've made two functions:

    void checkBT() {
        //Checks BT. Make sure this is non blocking: if you need to, set a few global variables
        //Note this code will get called a LOT, so don't implement any delays or loops: inside here: use millis().
    }
    void delayAndCheckBT(int timeToWait) {
        unsigned long finishTime = millis() + timeToWait;
        while (millis()<finishTime) {
            checkBT();
        }
    }

body:
As your question "to sync the movement of the 4 joints while running a correction algorithm on each joint individually."

**Referring to the first part of your question**, **sync** the movement, assume your are doing this at either commercial or university project level, **popular practice** is to use 'hard real time preemptive operating system".

RTOS, real time operating system, is a piece of system software that coordinates execution of your multi thread user software at **precise and predictable** time accuracy in order of millisecond.

RTOS involve money and learning time. You may want to continue using the simpler system that you already having now and work in just one joint, hence, no issue of syncing multiple joints. Once you reach some maturity on single joint, then, expand to syncing 4 joints.

RTOS can be commercial with full support or free of charge. Some are dual mode. Same software may either be free or if you choose, can buy commercial full support. There are simple and full-scale implementations where functionality, complexity, learning time and software cost (commercial  or free) varies by huge extend. You will then be more able to choose when you done the above single joint system.

Introduction http://en.wikipedia.org/wiki/RTOS

There are also real time 'executive' (smaller and less functions). For example, ucos II (older and simple version) is used by many people.

Hope it helps


body:
I'm new to the Arduino Yun and I'm trying to convert a sketch written for the Arduino Uno with a Ethernet Shield. The sketch does HTTP posts to Azure Mobile Services.

I've added in the `Bridge.h` and `YunClient.h` libraries in place of the `Ethernet.h` one for the Uno.

My modified sketch compiles, however, I don't think the http posts are working. I don't see my table updating in Azure.
<!-- language-all: lang-cpp -->
    /*
    ** This sample Arduino sketch uploads telemetry data to Azure Mobile Services
    ** See the full article here: http://hypernephelist.com/2014/07/11/arduino-uno-azure-mobile-services.html
    **
    ** Thomas Conté @tomconte
    */

    #include <Bridge.h>
    #include <YunClient.h>
    //#include <Ethernet.h> // removed as not used by Yun
    #include <SPI.h>

    // not sure if these libraries are required?
    #include <HttpClient.h>
    #include <Process.h>

    // Ethernet shield MAC address (sticker in the back)
    //byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    // 90:A2:DA:F8:28:38

    // Azure Mobile Service address
    // You can find this in your service dashboard
    const char *server = "myhost.azure-mobile.net";

    // Azure Mobile Service table name
    // The name of the table you created
    const char *table_name = "my_data";

    // Azure Mobile Service Application Key
    // You can find this key in the 'Manage Keys' menu on the dashboard
    const char *ams_key = "HJRxFXXXXXXXXXXXXXXXXXXXNQoMcXXXXXXx99";

    //EthernetClient client;
    YunClient client;

    char buffer[64];

    /*
    ** Send an HTTP POST request to the Azure Mobile Service data API
    */

    void send_request(int value)
    {
      Serial.println("\nconnecting...");

        Serial.print("sending ");
        Serial.println(value);

        // POST URI
        sprintf(buffer, "POST /tables/%s HTTP/1.1", table_name);
        client.println(buffer);

        // Host header
        sprintf(buffer, "Host: %s", server);
        client.println(buffer);

        // Azure Mobile Services application key
        sprintf(buffer, "X-ZUMO-APPLICATION: %s", ams_key);
        client.println(buffer);

        // JSON content type
        client.println("Content-Type: application/json");

        // POST body
        sprintf(buffer, "{\"value\": %d}", value);

        // Content length
        client.print("Content-Length: ");
        client.println(strlen(buffer));

        // End of headers
        client.println();

        // Request body
        client.println(buffer);

    }

    /*
    ** Wait for response
    */

    void wait_response()
    {
      while (!client.available()) {
        if (!client.connected()) {
          return;
        }
      }
    }

    /*
    ** Read the response and dump to serial
    */

    void read_response()
    {
      bool print = true;

      while (client.available()) {
        char c = client.read();
        // Print only until the first carriage return
        if (c == '\n')
          print = false;
        if (print)
          Serial.print(c);
      }
    }

    /*
    ** Close the connection
    */

    void end_request()
    {
      client.stop();
    }

    /*
    ** Arduino Setup
    */

    void setup()
    {
    Serial.begin(9600);
    Serial.println("Starting Bridge");
    Bridge.begin();

    }

    /*
    ** Arduino Loop
    */

    void loop()
    {
      int val = analogRead(A0);

      send_request(val);
      wait_response();
      read_response();
      end_request();

      delay(1000);
    }

title: Converting Arduino Uno with Ethernet Shield sketch for Arduino Yún

Answers: 1

body:
(Updating answer from comments.)

The OP answered their own question, they missed the code to connect to the web service

 `if (client.connect(server, 80))`


body:
The arduino website states that the operating voltage of an arduino is 7-12V.

Why does the arduino work powered on just usb then? As usb only outputs 5V and 500ma.

Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?

title: Why does arduino work on usb power?

Answers: 1

body:
> The arduino website states that the operating voltage of an arduino is 7-12V.

That's when it goes through the voltage regulator. It's a *linear regulator*, meaning it wastes a lot of power as heat. The regulator outputs 5V that's given to the MCU. The USB voltage bypasses the regulator and goes to a fuse before going to the common 5V for the board. If less than 7V is given to the regulator, it will produce less than 5V.

> Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?

Usually, yes. A 9V supply would give you more than 500ma, giving you flexibility to add higher current components like motors and lots of LEDs. It will make no difference if you have a single LED connected.


body:
I am using below sensor (accelerometer) .My application is a solar tracker, where I wanted to convert the sensor output into +70° to -70° format.

My question is how can I convert the angle?

    #define ADC_ref 2.56
    #define zero_x 1.569
    #define zero_y 1.569
    #define zero_z 1.569
    #define sensitivity_x 0.3
    #define sensitivity_y 0.3
    #define sensitivity_z 0.3

    unsigned int value_x;
    unsigned int value_y;
    unsigned int value_z;

    float xv;
    float yv;
    float zv;

    float angle_x;
    float angle_y;
    float angle_z;

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

    void loop() {
      value_x = analogRead(A0);

    //  value_y = analogRead(A1);
      //value_z = analogRead(A2);

      Serial.print("voltage  of x");
      Serial.println(value_x);
      /*Serial.print("voltage  of y");
       Serial.println(value_y);
       Serial.print("voltage  of z");
       Serial.println(value_z);
       */
      //xv=(value_x/1024.0*2.5)/sensitivity_x;
    /*  zv=(value_z/1024.0*ADC_ref-zero_z)/sensitivity_z;
      yv=(value_y/1024.0*ADC_ref-zero_y)/sensitivity_y;
      xv=(0.0032226562499999998*value_x)/sensitivity_x;
      angle_x =atan2(-yv,-zv)*57.2957795+90;

      Serial.print ("x= ");
      Serial.println (xv);
      Serial.print("x_degree= ");
      Serial.print(angle_x);
      Serial.println(" deg");

      /*Serial.print(" g ");

       Serial.print ("y= ");
       Serial.print (yv);
       Serial.print(" g ");

       Serial.print ("z= ");
       Serial.print (zv);
       Serial.print(" g ");

       Serial.print("\n");

       Serial.print("Rotation ");

       Serial.print("x= ");

       angle_x =atan2(-yv,-zv)*57.2957795+180;

       Serial.print(angle_x);
       Serial.print(" deg");
       Serial.print(" ");

       Serial.print("y= ");

       angle_y =atan2(-xv,-zv)*57.2957795+180;

       Serial.print(angle_y);
       Serial.print(" deg");
       Serial.print(" ");

       Serial.print("z= ");

       angle_z =atan2(-yv,-xv)*57.2957795+180;

       Serial.print(angle_z);
       Serial.print(" deg");
       Serial.print("\n");
       */
      delay(1000);
      //delay(1000);
    }

 - [Description][1]

 - [Datasheet of ADXL335][2]

  [1]: http://www.ebay.in/itm/ADXL335-analog-3-axis-Accelerometer-Module-For-Arduino-MEGA-AVR-PIC-Etc-/331259252773?pt=LH_DefaultDomain_203&hash=item4d20971025&_uhb=1
  [2]: https://www.sparkfun.com/datasheets/Components/SMD/adxl335.pdf

I have inclinometer off the shelf its Vout is 0~5 V and angle measure from -70° to 70°, and I calculated as below.

    void calcPos()
    {
      Sensor_Value=analogRead(A3);
      voltage = Sensor_Value * ARDUINO_ANALOG_SCALING;
      tracker_actual_pos=(30*voltage)-75;
    }

title: Analog angle conversion from +70° to -70°

Answers: 1

body:
So atan2(y,x) gives the angle CCW from the x axis in radians, limited to [-pi,pi].

If you want it converted to degrees CW from the Y axis, you would do

    azimuth=90.0-atan2(y,x)*57.295779;

If you need to constrain it to -70,70 then:

    azimuth_constrained=constrain(azimuth,-70,70);


body: It's kind of hard to get full guide from the internet. I just wanna buy a book for UAV guide. I gotta make DIY drones. I'd appreciat it if you recommend good books.

title: Can anyone tell me the best books for studying UAV?

Answers: 1

body:
Not a book, but try the following course from EdX, the online MOOC:
https://www.edx.org/course/tumx/tumx-autonavx-autonomous-navigation-1658


body:
I am building a small wireless controlled robot using the Arduino and the raspberry pi. It works by the user wirelessly connecting through to the raspberry Pi (using vnc or some other form wirelessly) and using the user inputs to send a command to the Arduino which controls the motorised wheels. SO for example if the user presses the up button, a 'W" command is sent from the Raspberry Pi to the Arduino which then reads it and pushes the wheels forward.

I was looking to use one of the new Arduino-Raspberry Pi bridges to connect the two to make it easier to use, but I am not too familiar on how they work. Had a few question such as:

1) How exactly do they work (connection wise)?

2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?

3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)

Sorry really new to the raspberry pi and need to find a solution soon so any help would be awesome.

Cheers

title: Raspberry pi -Arduino bridge

Answers: 2

body:
Have you thought about using the Raspberry Pi to control the robot directly, instead of adding the complexity of having the Pi talk to the Arduino?

Python allows you to control the GPIO pins of the Pi, and as long as you connect a suitable motor driver (to protect your Pi), you should be fine.

If you want to connect the Pi to the Arduino, then you could also look at doing this using Serial communications and wouldn't need the complexity of a bridge - just need a logic-level converter to convert the 5V of the Arduino to the 3.3v of the Pi

body:
> 1) How exactly do they work (connection wise)?

Physically they all sit on the GPIO sockets of the Pi, sitting on top of the pi. The [Gertduino][1] and [AlaMode][2] seem to have the same form factor as the Pi which makes them a little more appealing to me but I guess then is personal choice.

Communication appears to differ but it will use [Serial][3], [SPI][4] or [I2C][5]. I would imagine that you'd be able to choose an alternate one but not read enough about them to know for sure. Serial appears to be fairly simple, and it would be easy to debug, however you might struggle if you wanted to receive data on the Pi without the communication being initiated by the Pi.  I2C would overcome this as you can run it in [multi-master][6] mode.

>
> 2) is it possible to write one python code in the raspberry pi that
> when run can load the specific ino code into arduino?

As you can call external programs with python I would say that even if you have to resort to this mechanism then it would be possible. You can turn on the debugging in the Arduino IDE to see what it actually does, then either script it or make the calls from your python program.

>
> 3) which bridge would be the most suited for my project? (eg:
> Arduberry, alamode, gertduino, etc?)

I'd go for either the gertduino or alamode purely on looks particularly the matched form factor.

  [1]: http://www.element14.com/community/docs/DOC-64326/l/gertduino-add-on-board-for-raspberry-pi
  [2]: http://www.makershed.com/products/alamode-for-raspberry-pi
  [3]: http://www.bitsharr.com/rtxu6LvK
  [4]: https://www.google.co.uk/search?q=SPI communication between raspberry pi and arduino
  [5]: http://www.adafruit.com/blog/2014/02/21/connecting-an-arduino-to-a-raspberry-pi-using-i2c-raspberry_pi-piday-raspberrypi/
  [6]: http://forum.arduino.cc/index.php/topic,13579.0.html


body:
Having recently entered the world of Arduino I am seeking to make, as my first project, a ball that will sense my dogs approach and roll away.

I can handle the rolling part but I have been unable to find a sensor that will work when fully embedded in the ball (so the dog cannot bite or swallow it). This means no ultrasound or infra red or normal proximity sensor will do.

My best bet - an inductive proximity sensor (with a metal object attached to dog's collar) is only effective at a maximum distance of 8 cm and that is far too little. I need something that activates at say 1 foot.

Any ideas anyone?

title: Need a sensor to make ball roll away from pet but which sensor?

Answers: 4

body:
Interesting.  You may want to consider using strong,small, modern rare earth, low cost (silver color) magnetic that can work up to 1 foot, depending on size and shape of magnetic. Test different size/shape mag with simple mechanical compass to check the distance.

You may want to use one of those popular sensor board with

a) MPUxxxx (3D accel to sensor gravity in 3D to know which way is up and down)
b) 3D magnetic sensor

Both sensors are 3D and you know which direction the dog is coming (direction and mag strength, changed from background earth magnetic field when dog is coming, gives distance) and which 3D orientation of the ball is and hence to calculate which way to move a weight inside the ball to make the roll.

Biological disclaimer, no idea if dog health may be affected, positively or negatively (people sells human magnetic collar with health claim), by constant, 24 hours, magnetic collar.

Hope it helps

body:
Perhaps an RFID tag on your dogs collar and a reader inside the ball will work.
You will just have to find a reader and tag combination that can work from the range you need, I think some RFID can work from over 1ft.
EDIT: You will need active tags (battery powered) to get over a foot range.

PIR sensors detect heat given off by humans and animals, so they make work through the ball. (not totally sure though).

Edit: i think PIR that is capable of detecting small animals may be your best bet you would just have to calibrate the range of detection some how

body:
Idea 1:

Put a transceiver in the dogs collar, and one in the ball. Monitor the RSSI (received signal strength). If it goes above a threshold, roll away. Adjust the threshold to set the correct distance.

Idea 2:

Put an accelerometer inside the ball. Whenever it detects a knock (dog's paw etc) roll away for a few seconds.

body:
Other than the answers above/below, you also could try infra-red lights and photosensitive transistors. However, that has some troubles, such as not working properly in the sunlight, or the material that the ball is made of blocking the light, and therefore not working.

AVOID MAGNETS! You could get your dog stuck in some metal, like a fridge. To get one working in such distance, you would need an awfully powered magnet, which could be strong enough to permanently impact circuitry in close range, such as a home theater which sits close to the ground.

By the way, how are you going to fit it all in a ball that is bite-sized? i'm actually interested in that. Aren't you worried of the dog munching it and breaking/swallowing circuits?


body: I am trying to write a class/function that I think I will be using often in my Arduino IDE, I know the code but where should i save the file so that the IDE picks it up without a full directory address in the #include line, as you may guess I'm a little new to this....

title: file directory for saving .cpp & .h for the Arduino IDE for short #include statement

Answers: 1

body:
If you think you will be reusing this code frequently, you might want to make a library as suggested by Joachim. Your library can then be added to any sketch you write using a `#include` statement.

The arduino website has a nice guide on writing libraries, check it out [here][1].

If you would just like to include your header file in a sketch without writing a library, placing the header file in the same directory as your sketch should compile if you use `#include "header_file_name.h"`.

  [1]: http://arduino.cc/en/Hacking/LibraryTutorial


body:
I've taken apart an [old range finder (see photo here)][1]. It uses a circular, seemingly gold-plated, two-wire sensor that I'd like to re-use in an Arduino project.
I'm looking for a datasheet of the sensor and/or a circuit-diagram. Any help is welcome.

  [1]: https://plus.google.com/111652317143259686566/posts/75TraxED8bg

title: What is this component? (range finder)

Answers: 1

body:
The big circular parts likely is ultrasonic transducer as used in instant camera.

http://www.uoxray.uoregon.edu/polamod/

https://www.google.com/?gws_rd=ssl#q=polaroid+ultrasonic+ranging+module&revid=399558007&safe=off

Working principle is same as modern unit, easily available at a few US dollars. The transducer does NOT work by itself, needs the associate PCB to work.


body:
I am getting back into doing some hardware stuff after a fairly long time away and am having a hard time getting back into it. I have a [Teensy 2.0][1] and am trying to run a basic sketch that when a button is pressed will output 0, but my button is always High. I think that I miswired something but my breadboard looks like all the tutorials so I'm just confused as to what is going on and would appreciate any help.

    const int pinBtnUp = 0;
    const int pinLEDOutput = 11;

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

      //Setup the pin modes.
      pinMode( pinLEDOutput, OUTPUT );
      //Special for the Teensy is the INPUT_PULLUP
      //It enables a pullup resitor on the pin.
      pinMode( pinBtnUp, INPUT_PULLUP );

    }

    void loop()
    {
      Serial.println(digitalRead(pinBtnUp));
    }

![Breadboard][2]

  [1]: https://www.pjrc.com/teensy/pinout2b.png
  [2]: https://i.stack.imgur.com/HO3lS.jpg

title: Simply Button Problem (Teensy 2.0)

Answers: 2

body:
You would need to place your button over the "valley" in the centre of the breadboard, separating teh top 2 and bottom 2 legs of the button.

Currently the wire connecting the button to Pin 0 on your teensy is also connected to your pullup resistor on the breadboard, as it is in the same row.

To help troubleshoot this kind of thing I always find a digital multimeter very useful.

body:
You should post a higher quality version next time.

## Wiring:

First of all, the button looks like it's not all the way in. Fix that first.

Also, from your picture, it looks like the green wire isn't in the right row:

![][1]

I can't tell for sure. Also, like mentioned before, you to put the button over the gap between the two sides of the breadboard.

Also, you have a pullup resistor in your circuit *and* you enable it on the Arduino. And your physical pullup resistor isn't connected to your signal line. And you short your signal line to ground. All of this is incorrect wiring...

If utilizing the internal pullup resistor (like you are in your code), all you should need to do for a circuit is like this:

![][2]

Just be sure to connect the 5V rail to 5V and the green wire to your digital pin.

## Code:

That's all fine. When doing logic with a button, be sure to *debounce* it.

  [1]: https://i.stack.imgur.com/eHMZl.jpg
  [2]: https://i.stack.imgur.com/fLDxJ.png


body:
Trying to modify the native mouse methods so that it can use absolute, rather than the relative values it currently uses. This is so it can function as a touch screen pointer, and NOT a mouse.

Am using this modified HID.cpp file here

https://github.com/nospam2000/Arduino/commit/7b77d1e84d7b80819f049e5fd6e7bafa0d06521f#diff-0dd97502971c8a55546092b93abd32caR349

Mostly works, but the author has mapped to the maximum and minimum possible int values, (-32768 to 32767) and no matter what permutation of values I use with the native map method, I can't get it to work properly.

Has anyone wrestled with this problem and has a solution?

Since posting found another possible solution http://forum.arduino.cc/index.php/topic,94140.0.html

However with this solution the mouse movements are WAY too coarse for any monitor with a resolution above 100x100. Tried changing the LOGICAL_MAXIMUM value in HID.cpp but that alone doesn't work. Any C++ gurus possibly able to have a look?

Going back to the first solution this is the map method calls I am using, which should theoretically work!. TAR_WIDTH is the horizontal display resolution of my target monitor. TAR_HEIGHT is the vertical display resolution

    xPos2= map(xPos, 0, TAR_WIDTH, -32768, 32767);
    yPos2= map(yPos, 0, TAR_HEIGHT, -32768, 32767);

What happens is that when the x value is roughly -2800 or less than, I've reached the left edge of my monitor

Ditto for y, when less than or equal to -2800, I've reached the top.

Moving to the right and or down, once I reach roughly a value of 5000, x, OR y, the mouse wraps back to the left or top edge.

This value of 5000 represents only about 2/3 the width of my target monitor so I'm never able to fully map my mouse movement. Make sense?

So in summary, if I use solution1, I need to figure out how to fully map to my monitor. If solution 2, the movement is too coarse(and the mouseclick doesn't work).

title: Using Leonardo and getting absolute x,y Mouse values

Answers: 0


body:
I am trying to control an RGB LED strip with an Arduino. I have followed the tutorials in both of these websites:

Using MOSFETs: https://learn.adafruit.com/rgb-led-strips?view=all
![enter image description here][1]

Using LED Amplifiers: http://www.instructables.com/id/LED-Strip-Controller-w-LED-Amp-Arduino/
![enter image description here][2]

I have tried both setups and none of them work for me. When I try the setup with the MOSFETs, I am able to control each color but the blue LEDs are dimmer than the red and green, and therefore I can't mix any colors with blue.

When I try the LED Amplifiers, I am not able to control any light at all. Only the blue LEDs light up but the red and green dont. Also the blue LEDs stay ON the whole time and the only way to turn them off is to disconnect them from the DC power source.

What am I doing wrong?

  [1]: https://i.stack.imgur.com/ZTJij.gif
  [2]: https://i.stack.imgur.com/Jt91f.jpg

title: RGB LED strip with Arduino

Answers: 0


body:
I am trying to control an RGB LED strip with an Arduino. I have followed the tutorials in both of these websites:

Using MOSFETs: https://learn.adafruit.com/rgb-led-strips?view=all
![enter image description here][1]

Using LED Amplifiers: http://www.instructables.com/id/LED-Strip-Controller-w-LED-Amp-Arduino/
![enter image description here][2]

I have tried both setups and none of them work for me. When I try the setup with the MOSFETs, I am able to control each color but the blue LEDs are dimmer than the red and green, and therefore I can't mix any colors with blue.

When I try the LED Amplifiers, I am not able to control any light at all. Only the blue LEDs light up but the red and green dont. Also the blue LEDs stay ON the whole time and the only way to turn them off is to disconnect them from the DC power source.

What am I doing wrong?

  [1]: https://i.stack.imgur.com/ZTJij.gif
  [2]: https://i.stack.imgur.com/Jt91f.jpg

title: RGB LED Strips with Arduino

Answers: 4

body: From the drawings in that instructable, you need the Arduino ground and the 12 volt ground connected together - perhaps the line you have marked "+3v or 5v" should really be ground?

body:
For the mosfet circuit. Are you using an external power supply? The reason why you cannot mix any color might be due to the fact that you're not providing enough current to the led strip, so it just work fine when turning on each channel individually. Check the current the led strip draws (which usually is provided as amp per channel per meter) and use a power supply that can provide enough current for it.

From the adafuit page

> Connect a 9-12V power supply to the Arduino so that Vin supplies the high voltage to the LED strip. If you want, you can also just use a separate wire that connects to a power supply that provides about +12V. Make sure to connect the ground of that supply to the ground of the Arduino/MOSFETs!

body: The LED strip with blue ones requires a higher current drive. Arduino output pins can drive only 20mA max(ideal). Try an external power source.

body:
Your 12 strip probably puts each set of 3 LEDs in series.  3 Red LEDs take about 6V to be fully on, while 3 blue LEDs take about 9V; when you have 12v the resistors absorb the rest of the voltage drop (higher value resistors are needed for the red LEDs if you want about the same current in each color).  Driving 3 in series is good - the same current travels through 3 LEDs producing 3 times as much light per amp than if each LED was separately driven.  (Or from another perspective, with 3 in series the LEDs get 6-9v and thethe resistors and power amp need to drop the 3-6v from a 12v supply, versus a single LED dropping 2-3v and the resistors and power amp dropping the other 9-10v).

All is good, if you are driving each color with close to 12v.

BUT - your LED amplifier may expect more than 5v inputs in order to be fully on (eg: if it uses conventional FETs).  Driving it with 5v may not fully turn on the LED driving transistors.  In that case, the LEDs may be seeing less than 12V.  The blue LEDs would be the first to suffer from this voltage sag.

Note that if this is the case, the LED amplifier may also overheat - the transistors dissipate more power when not fully on, which raises the temperatures, probably leading to shortened life at best, possibly release of the magic smoke that makes electronics work.

You can test this.  Disconnect the Arduino.  Connect the +12v to one of the inputs at a time.  If that color is now fully bright, then you have shown that 12v input fully turns on the driving transistor, but 5v does not.

(If your LED amplifier says it's designed to be driven by 5v, do not do this test.  Many of them however expect to be driven by the tail end of a previous strip, at roughly 12v)

An example of an LED amplifier which **IS** designed for 5v inputs: http://www.usledsupply.com/shop/rgb-mini-amplifier-ttl.html  I have not used this device and am not recommending it, just using it as an example.  Note that it appears that for this amplifier, you would connect the Arduino's +5 to the input (along with the PWM outputs from the Arduino), rather than ground - and the PWM sense would be reversed, with lower PWM values being brighter, because the amp would turn on when the output pin was **low**.


body: I want to learn AVR C programming instead of arduino programming. I have an arduino UNO board and few Atmega328 chips that I bought, and Atmel studio for programming. Can I use Arduino Uno board as programmer to flash the chips from Atmel Studio? Or any other alternatives?

title: Using Arduino to learn AVR programming

Answers: 4

body:
If your chips have a bootloader already installed in them, you can use any USB -> Serial cable (FTDI cable) to program them in-circuit on their Rx/Tx pins. If not, you can use the Uno to program a boot loader into them (one time) and program them with the cable from then on.

To use standard C, you can use the bare chips or the UNO. You'll want a different environment than the Arduino IDE, though. That can be anything from an editor, the the gnu compiler tools run from a command line, to almost any other IDE. A number of people, myself included, use the Eclipse IDE with an AVR plug-in and do almost everything from writing the code to programming the AVR from within it. (I say 'almost' only because I personally prefer a full-blown programming editor, run outside of the IDE, for initial creation of sizeable projects or major edits and rewrites. That isn't necessary, though).

body:
If you're starting out then Atmel Studio is a good option - it's very easy to install and get up and running, and I use it.

To use an Arduino as an ISP you're going to need to use AVRDude.  You can configure Atmel Studio to flash chips using AVRDude - I struggled with this but eventually got it working, you can look [here](http://www.crash-bang.com/using-usbtiny-with-atmelstudio/) if it will help - not specifically for the Arduino as ISP, but should get you started.

Finally you should also double-check whether you have ATmega328-PU or ATmega328P-PU - AVRDude doesn't support the ATmega328-PU (without the P) so you'll need to do a workaround (again something that I've been caught out with in the past, [here's how I worked around it] (http://www.crash-bang.com/resource/bootload-atmega328/)

Good luck - programming the AVR directly is more challenging but gives you more control.

body:
> I want to learn AVR C programming instead of arduino programming.

It's not really clear what you think the difference is. You can use the Arduino IDE to do "straight AVR" programming, for example:

    int main ()
      {
      DDRB = bit (5);  // pin 13
      DDRB |= bit (4);  // pin 12

      while (true)
        {
        PINB = bit (5); // pin 13
        PINB = bit (4); // pin 12
        }
      }

The AVR register names (eg. DDRB, PINB, PORTB and so on) will be included by the IDE, however you don't have to use a single Arduino library or function if you don't want to.

body: You can use the Atmel Studio + Visual Micro plugin to easily get started with atmega328 + support for the uno board (easily program, use arduino libraries etc). Checkout here.  http://www.visualmicro.com/page/Arduino-for-Atmel-Studio.aspx