body:
I am attempting to build an Android app from which I can can upload a .hex file to my Arduino(Leonardo). I am aware of a few apps in the Google Play store that are capable of this functionality but I can't seem to find any actionable resources on how to go about doing this. I am aware that the desktop Arduino IDE uses AVRDude to perform the upload but I don't believe AVRDude is available on Android so I'm at a complete loss here. Does anyone know how I would go about accomplishing this?

After some more searching I now know that the Leonardo(ATMega32u4) uses the AVR109 Protocol to flash new programs onto the hardware but I'm still at a complete loss as to what that process is and how I'd reproduce it in Java.

title: Programmatically Upload Arduino Sketch From Android App

Answers: 1

body:
If I wanted to do this for a conventional Arduino I'd start by figuring out the operations against a serial API to talk to the bootloader, and perhaps test it against something exposing desktop serial ports to Java, as debugging Android host mode stuff is a pain given you have to use ADB-over-wifi. You might try to figure out how avrdude works, for example. Then I'd try to combine that with existing code that is out there for talking serial-over-USB to Arduino boards with the various device-side chipsets. For a leonardo type board the two pieces may be more tightly coupled.

Copy of Chris Stratton's comment which was acknowledged as an answer.


body:
I'm installing some daylight running lights in my car and I have purchased 2 LED bars, each with 8 white LEDs. They use 12V and I need to make some effect when they turn on. Like in some modern cars, when I turn on the key, LEDs should blink(shake like when old fluorescent tubes turns on) and then turn on slowly(brightness from 0-100).

I can do this with Arduino-Uno and I need to put this in a smaller chip. What would be the best suitable ATTiny chip for this project? Because using an ATmega328 is not worth for a small project like this.

title: ATTiny to drive LEDs

Answers: 1

body: The ATtiny85 is an 8-pin AVR device with 3 PWM channels available in DIL and SO packages. The Arduino core can be downloaded from arduino-tiny. It can be programmed via ISP using either ArduinoISP or a dedicated programmer.


body:
I have two I2C LCD screens:

 - one with 2 lines
 - one with 4 lines.

Both have 4 pins each: `GND`, `VCC`, `SDA`, `SDL`. I connect `SDA` and `SDL` to `A4` and `A5` respectively, and I display text on each one of them with:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x27,16,4);

But how can I use both of them at the same time?

I connected the second one's `SDA` and `SDL` to `A2` and `A3`, but apparently I have to provide the right address for them (like `0x27`), right?

However, while both are connected, using [I2C_Scanner][1] only shows one device:

    Scanning...
    I2C device found at address 0x27  !
    done

  [1]: http://playground.arduino.cc/Main/I2cScanner

What am I missing?

title: How do I use two I2C LCDs with 4 pins?

Answers: 3

body: You can't hook up I2C devices to arbitrary pins; they must either be connected to SDA and SCL and given different addresses, or you must use software I2C. Figure out how to give the second device a different address, and then instantiate another `LiquidCrystal_I2C` with the new address in order to be able to use it.

body:
You may be able to wire them in parallel, if you can hold the clock (SCL) high (for one at a time).

Put a diode in to stop the other one going high as well.

Pick a spare pin on your arduino (I will use digital pin 7 for device A, 8 for device B, but it doesn't matter which). When you want to talk to device A, make sure pin 7 is in high impedance mode, and 8 is high. Talk to device A. Stop talking to device A. Put pin 8 in high impedance mode, and pin 7 to high. Talk to device B. Wash, rinse, repeat. So long as a device sees it's clock as high, it won't listen or talk.

body:
**With the I2C backpack there are three pairs of landings, A0, A1, A2, which determine the 3 LSB of the device's address, using inverted binary.**

Left alone, they generate part of the F or 7 part of the address.  0x3F is common, as is 0x27.

**To use more than one device it is necessary to jumper them all uniquely.**

The upper bits that generate the 0x3 are hard-wired.  So is the highest bit of the lower byte.  Only the three lowest-order bits can be changed.

Since these address bits are inverted, jumpering the A0 will subtract 1 from the address.  0x3F will become 0x3E, 7 will become 6.

**You have control enough to make up to 7 LCD modules on the same I2C bus.**

The only caveat is that if you have more than one device writing to the various LCDs you might get collisions, which can mess up the display pretty good.

There are questions on I2C collision avoidance and detection on http://RaspberryPi.StackExchange.com if that is your situation.

**Jumpering one or more of them is pretty easy - just pre-tin some wire and solder it quickly then cut off the excess.**

Wire the SDA and SCL wires of the LCDs in parallel and to the SDA and SCL pins on the Arduino, usually A4 and A5.  (I always begin with a breadboard for this).  Make sure you have discrete pull-up resistors (10K is common) on each, in only one place on the bus.

If you have a DS3231 RTC module in the system, you do not need to add pull-ups because it has them internally.

If one LCD is already working then you know you have proper pull-up voltage on the bus.  (The signals are switched to the ground state to send data on the I2C bus)

So, to Summarize:
--

If you have two LCDs in your system you can use LCD modules that already come with different addresses, like

    LiquidCrystal_I2C lcd1(0x27,....);

for the first one, then

    LiquidCrystal_I2C lcd2(0x3F,.....);

for the second one.

Note that the parameters for these definitions are
-
    LiquidCrystal_I2C lcdname(addr,en,rw,rs,d4,d5,d6,d7,bl,blpol);

0x27 and 0x3F are the most common stock addresses and **0x27 modules are getting harder to find.**

If you have a 0x27 then it is very likely that if you buy a newer one it will be 0x3f. **Problem solved.**

The d4 and d5 in the definition specifies the pins to use for I2C.

You can run the i2cscanner program to see what it finds, once they are wired together.  If you see two different addresses, say 0x27 and 0x3F, then you are good to go.

If only 2F shows, then you want to consider soldering A0 together on one module then run the scanner again to make sure it worked.

Here is how I usually do it when both come set as 0x3f:
-

**I have a Yellow one which is a stock 0x3F and a Blue one where I jumpered A0 to make it 0x3E.  They both are 20 x 4 displays.**

Here are my definitions:  (remember, the 4,5 define SDA, SCL pins)

    LiquidCrystal lcdblue  (0x3e,2,1,0,4,5,6,7,3,POSITIVE);
    LiquidCrystal lcdyellow(0x3f,2,1,0,4,5,6,7,3,POSITIVE);

Then in setup() I use this:

    lcdblue.begin(20,4);
    lcdblue.backlight();
    delay(250);
    lcdblue.nobacklight();
    delay(250);
    lcdblue.backlight();

    lcdyellow.begin(20,4);
    lcdyellow.backlight();
    delay(250);
    lcdyellow.nobacklight();
    delay(250);
    lcdyellow.backlight();

And it's good to go, using pin A4 as SDA and A5 as SCL.

You know they are working as they wink their backlights at you.

If one of yours is 20 x 2 then use `lcd2.begin(20,2);` of course.

If you REALLY want to use other pins for your I2C bus then just change the 4,5 in the `LiquidCrystal_I2C` definition to the pins you want to use.  I never have met anyone who would want to do this.

Hope this helps.


body:
A few days ago, I've asked [this question](https://arduino.stackexchange.com/questions/12117/arduino-yun-doesnt-link-any-library).
Thanks to the replies I've received, I've set up a cross compile environment for Yun by following [this guide](http://wiki.openwrt.org/doc/devel/crosscompile).

I've created a virtual machine with virtualbox and installed Debian 8.0 on it. I installed all the software required to download and compile the OpenWRT-Attitude Adjustment version (which, I think, is the version used by Arduino Yun) on Debian.

So, I've downloaded the OpenWRT source code, downloaded its packages feed (with "git clone git://git.openwrt.org/12.09/packages.git"), downloaded and installed all available "feeds" (with: "./scripts/feeds update -a" "./scripts/feeds install -a") and then compiled it with: "make defconfig" "make prereq"
and "make menuconfig".

When I typed in "make menuconfig", a graphical interface prompted. In that interface I selected:

Target System: (Atheros AR7xx/AR9xx);

Base System: I selected libc, libcc and marked as package libpthread and librt.

I left any other option as default. Then I compiled all with "time make V=99" command.

After about 2 hours, the compiling finished and I set the environment variables as the above mentioned guide described.

Looks like now I can compile any C code with this cross-compiler. Anyway, my application includes the png.h header in order to use the libpng library, and every time I try to cross-compile it, a "png.h not found" error pops up during the process.

So I tried to cross-compile the libpng library but when I ran "./configure" with the options for cross-compiling, it failed saying that zlib wasn't installed. So I downloaded the zlib library source code but looks like I can't cross-compile it.

Eventually I compiled zlib and libpng normally on Debian and now, when I try to cross-compile my application, it still says that it can't find png.h...
So, how can I "integrate" the libpng library to the cross-compiling environment?

Sorry for this long question, but it is all I've done today.

As always, I thank you for any help you can give me.

title: How do I install a library in Arduino Yun cross compile environment?

Answers: 0


body:
I have been tinkering for 2 days to manage send and receive between 2 arduinos. My code is bellow:

Arduino 1:

    #include <SPI.h>
    #include <RF24.h>
    #include "printf.h"
    #define LED 2
    #define RF_CS 8
    #define RF_CSN 9
    RF24 radio(8,9);
    String datargb = "rgb: 000000005";
    char chartosend;
    char inchar;
    String inradio;
    int endchar = '~';
    void check_radio(void);
    void setup() {
      // put your setup code here, to run once:
    Serial.begin(115200);
      printf_begin();
      radio.begin();
      radio.setRetries(15,15);
      radio.openWritingPipe(0x080C600C01LL);
      radio.openReadingPipe(1,0x080C600C71LL);
      radio.setPALevel(RF24_PA_MAX);
      radio.setAutoAck(true);
      radio.printDetails();
      attachInterrupt(0, check_radio, FALLING);
      radio.stopListening();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    int lnth = datargb.length();
      for(int i=0; i<lnth; i++){
          chartosend=datargb.charAt(i);

          while(!radio.write( &chartosend, sizeof(chartosend) )){}

          Serial.println("sent");
      }
      radio.write(&endchar,1);
    }
    void check_radio(void){

      bool tx,fail,rx;
      radio.whatHappened(tx,fail,rx);

      if(rx){
        Serial.println("interrupt!!");
    radio.startListening();
        radio.read( &inchar, sizeof(inchar) );
        inradio+=inchar;
        Serial.println(inchar);
        if(inradio.endsWith("~")){
          Serial.println(inradio);

          if(inradio.startsWith("rgb: ")){
            analogWrite(6,inradio.substring(5,8).toInt());
            analogWrite(9,inradio.substring(8,11).toInt());
            analogWrite(5,inradio.substring(11,14).toInt());
          }
          inradio = "";
          radio.stopListening();
        }
      }
    }
Arduino 2:

    #include <SPI.h>
    //#include <nRF24L01.h>
    #include <RF24.h>
    #include "printf.h"
    //#include <RF24_config.h>
    RF24 radio(8,10);
    char data;
    char chartosend;
    char endchar = '~';
    String inradio;
    void check_radio(void);
    String datargb = "To mounti tis manas tou nrf24";
    void setup() {
      // put your setup code here, to run once:
      pinMode(9, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, INPUT);
      attachInterrupt(1, check_radio, FALLING);
      Serial.begin(115200);
      printf_begin();
      radio.begin();
       //radio.setRetries(2,15);
        // open pipe for writing
        radio.openReadingPipe(1,0x080C600C01LL);
        radio.openWritingPipe(0x080C600C71LL);
        radio.setPALevel(RF24_PA_MAX);
        radio.startListening();
        radio.printDetails();
        radio.setAutoAck(true);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    if(digitalRead(7)==HIGH){
      radio.stopListening();
      for(int i=0; i<28; i++){
          chartosend=datargb.charAt(i);
          while(!radio.write( &chartosend, sizeof(chartosend) )){}
          //Serial.println("sent");
      }
      radio.write(&endchar,1);

      while(digitalRead(7)==HIGH){}
      radio.startListening();
    }
    }
    void check_radio(void){

      bool tx,fail,rx;
      radio.whatHappened(tx,fail,rx);

      if(rx){
        Serial.println("interrupt!!");
    //radio.startListening();
        radio.read( &data, sizeof(data) );
        inradio+=data;
        Serial.println(data);
        if(inradio.endsWith("~")){
          Serial.println(inradio);

          if(inradio.startsWith("rgb: ")){
            analogWrite(6,inradio.substring(5,8).toInt());
            analogWrite(9,inradio.substring(8,11).toInt());
            analogWrite(5,inradio.substring(11,14).toInt());
          }
          inradio = "";
          //radio.stopListening();
        }
      }
    }
Arduino 2 receives all data from ar1 but when I press the button attached to the pin 7 arduino 2 stops listening and only sends the first character of the string.

title: Pressing button stops listening on nrf24l01

Answers: 1

body:
@Gerber remarked:

There is probably a death-lock situation where both arduino's are trying to send data the the other, while both aren't listening. So both are waiting for the other to ack. Like I said at your previous question. Why not send all rgb data in one packet. Also, there is no need to call `radio.stopListening`.

You send one char, and wait for and ACK. Then you send the next char and wait for an ACK. If the other unit doesn't process the message, the buffer will will up after 3 messages, and it will no longer send an ACK (because the buffer is full), and you while loop will hang


body:
I want to send some data from an Arduino Mega to an android device via bluetooth (HC-06). I have installed some sensors whose values are frequently written in an SD card. Every time a new string line is added in a text file of the SD card. This is the format of the line

    27/5/2015,11:55:00,34.00,27.00,42.50,26.80,47.80,26.00,24.62,24.12,26,0,0,708,1023,1023,1023,1023,10.5,10.5,10.5,10.5

and this is part of the code. I send from a bluetooth terminal the string "download" and after that the text file is opened and every line is readed and sent to the android device via bluetooth.

    void loop(void){
        while(Serial1.available()) {
           character = Serial1.read();
           content.concat(character);
        }

    if (content == "download") {
        Serial.println(content);
        content = "";
        read_from_SD_Card();
       }
        ........................
        ........................
        ........................
    }

    void read_from_SD_Card(){
        myFile = SD.open("test.txt");
        if (myFile) {
            Serial1.println("test.txt:");

            while (myFile.available()) {
                Serial1.write(myFile.read());
          }
          myFile.close();
        }
    else {
      Serial1.println("error opening test.txt");
      }
    }

The problems are:

 - the data are downloaded only after an upload of the sketch has been done. (I can't upload the sketch once and download the data from time to time)

 - No more than 10-20 lines can be downloaded. With bigger files the downloading seems to slow down and finally stops after a few lines.

Any thoughts would be appreciated.

title: Bluetooth transfer problem with big files

Answers: 3

body:
    String content;
    void loop()
    {
        while(Serial1.available()) {
           character = Serial1.read();
           content.concat(character);
         }

    if (content == "download")
    {
        Serial1.println(content);
        content = "";
        read_from_SD_Card();
        }

    ........................
        ........................
        ........................
    }//end of loop()

    read_from_SD_Card(){
        myFile = SD.open("test.txt");
        if (myFile) {
            Serial1.println("test.txt:");

            while (myFile.available()) {
                Serial1.print(myFile.read());
          }
          myFile.close();
        }
    else {
      Serial1.println("error opening test.txt");
      }
      Serial1.readString()//to flush the serial buffer.
    }

body: @user3060854 -- were you able to resolve this? A higher baud rate for communicating with the HC bluetooth module can help with your speed/slowdown problem. But have noticed baud rates above 115200 dont work well. I believe the problem is the receiver baud rate %error, which should not happen at 250k baud. But I havent figured out how to set a baud rate of 250k in the BT module. The question with details is here ---  https://arduino.stackexchange.com/questions/18132/setting-baud-rate-of-250k-for-the-hc-05-bluetooth-module

body:
I suspect that this is a String class heap-fragementation issue (again). To test this you could sending a fixed string buffer (vector of characters, "Hello world" :). Do not use String and SD/FAT in the test. Just send a large number of lines with dummy data.

If this works replace the String usage with a character buffer. Fill it from the SD file (buffer size at a time) and write to Serial.

Cheers!


body: I want to make a transmitter and receiver for quad copter for that I am using two arduinos(UNO and nano).I am using 4 pots for controlling the brushless motors.For that I am sending 4 integer values of the pots and with that integer value PWM signals are generated at receiver by the arduino.Now I want to know how to send that 4 integer values of the pots serially using arduino.

title: how to make transmitter and receiver for quad copter?

Answers: 1

body:
The APC220 radio module provides a simple and economic solution to wireless data communications. Integrates an embedded high speed microprocessor and high performance IC that creates a transparent UART/TTL interface, and elminates any need for packetizing and data encoding. Use this module as this works as a pair and more intriguing part is that "it" can transmit over a km away.

link ~http://www.dfrobot.com/index.php?route=product/product&filter_name=apc&product_id=57#.VWeKIVWqqko


body: I'm new to all this. I bought an Arduino Uno recently and an Ultrasonic distance sensor. My mom's cats keep walking down into the basement and doing their... business. Anyhow, I want to create a radar system which detects movement past this door. I'd like to have an alert sent to my computer or Android. Is this within a basic Arduino level? Other than the Arduino what else might I need?

title: I want to build a radar alert system with Arduino

Answers: 6

body:
I think that's quite possible. As mentioned, not technically radar. I don't know if cats could hear it, but then if it scares them off, job done, right?

I don't know if sending the alert to a PC would help or not - you might just consider an audible alarm using a cheap 8-ohm speaker. Otherwise, USB, bluetooth, wifi, or SMS for notification. A PC or phone (on all the time) to receive the data. Some thought about what you will do with it.

As a deterrent, a water pistol is ideal, you'd need a motor - solenoid? - to fire the water pistol. Harmless, but very distasteful to cats.

https://www.youtube.com/watch?v=lxmRYRlgreo

Update: Inspired by @SDSolar, I checked it out - yes, cats can hear that frequency.

>Cats have excellent hearing and can detect an extremely broad range of frequencies. They can hear higher-pitched sounds than humans or most dogs, detecting frequencies from 55 Hz up to 79 kHz.

(from https://en.wikipedia.org/wiki/Hearing_range#Cats )

This means they will probably learn to associate the sound with the water pistol (yes, cats CAN be trained, if they are motivated). This means if you remove your device, they will probably come back, but if you leave the sensor (active), but remove the water, then it will continue to work!

body:
I'm not convinced an ultrasound detector will detect a cat.  They're fluffy and (usually) soft, so the ultrasound might not bounce off.

Instead I suggest you just try a gadget that annoys cats and keeps them out of the area.  It's an ultrasound emitter, and the noise is **claimed** to be objectionable to cats.  I've seen them sold in gardening stores, for keeping cats away from the bird table:

[Opinions on cat scarers][1]

  [1]: https://skeptics.stackexchange.com/questions/5945/do-ultrasonic-cat-repellents-work

body:
As a project building a cat detector sounds interesting, but as a cat owner I can promise you that if you actually go through with it the cats will see it, play with it and trash it within 5 minutes.  If it is successful and you do manage to scare them out of the basement they are just going to find somewhere else to 'do their business' and that could be in your bed.

However, your sensor will need to scan a large field of potentially rapidly moving objects.  A beam wouldn't be suitable because they could step over or under it.  I think PIR would be best for this task, but PIR sensors might not be sensitive enough to detect the little darlings.

Another idea maybe a gas sensor based project to provide an audible warning when a human enters the area that there are 'landmines' in the proximity and extreme caution needs to be used, if you know what I mean :)

body:
Ultrasonic sensors can only measure the distance to the nearest object in their cone. Are you sure you can detect a "small" thing like a cat?

I think the only feasable way is to use optical recognition (motion sensor with a camera - even a webcam - and a board like a raspberry pi).

body:
ANSWER BASED ON YOUR TITLE:

Here is a microwave RADAR motion-sensing module that you might find useful.  You could mount it right by the stairs.

http://www.ebay.com/itm/262662221979

LFS-DC04 2.7GHz Microwave Radar Module DC 5V 360 Degree High Level Signal New

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

Product Introduction:
-----
    1.Model:LFS-DC04
    2.Frequency:2.7GHz
    3.Size:40*22mm
    4.Input Voltage:DC 5V
    5.Output Type:level signal output
    6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
    7.Installation Height:1-3.5m
    8.Sensing Ditance:5-8m
    9.Delay Time:30s(quick testing mode is 4s)
    10.Sensing Angle:360 degree
    11.$1.59 price via the slow boat

--------

ANSWER BASED ON YOUR TEXT:

Ultrasonic can work - you will want to position it so your software can tell whether there is a cat/no cat, like pointing it across a step.  With no cat it would give a reliable distance reading from something on the other side of the step.   With the cat in the way, that reading would change.

Yes, this is in the realm of Arduino, for sure.

Here is a Google search to get you started:

https://www.google.com/search?q=arduino+with+ultrasonic+sensor

To tell the difference between a cat an a human you would want a second sensor, above the cat's height, also.

Or you could use a DS3231 RTC module to decide when it is night-time so you wouldn't need to discriminate between cats and people at all.

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

body:
Or there's an off-the-shelf solution: [Innotek ssscat][1] is a bottle of compressed air and a motion detector. The spray is harmless but it sounds like a hiss, which is Cat for GTFOuttaHere!

  [1]: https://www.innotek.net/Products/Pet-Proofing-Barriers/Innotek-ssscat.aspx


body:
I'm using Raspberry Pi and Arduinos for my home automation project where Raspberry Pi is the controler of Arduino nodes.
I use nRF24 wireless transceivers to communicate.

My problem is that when I was sending a structure like following

    struct TempSensorData
{
      uint32_t result;
      uint32_t temperature;
      uint32_t humidity;
    };

From Raspberry to Raspberry everything went fine but now when I use Arduino as sender I get very strange results:

    received: status: 335544320, temperature: 754974720 degrees, humidity: 0%

While on Raspberry it was

    received: status: 0, temperature: 22 degrees, humidity: 44%

Can this be a problem with types? Or with different type of architecture (like different sizes on 3-2bit and 64-bit arch)?

EDIT:

Code on Raspberry:

    if (radio.available())
{
        // dump the payloads until we've got everything
        Message receivedData = {0};
        radio.read(&receivedData, sizeof(Message));
        TempSensorData data = receivedData.msgData.tempSensorData;
        std::cout << "received: status: " << data.result << ", temperature: " << data.temperature << " degrees, humidity: " << data.humidity << "%" << std::endl; //TODO here we have some strange numbers - check if we have proper types
    }

Before that I have:

    radio.begin();
    radio.setPALevel(RF24_PA_LOW);
    radio.setChannel(0x4c);
    radio.openReadingPipe(1, RASPI_READ_ADDR);
    radio.openWritingPipe(RASPI_WRITE_ADDR);

    radio.enableDynamicPayloads();
    radio.setAutoAck(true);
    radio.powerUp();
    radio.startListening();

And on Arduino:

    Header header = {thisNodeId, thisNodeType, 0, static_cast<uint8_t>(MsgType::TEMP_SENSOR_DATA), 12345, Status::ok};
    TempSensorData dhtData;
    dhtData.result = DHT.read11(DHT11_PIN);
    dhtData.humidity = (int)DHT.humidity;
    dhtData.temperature = (int)DHT.temperature;
    Message message = {0};
    message.header = header;
    message.msgData.tempSensorData = (dhtData);
    radio.stopListening();
    radio.write(&message, sizeof(message));
    radio.startListening();

I also use a common header with defined structures for both Arduino and Raspberry, which contains:

    #define RASPI_WRITE_ADDR 0xF0F0F0F0F0LL
    #define RASPI_READ_ADDR 0xF0F0F0F0E1LL

    struct TempSensorData {
      uint32_t result;
      uint32_t temperature;
      uint32_t humidity;
    };

    enum class Status : uint8_t
{
        ok,
        error,
        fail
    };

    enum class MsgType : uint8_t {
        INITIALIZATION,
        RESET_REQUEST,
        ACK_NACK,
        TEMP_SENSOR_DATA,
    };

    struct Header {
      uint8_t nodeId;
      uint8_t nodeType;
      uint8_t location;
      uint8_t msgType;
      uint16_t checksum;
      Status status;
    };

    union MsgData {
      InitMsgData initMsgData;
      AckNack ackNack;
      TempSensorData tempSensorData;
    };

    struct Message {
        Header header;
        MsgData msgData;
    };

`radio` is an item of RF24 class from https://github.com/TMRh20/RF24/

Unfortunately the RF24 repo is 64 commits ahead of what I use.

**EDIT2:**

Maybe the problem lays in that

    enum class Status {};

which I use in both files.

I must add that I use g++-4.7 when compiling on Raspberry and when compiling on Arduino I use avr-g++-4.8.2

title: Sending struct from Arduino to Raspberry Pi - wrong types

Answers: 3

body:
It is not a size problem: `uint32_t` is always 32 bits. Converting the
numbers to hex gives:

* Raspberry to Raspberry: 0x00000000, 0x00000016, 0x0000002c
* Arduino to Raspberry: 0x14000000, 0x2d000000, 0x00000000

There seems to be an offset between the two. You may just have lost one
byte when the Arduino is the sender. There _may_ be also a byte order
issue, but your test is not sufficient to say. You can, e.g., send a
series of `0x12345678` to know for sure.

You need to devise a way of synchronizing the communication, i.e. to
identify, in the byte stream, which is the first byte of the packet.

**Edit**: Let me illustrate how this can happen both with and without
and endianness issue. I'll assume you are transmitting
`{status: 0, temperature: 20, humidity: 45}` and the first byte(s) of
the first packet are lost. On the receiving side, you combine the
remaining bytes of the first packet with the first byte(s) of the second
packet, and interpret the whole as a single packet. You get:
`{status: 335544320, temperature: 754974720, humidity: 0}`.

In a little endian to little endian scenario, you only need to loose one
byte:

    original data:     0x00000000, 0x00000014, 0x0000002d
    transmitted bytes: 00 00 00 00 14 00 00 00 2d 00 00 00
    received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
    received data:     0x14000000, 0x2d000000, 0x00000000

In a big endian to little endian scenario, you get the exact same result
if you loose 4 bytes:

    original data:     0x00000000, 0x00000014, 0x0000002d
    transmitted bytes: 00 00 00 00 00 00 00 14 00 00 00 2d
    received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
    interpreted data:  0x14000000, 0x2d000000, 0x00000000

body:
I believe this could be because the Raspberry pi is big endian and the arduino is little endian.

[Learn about Endianness here!][1]

  [1]: http://en.wikipedia.org/wiki/Endianness

body:
You may have multiple problem.
First of all the structure get align to be efficient on the specific architecture, to avoid those filling you have to tell the compiler to pack the structure. There are different way to pack depending on compiler used.

Then endianess is different, so the byte composing the value has to be swapped.

Finally there may be a desincronization or a bus error. In those case a sync message (normally 2 byte before each transmission) and a CRC are used to fix the issue.


body: So I'm using the DFRobot LCD Keypad shield to make a text-based game. Can someone give me an example? Let's just say i want to make the LCD display "text1" and then press up then select, it displays "text2". If I press down then press select, it displays "text3".

title: How to program LCD shield?

Answers: 1

body:
Attach the shield to arduino then run the following code to check if everything is ok.
Wiring is made default.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;

    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    int read_LCD_buttons(){               // read the buttons
        adc_key_in = analogRead(0);       // read the value from the sensor

        // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
        // we add approx 50 to those values and check to see if we are close
        // We make this the 1st option for speed reasons since it will be the most likely result

        if (adc_key_in > 1000) return btnNONE;

        // For V1.1 us this threshold
        if (adc_key_in < 50)   return btnRIGHT;
        if (adc_key_in < 250)  return btnUP;
        if (adc_key_in < 450)  return btnDOWN;
        if (adc_key_in < 650)  return btnLEFT;
        if (adc_key_in < 850)  return btnSELECT;

       // For V1.0 comment the other threshold and use the one below:
       /*
         if (adc_key_in < 50)   return btnRIGHT;
         if (adc_key_in < 195)  return btnUP;
         if (adc_key_in < 380)  return btnDOWN;
         if (adc_key_in < 555)  return btnLEFT;
         if (adc_key_in < 790)  return btnSELECT;
       */

        return btnNONE;                // when all others fail, return this.
    }

    void setup(){
       lcd.begin(16, 2);               // start the library
       lcd.setCursor(0,0);             // set the LCD cursor   position
       lcd.print("Push the buttons");  // print a simple message on the LCD
    }

    void loop(){
       lcd.setCursor(9,1);             // move cursor to second line "1" and 9 spaces over
       lcd.print(millis()/1000);       // display seconds elapsed since power-up

       lcd.setCursor(0,1);             // move to the begining of the second line
       lcd_key = read_LCD_buttons();   // read the buttons

       switch (lcd_key){               // depending on which button was pushed, we perform an action

           case btnRIGHT:{             //  push button "RIGHT" and show the word on the screen
                lcd.print("RIGHT ");
                break;
           }
           case btnLEFT:{
                 lcd.print("LEFT   "); //  push button "LEFT" and show the word on the screen
                 break;
           }
           case btnUP:{
                 lcd.print("UP    ");  //  push button "UP" and show the word on the screen
                 break;
           }
           case btnDOWN:{
                 lcd.print("DOWN  ");  //  push button "DOWN" and show the word on the screen
                 break;
           }
           case btnSELECT:{
                 lcd.print("SELECT");  //  push button "SELECT" and show the word on the screen
                 break;
           }
           case btnNONE:{
                 lcd.print("NONE  ");  //  No action  will show "None" on the screen
                 break;
           }
       }
    }


body:
The central arduino
![The central arduino][1]
The 1st node
![The 1st node][2]
The 2nd node
![The 2nd node][3]

  [1]: https://i.stack.imgur.com/LnAZh.png
  [2]: https://i.stack.imgur.com/HrrK8.png
  [3]: https://i.stack.imgur.com/LT4Vu.png

I want the central to send to the first node the rgb code like a string on the loop

> "rgb: 255000255"

 but when it detects something to PIR to send a string to central.
In addition every some seconds the 2nd node to send a string to the central the temperature.

As i mentioned in my previous questions i have some problems when it comes to the bi-directional comunication. I have tried a lot of code. Can someone show me how to achieve what i want to do if not with code, with steps. Please help me!!

title: bi-directional nrf24 communication

Answers: 2

body: Try the [`RF24Network`](https://github.com/maniacbug/RF24Network) library from `maniacbug`. If you don't have too many nodes it's easy to use. It comes with examples easy to test and extend. It also uses different channels for sending and receiving so you should have no collisions.

body:
**You *cannot* (easily) have all nodes on the network with the same address.**

There are ways of doing it but they aren't easy.  They basically involve creating a "broadcast" facility in your network, and that has certain caveats involved with it.

The nRF24L01 modules have an "auto-ACK" mode to give reliable communications.  *This only works with 1:1 addressing* and cannot work with broadcast.  If you want to (as most people do) use the auto-ACK facility then you have to have each node with its own unique address.  After all, if you're sending the *ACK* to a station, and there are multiple stations with that address, *which one will ACK?*

So you have to think about if what you are trying to achieve is really the right way of going about it.  It sounds like you want to just program another node with the same code as an existing node without making any changes to that code and "just have it work".  That's a very advanced topic and one that even I would spend quite some time implementing it.  Yes, you can do unreliable communications (i.e., no auto-ACK) then you could have all the remote stations with the same address, but I would certainly keep the master as a unique address.  Better would be for each node to start up with a pre-defined address which it then uses to ask the master for a unique address (a-la DHCP) and the master then keeps a list of what is connected on what address.  From then on it can use reliable communications to send and receive data to each node as it needs to.

[A system I wrote for the chipKIT boards](https://github.com/MajenkoLibraries/nrf24l01) gives each node two addresses - its own unique address which you have to provide manually, and a more global "broadcast" address.  They are each on different pipes within the nRF24L01.  To communicate with an individual node you send to its unique address.  To broadcast to all nodes you send to the broadcast address.  If you're sending to the unique address you can then turn on auto-ACK. If you're sending to the broadcast address you don't turn on auto-ACK.

Note that using auto-ACK is a whole topic in itself and requires careful design planning to get it to work properly.

Also you have to think about what happens when you send a broadcast packet out and it's received by other nodes - how do they handle that data? Sending temperature data out globally, it will be received by the RGB receiver, which may try and interpret it, causing problems.  You need to come up with a way of identifying just what it is you're sending out and only having the right nodes responding to the right data.  That means coming up with a strict packet format.  Luckily the nRF24L01 chips communicate in fixed packet sizes (incidentally, all nodes on the network will have to be set to use the same packet size or it just won't work) up to 32 bytes, so implementing a packet structure over that is easy enough.  Just sending strings of data is both hard to interpret and incredibly inefficient.  You should be sending the data as actual data values in variables as part of the packet structure.


body:
I am using an Arduino Due for a project. I am running out of digital pins, using 22 to 53. Can pins 0 to 13 and SCL1, SDA1 be used as digital inputs?

How about analog pins (A0 to A11) and DACs?

Thanks!

title: Can all Arduino Due pins be used as digital input/output?

Answers: 2

body:
**Bear in mind that this has nothing to do with "Electrical Engineering".
This simply is an arduino question. And should be asked on [arduino Stack Exchange.][1]**

Yes.

They can be used as input/output pins. [[Simple 'tutorial'][2]]
If that even isn't enough or not working on your type of arduino, you can use I/O expanders or shift registers.
Check them out on the internet. [[I/O expanders][3]]

  [1]: https://arduino.stackexchange.com/
  [2]: http://waihung.net/arduino-tip-turn-your-analog-pins-into-digital-io/
  [3]: https://www.google.nl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=io expander ic

body:
Yes, sort of. All the Analogs/digitals can be used as digital outputs with the following exceptions. TX0/RX0 (unless you are aware of what you're doing), SPI buss (SCK/MOSI/MISO), SDA1/SCL1, & CANRX/CANTX. DAC0/DAC1 may be used but be aware the min/max those two pins can output is ~0.55 to 2.75V.

And these exclusions are only for an arduino DUE. Other Arduino's will have more/less exclusions.

Correction:  I was able to use CANRX and CANTX as alias pin names to declare these two lines as digital outputs, and set the pin values high/low in the normal way.


body:
I've recently purchased a screen on DX without really thinking about it, because I have no idea how to connect it to my Arduino.

It is [this][1] screen:

![XS075][2]

The description says that it uses the SPI serial protocol but I don't know how to connect that ribbon to my Arduino, is soldering cables to it the only way?

  [1]: http://www.dx.com/p/xs057-1-8-serial-128-x-160-spi-tft-lcd-module-display-for-arduino-black-white-golden-255430#.VWg4E8-eDRZ
  [2]: https://i.stack.imgur.com/R40Mz.jpg

title: How do I connect this SPI serial display to an Arduino?

Answers: 2

body:
That kind of connector is most commonly directly soldered on to a PCB.  You can [buy adaptor boards](http://www.ebay.com/sch/i.html?&_nkw=fpc+adapter+board) with the various different pitch pads on them for soldering it to.

![enter image description here][1]

Also there is no mention of what chip the screen uses (I am unfamiliar with "XS057" as a chip, so that is probably the model of the screen not the chip).  At that resolution it's probably an ILI9163, but without being sure all you can do is stab wildly in the dark and try different drivers.

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

body: if you have the pinout you should be able to solder the hookup wires directly to the pins if you know how to use solder paste and a heat gun and skill if you are a beginner you need to put it in a box and order something from other suppliers more friendly to newbes.


body:
I am using an Arduino Mega2560. Using Arduino Mega as ISP to burn sketch, I had loaded the bootloader from Arduino IDE.

I uploaded the blink LED code to the Mega. But the LED is responding slowly. Same with Serial code. Delay of 0.1 second acting as 1 second on my board. In code serial communication baud-rate is 9600 but I am getting proper value when I set the baud-rate to 4800 in serial monitor.

Could anyone point out the problem?

title: Arduino Mega2560 clone responding slowly

Answers: 1

body:
Either your fuses are wrong (set to 50% the real speed of your crystal / ceramic resonator), you're using the internal oscillator instead of the expected external one, or you have the wrong board with the wrong F_CPU value selected in the IDE.

Check all of those carefully.


body:
So, I've got a music degree, 5 years programming with Ruby and 7 with Pure Data. I've also got hold of an Arduino and a Raspberry Pi.

Anyway, I've seen a number of Arduino projects which involve firing events which cause a stick to hit a drum, but I really don't know where to start.

I have a wicker penguin that I want to have play the drums:

![](https://i.stack.imgur.com/uXNPFm.jpg)

 - What components do I need to produce this kind of one-off percussive event?
 - Can I trigger these events from Ruby?

title: Beginner Arduino Project: Drumming Robot

Answers: 2

body:
  - to move the arms: look for tutorials about arduino controlling a motor (either step od DC).
  - to control the arduino from a PC (or the PI) - that's what it means when you say Ruby - check how to remote control over serial port

body:
The approach I would take for the arms is to use a **servo motor** as these are fairly cheap and are **closed loop** so you don't have to add any extra sensors to check where the current position is.

### Types of Motors:

 - **Stepper motors** are a type of motor with a special arrangement of coils that allows you to turn a fraction of a degree by sending pulses to the motor. For example, you can buy a 200 step stepper motor that turns in increments of 1.8 degrees. These are somewhat expensive and require somewhat expensive drivers (usually $5-10 per driver). Often used in CNC machines and 3D printers. Continuous rotation.
 - **General DC motors** (two types: brushless and brushed, but I won't get into that in here) are a type of motor. Their drivers are often cheaper than one for a stepper motor, but you have little control over their rotation (instead of "take one step which is X degrees," you say , "turn at 25% power clockwise," where you don't know the actual speed). These are sometimes used with *rotary encoders* or *potentiometers* to control the speed and position of the spindle. Continuous rotation.
 - **Servo motors** are actually not their own type of motors; they are DC motors (not steppers) with a potentiometer built in along with the driver. You send pulses to it (you can use the *[Arduino servo library][1]* for this) to tell it the exact degree to go to. Can only go a limited range: usually either 90 or 180 degree, although you can get special ones that can turn much longer ranges than that.

### Using a Servo Motor:

You can hook it up like this:

> ![][2]
>
> *From [this Arduino Tutorial](http://www.arduino.cc/en/Tutorial/Sweep)*

And then some very simple code to use the motor:

    #include <Servo.h>

    Servo myservo;

    void setup() {
      myservo.attach(9);
    }

    void loop() {
      myservo.write(10);
      delay(500);
      myservo.write(0);
      delay(500);
    }

### Talking with Ruby:

Your best option is to use the serial port on your computer. Figure out how to access a COM/serial port in Ruby. You can then send messages from your computer to the Arduino, but you'll have to figure out a way to structure the messages.

  [1]: http://www.arduino.cc/en/Reference/Servo
  [2]: https://i.stack.imgur.com/hC7tZ.png


body: I'm looking for a way to check the air-flow from an aquarium air pump. I need something that can test whether air is flowing or not and I'm not bothered about measuring flow speed. The air will be flowing through a pipe but if required I can have the sensor on the end of an additional pipe just used for measuring.

title: How to measure whether air is flowing through a pipe?

Answers: 3

body:
Did you consider a barometric sensor deployed inside the pipe?
The pressure should be higher when the pump is active.

body:
Flow sensors tend to be expensive. However, there are many pressure sensors that provide a simple analog voltage input and others with easy to use digital interfaces.
As Igor Stoppa points out, these can be used to infer flow. Some can be purchased with tube ports that allow the user to mount the hose directly to the sensor. This would only require a "T" connector and some additional hose to connect to the air pump.

Aquarium air pumps may be pulsatile. So be sure to use an average pressure.

Average Pressure:

 - above a certain point may indicate blockage
 - between certain values indicates correct flow
 - below a certain value indicates no flow

.

body:
Grab yourself something [like this](http://www.amazon.com/Scienceware-Blue-Polystyrene-Roto-Flo-Indicator/dp/B002VBW2I4/ref=lp_3206433011_1_12?s=industrial&ie=UTF8&qid=1432915944&sr=1-12)

![enter image description here][1]

Butcher it to get inside it, and add three small magnets to the fins (should be simple enough - just keep it balanced).  Then glue it all back together again.

Add a hall effect sensor to the outside, and Bob's your uncle.

Or, since the principle of that unit is so simple, you could make your own from scratch.

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


body:
why do I end up with the display "Failed to read from DHT sensor!" in the serial monitor in most cases when I run the code given below?? In case I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false......Any help would be highly appreciated...

    // Example testing sketch for various DHT humidity/temperature sensors
    // Written by ladyada, public domain

    #include "DHT.h"

    #define DHTPIN 2     // what pin we're connected to

    // Uncomment whatever type you're using!
    //#define DHTTYPE DHT11   // DHT 11
    #define DHTTYPE DHT22   // DHT 22  (AM2302)
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)

    // Initialize DHT sensor for normal 16mhz Arduino
    DHT dht(DHTPIN, DHTTYPE);
    // NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
    // might need to increase the threshold for cycle counts considered a 1 or 0.
    // You can do this by passing a 3rd parameter for this threshold.  It's a bit
    // of fiddling to find the right value, but in general the faster the CPU the
    // higher the value.  The default for a 16mhz AVR is a value of 6.  For an
    // Arduino Due that runs at 84mhz a value of 30 works.
    // Example to initialize DHT sensor for Arduino Due:
    //DHT dht(DHTPIN, DHTTYPE, 30);

    void setup() {
      Serial.begin(9600);
      Serial.println("DHTxx test!");

      dht.begin();
    }

    void loop() {
      // Wait a few seconds between measurements.
      delay(2000);

      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit
      float f = dht.readTemperature(true);

      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }

      // Compute heat index
      // Must send in temp in Fahrenheit!
      float hi = dht.computeHeatIndex(f, h);

      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hi);
      Serial.println(" *F");
    }

title: Failed to read DHT22 sensor using Arduino Uno

Answers: 2

body:
Have you put a  4.7kOhm  resistor between data pin and Vcc on the dht22? i had problems with a reading until i did. see [this][1]
HTH

  [1]: http://forum.arduino.cc/index.php?topic=53888.0

body:
I suggest you to modify the following lines of code to check which reading has issue.

    if (isnan(h) || isnan(t) || isnan(f)) {
       Serial.println("Failed to read from DHT sensor!");
       return;
    }


body:
I am aware of the simplicity of the question.  Nevertheless...

I need to code into the arduino the execution of a file.  More precisely a .exe.
To put things in perspective.  I have little to no knowledge of coding.  Yet I need to put together a photocabin.  I have the arduino to count the coins inserted to my coin collector and I need to take a picture when the precise ammount is reached.  Then reset the ammount to avoid taking more pictures.
here is what my code looks so far: (taken from the examples on the arduino page)

    const int coinInt = 0;
    //Attach coinInt to Interrupt Pin 0 (Digital Pin 2). Pin 3 = Interrpt Pin 1.

        volatile float coinsValue = 0.00;
        //Set the coinsValue to a Volatile float
        //Volatile as this variable changes any time the Interrupt is triggered
        int coinsChange = 0;
        //A Coin has been inserted flag

    void setup()
    {
      Serial.begin(9600);
    //Start Serial Communication
      attachInterrupt(coinInt, coinInserted, RISING);
    //If coinInt goes HIGH (a Pulse), call the coinInserted function
    //An attachInterrupt will always trigger, even if your using delays

    }

    void coinInserted()

    //The function that is called every time it recieves a pulse
    {
      coinsValue = coinsValue + 0.05;
    //As we set the Pulse to represent 5p or 5c we add this to the coinsValue
      coinsChange = 1;
    //Flag that there has been a coin inserted
    }

    void loop()
    {
      if(coinsChange == 1)
    //Check if a coin has been Inserted
      {
        coinsChange = 0;
    //unflag that a coin has been inserted

       if(coinsValue >= 0.30)
      {
           here goes the code to open a file, then the code to reset coinsValue

      }
      }
    }

Thanks a million.

title: How to call a file from the arduino?

Answers: 2

body:
First of all you need to develop a windows app. You can achieve this by downloading visual studio express for windows desktop from [here][1]. Then you must create a project in your language of your preference. You will have to add a **serial port** component and set the properties to match your arduino serial ones. Then from the **event** that handles the "data available" of your serial port you can check if there is an incoming character from your arduino and create an if statement that runs the .exe file. Then you must add serial.print('c') to your code when there is a coin inserted. By doing so, you will manage to communicate between arduino and your windows app.

More info and full guide can be found [here][2]

  [1]: https://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx
  [2]: http://www.jeremyblum.com/2011/02/07/arduino-tutorial-6-serial-communication-and-processing/comment-page-1/

body:
I used the following code to run a program, not from the arduino, but from software listening to a specific character sent from the arduino.  Thanks for your help.  I share the code that I used.  It doesn´t need to print the character, but I copied it exactlyy from microsoft help pages (lost the link). I just aded the if statement and the start.process part (I got this from a stackoverflow answer).  Without any further delay:

    using System;
    using System.IO.Ports;
    using System.Diagnostics;

    class PortDataReceived
    {
        public static void Main()
        {
            SerialPort mySerialPort = new SerialPort("COM3");

            mySerialPort.BaudRate = 9600;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.One;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;
            mySerialPort.RtsEnable = true;

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            mySerialPort.Open();

            Console.WriteLine("Press any key to continue...");
            Console.WriteLine();
            Console.ReadKey();
            mySerialPort.Close();
        }

        private static void DataReceivedHandler(
                            object sender,
                            SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string indata = sp.ReadExisting();
            Console.WriteLine("Data Received:");
            Console.Write(indata);
            if (indata == "c")
            {
                Process.Start(@"C:\Users\Laptop\Desktop\print.ahk");
            }
        }
    }


body:
[Link of the member][1]
What is the character parameter in the above member of the class NRF24Network
I cannot understand the use of it.

  [1]: http://maniacbug.github.io/RF24Network/structRF24NetworkHeader.html#a99e675f31589d72cf2fe036e77988026

title: What is the type parameter on the NRF24NetworkHeader member

Answers: 1

body: It's to identify the type of packet.  Apparently that code supports types of 0-127, and I guess (impossible to tell without digging into the code) that what you use them for is entirely up to you.  Basically it would typically define what is in the rest of the packet - again something which is up to you.


body:
I have a project running on an arduino nano, and as part of it, I'd like to read from and write to a microSD card.  My problem is that the microSD shield for it doesn't fit my form factor (think slightly larger than a pen; definitely handheld).

I've purchased a PJS008-2003-0, and I'm wondering, assuming I have the soldering chops, is there any real reason I can't connect this directly?  What does the breakout board get me other than nicer connection points and a blinking light?  Do the example SD sketches rely on anything the shield provides, or will they work for me?

title: Smallest package possible reading microSD

Answers: 3

body:
Most likely you will have to add at least some pullup/pulldown resistor. I would recommend having a look at the schematics of the shield.
For example this shield:
http://freematics.com/store/index.php?route=product/product&product_id=74

And it depends on which mode you want to use (SPI?):
http://en.wikipedia.org/wiki/Secure_Digital#Transfer_modes

body:
SD card need 3.3v for power and logic level. So most breakouts have a buffer chip to convert the logic levels from 5v to 3.3v.

PS, you could use an microSD to SD adapter, and solder some wires to its pads, if you are unable to solder the tiny pins on the part you ordered.

body:
If your willing to be adventurous and step away from Arduino (as in AVR chips) and try out some of the myriad of other offerings there are around now, then you may find a better board that fits your needs.

One popular example is the [Fubarino SD](http://fubarino.org/sd/index.html):

![enter image description here][1]

It gives you a PIC32 chip (128KB RAM, 512MB Flash, 80MHz) with a microSD card slot already on the board.  And it measures just 2.5cm x 7cm.

Of course, you may need to tweak your programming a little to get it working as you want - the IDE ([MPIDE](http://chipkit.net/started/install-chipkit-software/)) is a bit old and the Arduino API compatibility is slightly behind the times (but catching up gradually). It's also fully supported by my [UECIDE](http://uecide.org) programming environment.

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


body:
Using an Arduino Mega. I have a motor hooked up exactly like the picture below. Using a BC548B transistor, 1N4001 diode, 220 ohm resistor and a 9V battery. I'm driving the motor in code by using PWM analogWrite to value 255. Weird thing is, if hooked up to USB (5V), the motor will only start to move after a certain amount of time, seems like it needs some initial "drive" to get started. If using the 9V battery it starts up quicker, but still not directly, as I would expect. Also, if I set analogWrite to some value less than 255, it will not move at all - is the transistor limiting? Can I change the resistor value to compensate? Thanks for any advice.

    int motorPin = 3;
    int interval = 10;
    int walkingTime = 7.5;
    bool walking = false;

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

    void loop() {
      delay(interval * 1000);
      if (!walking) {
        startWalk();
        delay(walkingTime * 1000);
        stopWalk();
      }
    }

    void startWalk() {
      walking = true;
      analogWrite(motorPin, 255);
    }

    void stopWalk() {
      walking = false;
      analogWrite(motorPin, 0);
    }

![Motor & Arduino hookup][1]

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

title: DC Motor not behaving reliably

Answers: 1

body:
**Summary:**

Your transistor is the wrong way round.
Rotate it 180 degree (so that collector and emitter are swapped) and it should work.

There are much better transistors available for this job, but this one should work when correctly connected.

Swap, test, report back.

The blue wire goes from emitter (right hand lead) to Arduino ground.

![enter image description here][1]

**Longer:**

The transistor is almost certainly "backwards" as above. More on that below, but first some comment on the actual transistor used and a superior alternative.

While it should work better than you describe, the BC548 is not a very good transistor for motor driving. It's maximum collector current is 100 mA. While you do not state the required motor current, within sensible limits a good guide is that the more a transistor can handle the better it will work, all else being equal. A 500 mA rated part would work better. An excellent pair of small transistor for "playing" are the BC327-40 (PNP) and the complementary BC337-40 (NPN). These have guaranteed current gains (effectively current amplification factor) of 250 and typically of 400. They are typically rated at 45V and 500 mA.
The Fairchild versions [data sheet here](https://www.fairchildsemi.com/datasheets/BC/BC337.pdf) from Digikey have an absolute maximum 800 mA rating. While the part was originally a European one it is widely available in the US and Asia and is usually about the same price as transistors with substantially inferior specs. eg see Digikey pricing below for BC548B and BC337-40 in 1, 10 and 100 quantity. The BC337 costs 1 cent more per transistor in each case. The BC337 comes in 3 versions with suffixes -16, -25 and -40. This relates to the current gain. The -40 part has an average Beta or current gain of 400. This is better (higher) than most alternatives and costs little or no more than the lower gain -16 and -25 parts.

[BC548B datasheet here](https://www.fairchildsemi.com/datasheets/BC/BC546.pdf)
[BC337-40 datasheet here](https://www.fairchildsemi.com/datasheets/BC/BC337.pdf)

[BC548B pricing](http://www.digikey.com/product-detail/en/BC548BU/BC548BU-ND/976761)
1 10 100 prices are 22 / 20 / 11 cents each.

[BC337-40 pricing](http://www.digikey.com/product-detail/en/BC33740TA/BC33740TACT-ND/1532788)
1 10 100 prices are   23 / 21 / 12 cents each.

According to that the pinout is CBE (collector base emitter) left to right looking at flat front with pins down. There are occasionally variations between manufacturers (but should not be) but if the datasheet matches your transistor it is "in backwards".

Swap C & E by rotating 180 degrees and report back.
With C&E swapped it acts like an NPN withj very low current gain.

Note: Presumable where you saay digitalWrite you meant analogWrite?

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


body:
I have two different codes. The first one makes a LCD screen count the time and print it, then when one of the buttons on the LCD shield itself is pressed, it prints the time on the top line that it was pressed. That's the one below, I apologize that it has a lot of notes though it so unless it's in the Arduino program it looks confusing.

    /*--------------------------------------------------------------------------    ------------
     Includes
     --------------------------------------------------------------------------------------*/
    #include <Wire.h>
    #include <LiquidCrystal.h>   // include LCD library
    /*--------------------------------------------------------------------------------------
     Defines
     --------------------------------------------------------------------------------------*/
    // Pins in use
    #define MILLIS_OVERFLOW 34359738
    #define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
    #define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
    // ADC readings expected for the 5 buttons on the ADC input
    #define RIGHT_10BIT_ADC           0  // right
    #define UP_10BIT_ADC            145  // up
    #define DOWN_10BIT_ADC          329  // down
    #define LEFT_10BIT_ADC          505  // left
    #define SELECT_10BIT_ADC        741  // right
    #define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing           window
    //return values for ReadButtons()
    #define BUTTON_NONE               0  //
    #define BUTTON_RIGHT              1  //
    #define BUTTON_UP                 2  //
    #define BUTTON_DOWN               3  //
    #define BUTTON_LEFT               4  //
    #define BUTTON_SELECT             5  //
    //some example macros with friendly labels for LCD backlight/pin control, tested and can be swapped into the example code as you like
    #define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
    #define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
    #define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
    /*--------------------------------------------------------------------------------------
     Variables
     --------------------------------------------------------------------------------------*/
    unsigned long currentMillis, previousMillis, elapsedMillis;
    int seconds = 0, minutes = 34, hours = 8;

    byte buttonJustPressed  = false;         //this will be true after a          ReadButtons() call if triggered
    byte buttonJustReleased = false;         //this will be true after a         ReadButtons() call if triggered
        byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for     detection of button events
            /*--------------------------------------------------------------------------------------
         Init the LCD library with the LCD pins to be used
     --------------------------------------------------------------------------------------*/
           LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2 LCD     shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
    /*--------------------------------------------------------------------------------------
         setup()
         Called by the Arduino framework once, before the main loop begins
     --------------------------------------------------------------------------------------*/
        void setup()
        {
      //button adc input
          pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
          digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
      //lcd backlight control
      digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is         high (on)
      pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
      //set up the LCD number of columns and rows:
      lcd.begin( 16, 2 );

      //Print some initial text to the LCD.
      Serial.begin(9600);
      lcd.begin( 16, 2 );

    }
    /*--------------------------------------------------------------------------------------
     loop()
     Arduino main loop
     --------------------------------------------------------------------------------------*/
    void loop()
    {
      setClock();
      byte button;

      button = ReadButtons();

      /**
       * After set clock now you have 3 int variables with the current time
       */
      //seconds
      //minutes
      //hours
      lcd.setCursor ( 0, 1);
      lcd.print(hours);
      lcd.print(":");
      lcd.print(minutes);
      lcd.print(":");
      lcd.print(seconds);
      lcd.print(":");
      lcd.print(elapsedMillis);

          //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

      //blank the demo text line if a new button is pressed or released, ready for a new label to be written

      //show text label for the button pressed
       if(buttonJustPressed || buttonJustReleased)
      switch( button )
      {

      case BUTTON_LEFT:
        {
          lcd.setCursor( 0, 0 );
                   lcd.print(hours);
                   lcd.print(":");
                   lcd.print(minutes);
                   lcd.print(":");
                   lcd.print(seconds);
                   lcd.print(":");
                   lcd.print(elapsedMillis);

          break;

        }
      default:
        {
          break;
        }
      }

      if( buttonJustPressed )
        buttonJustPressed = false;
      if( buttonJustReleased )
        buttonJustReleased = false;
    }
         /*--------------------------------------------------------------------------------------
         ReadButtons()
         Detect the button pressed and return the value
         Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
     --------------------------------------------------------------------------------------*/
            byte ReadButtons()
        {
      unsigned int buttonVoltage;
      byte button = BUTTON_NONE;   // return no button pressed if the below         checks don't write to btn

      //read the button ADC pin voltage
      buttonVoltage = analogRead( BUTTON_ADC_PIN );
      //sense if the voltage falls within valid voltage windows
      if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_RIGHT;
      }
      else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_UP;
      }
      else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_DOWN;
      }
      else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_LEFT;
      }
      else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_SELECT;
      }
      //handle button flags for just pressed and just released events
      if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
      {
        //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
    //it's the duty of the receiver to clear these flags if it wants to detect a new button change event
        buttonJustPressed  = true;
        buttonJustReleased = false;
      }
      if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
      {
        buttonJustPressed  = false;
        buttonJustReleased = true;
      }

      //save the latest button value, for change event detection next time round
      buttonWas = button;

      return( button );
    }
    void setClock()
    {
      currentMillis = millis();
          /**
       * The only moment when currentMillis will be smaller than previousMillis
       * will be when millis() oveflows
       */
      if (currentMillis < previousMillis){
        elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
      }
      else {
        elapsedMillis += currentMillis - previousMillis;
      }

      /**
       * If we use equals 1000 its possible that because of the mentioned loop     limitation
       * you check the difference when its value is (999) and on the next loop its value is (1001)
       */
      if (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
      }

      if (seconds == 60){
        minutes++;
        seconds = 0;
      }
      if (minutes == 60){
        hours++;
        minutes = 0;
      }
      if (hours == 24){
        hours = 0;
      }

      previousMillis = currentMillis;
        }

The next code is to control the speaker and makes it play happy birthday when the a proximity sensor is set off. I need to somehow merge the two codes so that when the proximity sensor is set off the speaker plays the sound, but so that the clock continues to still count. Does anyone know how I can do this?

    #include <Wire.h>
    #include <LiquidCrystal.h>

    int timer = 1000;
    int C = 262;
    int D = 294;
    int E = 330;
    int F = 349;
    int G = 392;
    int A = 440;
    int B = 494;
    int Bflat = 466;
    int Chigh = 523;

    LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );
    const int analogPin = A1;    // pin that the sensor is attached to
    const int threshold = 400;

    void setup()
    {
        // initialize serial communications at 9600 bps:
       Serial.begin(9600);
       pinMode(10, OUTPUT); // Red LED
       pinMode(12, OUTPUT); // Yellow LED
       pinMode(11, OUTPUT); // Green LED
       pinMode(13, OUTPUT); // Speaker
             lcd.begin(16, 2);
     }
    void loop()
    {
     int analogValue = analogRead(analogPin);

      if (analogValue > threshold) {

    tone(13,C,timer/2);// Happy Bday to You
    delay(200);
    tone(13,C,timer/2);
    delay(200);
    tone(13,D,timer/2);
    delay(400);
    tone(13,C,timer/2);
    delay(400);
    tone(13,F,timer/2);
    delay(400);
    tone(13,E,timer);
    delay(750);

     }
    else {
    }
    }

title: Merging two codes, one for speaker one for LCD clock (Arduino Uno)

Answers: 0


body:
I'm new to Arduino and I'd like to realize a system using Arduino One and SparkFun Electret Microphone Breakout (BOB-09964) to turn on/off lights clapping my hands. https://www.sparkfun.com/products/9964

What are the components I need? I'm going to buy them and I don't want to buy components which I will not use soon (so no starter kits but only a breadboard, resistors, LEDs, etc...).

Sorry for this basic question but as I said I'm new to this world.

title: Arduino ligths on/off clapping hands

Answers: 2

body:
If you start from the beginning of the project, instead of trying to jump in half way through, you'll know precisely what components you need.

Your first step shouldn't be trying to order components, but to identify (through research) how the technology works.

Second is to find out how it can be implemented, by looking at existing schematics and designs that other people have created.

Third is to design your own schematic.

Fourth is to prototype it.  It's only at this stage that you should be thinking about what components to order.

Go back to stage one and do the research. Thanks to the likes of Google it'll probably only take you a few minutes.

body:
See the Arduino tutorial for a [Sound Sensor Example][1].

This is a very similar project that shows the breadboard layout and code needed for a clapping sensor based on an electret microphone breakout board.

The website listed above has a list of parts needed, the circuit diagram as well as the code needed.

  [1]: http://www.arduino.org/learning/tutorials/boards-tutorials/sound-sensor-example


body:
I've got 2 Analog accelerometers and a Gyro/Acc/Mag connected to my arduino and it's been working and reading fine until a few hours ago.
I've got the arduino sending data over the serial connection and Unity reading the values and interpreting.

<!-- language: c -->

    #include <Wire.h>
    #include <LSM303.h>
    #include <L3G.h>

    LSM303 compass;
    L3G gyro;

    void setup() {
      Serial.begin(9600);
      Wire.begin();
      compass.init();
      compass.enableDefault();
      gyro.init();
      gyro.enableDefault();
    }

    void loop() {

      /* Accelerometers: */

      int sensorValueA = analogRead(A0);
      int sensorValueB = analogRead(A1);
      //Serial.flush();
      Serial.print(sensorValueA);
      Serial.print(",");
      Serial.println(sensorValueB);
      delay(10);

      /* Accelerometer + Magnometer: */

      compass.read();
      //Serial.flush();
      Serial.print(compass.a.x);
      Serial.print(",");
      Serial.print(compass.a.y);
      Serial.print(",");
      Serial.print(compass.a.z);
      Serial.print(",");
      Serial.print(compass.m.x);
      Serial.print(",");
      Serial.print(compass.m.y);
      Serial.print(",");
      Serial.println(compass.m.z);
      delay(10);

      /* Gyro: */

      gyro.read();
      //Serial.flush();
      Serial.print((int)gyro.g.x);
      Serial.print(",");
      Serial.print((int)gyro.g.y);
      Serial.print(",");
      Serial.println((int)gyro.g.z);
      delay(10);

    }
If I have it unplugged for several minutes then replug it, the print will work for a min or two then just stop completely. I've checked wires several times and it hasn't moved since it was working this morning.

As I said, which I think is probably of importance, the TX light is off when not printing.

![enter image description here][1]
*Acc1:* GND - GND | VCC - 3.3v | Y - A2

*Acc2:* GND - GND | VCC - 3.3v | Y - A3

*Gyro:* VIN - 5v | GND - GND | SAO - A4 | SCL - A5

Thanks

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

title: TX light not flashing, screen.print works sometimes.. UNO

Answers: 0


body:
Good evening :)

I am fairily new to coding the fabulous Arduino UNO. My project right now are consisting of reading Temperature from a DHT22 (AM2302) and writing to a 4-digit 7-segment display. I have got the display to work, but the system does not update the temperature at all. Just the first reading are displayed

    #include <DHT.h>
      #include <TimerOne.h>
      #include <SevenSeg.h>

      #define DHTPIN 4    //Defines the temp-pin

      /* DHT22- Pin1 (left) - 5V/3.3V
      Pin2- DATA
        Connect a 10K res from pin1 to pin2
      Pin3 - NC
      Pin4 - GND
      */

      //#define DHTTYPE DHT11   // DHT 11
      #define DHTTYPE DHT22   // DHT 22  (AM2302)
      //#define DHTTYPE DHT21   // DHT 21 (AM2301)

      DHT dht(DHTPIN, DHTTYPE);

      SevenSeg disp (13 ,2 ,3 ,8 ,5 ,6 ,7);
      //            (11, 7, 4, 2, 1, 10, 5)
      const int numOfDigits =4;
      int digitPins [ numOfDigits ]={9,10,11,12};  // uten transistorer
      //                            (12,9,8,6) Alle med 220 Ohm seriemotstand
      //int digitPins [ numOfDigits ]={12,11,10,9};  // med transistorer

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

        disp . setCommonCathode();  // uten transistorer
        //disp . setActivePinState(HIGH,HIGH);  // med transistoere
        disp . setDigitPins ( numOfDigits , digitPins );

        Timer1.initialize(15);   // 0.015 sek
        Timer1.attachInterrupt(loop);
      }

      void loop() {

        dht.begin();

        delay(300);
        float t = dht.readTemperature();

        disp.writeFloat(t);
        Serial.println(t);

      }

How do I get the Sensor to update regularly?

title: DHT22 Does not update

Answers: 2

body:
Try this in your loop method
The while loop will read the temperature, write to the display and write to the console.

    void loop() {
      dht.begin();
      float t;
      while(1)
      {
        t = dht.readTemperature();
        disp.writeFloat(t);
        Serial.println(t);
      }
      delay(300);
  }

body:
Try moving `dht.begin();` to `setup()`.

The DHTs are pretty slow and need some time (of the order of seconds!) between consecutive reads. In `dht.begin()` an internal timer is reset that is used in `readTemperature()` to ensure that reading data from the DHT is not attempted in shorter intervals than supported. By calling `dht.begin()` every 300 ms you're making this meachanism inoperative. You're supposed to call `dht.begin()` only once at start-up.

**Edit**: And please also remove the `Timer1` that calls `loop`. `loop` is already an infinite loop, so no good in calling it additionally from an interrupt...


body:
I am using Arduino Duemilanove and a hall effect sensor to calculate the speed of a motor.  When I used sensor out directly to Interrupt0, the rising edges of noise were also detected. So the speed calculation went wrong.

 So now  sensor is connected to A0.and a threshold is put. Pin No 13 is connected to Interrupt 0(Pin 2). I use the following code.

    volatile byte count;
     const int analogPin = A0;
     const int digitalPin=13;
     const int threshold =20;
     unsigned int rpm;
     unsigned long starttime;

     void setup()
     {
       pinMode(digitalPin,OUTPUT);
       digitalWrite(analogPin,HIGH);
       digitalWrite(digitalPin,HIGH);
       Serial.begin(9600);
       attachInterrupt(0,sense,FALLING);
       rpm=0;
       starttime=0;
       count=0;
     }
     void loop()
     {
       int sensorValue = analogRead(analogPin);
       Serial.println(sensorValue);
       if (sensorValue < threshold)
       {
         digitalWrite(digitalPin,LOW);
         if (count>=20)
         {
           rpm=60*1000*count/(millis()-starttime);
           starttime=millis();
           count=0;
           Serial.println(rpm,DEC);
         }
       }
       else
       {
         digitalWrite(digitalPin,HIGH);
       }

     }
     void sense()
     {
      count++;
     }

But I get actual speed only in between. The speed changes back . I feel there is some problem with the sampling or rpm updation. Looking forward for help

title: Hall sensor noise removal

Answers: 3

body:
           rpm=60*1000*count/(millis()-starttime);

Since rpm is an unsigned int (which has a maximum of 65535) you will almost certainly overflow if count is more than 1, which will give you negative numbers, or incorrect positive numbers.

Plus, outputting to serial constantly will cause the program to lock up waiting for the serial buffer to empty, which will throw out any timings you are doing.

I suggest making rpm unsigned long (or float as you seem to have done already) and only display the RPM every second or so.

---

Also see my page [Using the Arduino Analog Comparator](http://www.gammon.com.au/forum/?id=11916). This is a much faster way of detecting an analog signal merely passing some threshold. This only takes a few microseconds compared to 104 µS for a single analogRead. In the ISR then you just add one to a counter (which is the number of times it passes the threshold). Every second take this counter, and work out the RPM, then zero it. Make sure you make a copy of the counter in a protected way as shown on my page about [Interrupts](http://www.gammon.com.au/interrupts).

body:
A possibility I am toying with for a similar problem is realizing that there will always be a delay between valid sensor readings.  For example, imagine you had a maximum speed of 10 revolutions/second.  That would mean that there would be a maximum of 10 sensor inputs/second or 1 interrupt every 100 msecs.

If you changed your interrupt processing logic to something like:

    if (millis() - timeOfLastSensorReading >= 10) {
       count++;
       timeOfLastSensorReading = millis();
    }

Then your logic would become "Only register a sensor change if at least 10 msecs has passed since the last reading".

You might have to tune the values based on your real situation ... but it might go a long way to eliminate some aspects of false readings.

body:
It sounds like you need a debouncing circuit.
You can do it in code, but you are then trying to execute more code in you interrupt handler.
I would go for a hardware version.  I don't have the circuit to hand but if you search for a 'Schmidtt Trigger' based debouncing circuit.  You can implement it with 5 resistors, a capacitor, a LM386 OpAmp and a CMOS XOR IC (Inverts the signal which the inverting Schmidtt trigger inverts).

What happens is the Schmidtt trigger goes low when the input passes a certain voltage.  It remains low until the voltage passes the low voltage threshold at which point it goes high.  The CMOS XOR IC (I think its a 4004??) takes two inputs and inverts them.  It also adds extra hysteresis which further damps the bouncing.

The values of your resistors affect the thresholds, but there are plenty of calculators on the web that will solve the values for you.

The LM386 has two channels and the CMOS usually has 4 so it becomes quite easy to debounce multiple signals.

Hope that helps.


body:
can somebody tell me what`s wrong with my code, i am using it to calculate rpm using incremental encoder

    long counter=0;
     long  rpm = 0, z =0;
     long  ini_time = 0;
    long  end_time=0;

    void setup(){
      attachInterrupt(0, A_RISE, RISING);

      Serial.begin(115200);
    }//setup

    void loop(){

        Serial.println(rpm);
    }

    void A_RISE(){
      counter ++;
      if (counter == 1)
        ini_time = micros();
      else if (counter>470){ //470 is ticks per revolution
        z = counter;
        rpm_counter(z);

        counter =0;
      }
    }

    void rpm_counter(int x){

      end_time=micros()-ini_time;
      rpm=(60*10^6)/end_time;

    }

title: Incremental encoder code

Answers: 1

body:
**Volatile**.

Essentially any variable declared within global scope (anything you declare before you get to `setup()`) MUST have the `volatile` qualifier if you want to use it within an interrupt service routine otherwise it will not be correctly utilised/implemented/instantiated.

As your code stands, you need to add `voltatile` to all four of your global variables:

    volatile int counter = 0;     // if you're stopping at 470, int is all you need
    volatile long rpm = 0;
    volatile long z = 0;          // this isn't necessary, see below!
    volatile long ini_time = 0;
    voltaile long end_time = 0;

Your ISR includes some wasteful instructions, which will increase the time it takes for the routine to complete. As @jfpoilpret suggested, you may be constantly interrupting `loop()`. Cutting the time down may solve this:

Firstly, `z = counter; rpm_counter(z);` . Pointless, if I'm honest. Why not just call rpm_counter with counter?

Secondly, `rpm_counter()` function... it doesn't use the arguement you sent! "`x`" is not used anywhere within the function, so why are you sending it?

Thirdly, even if my second point wasn't valid `rpm_counter()` doesn't really need to be a function in its own right. Unless you're going to be calling it from lots of different places, just inline the contents of the function to into `A_RISE()`:

    else if (counter>470)
    { //470 is ticks per revolution
        end_time = micros() - ini_time;
        rpm = (60*10^6) / end_time;
        counter = 0;
    }

That could save a great deal of execute cycles.


body:
I am looking at creating a fleet of low power, Arduino driven devices.

I would need some kind of GPS on them all (or could triangulate through phone network?) plus a connection to the internet - just for HTTP POST requests. GPRS or GSM would do but 3G would be better.

What are the best (price is a major factor because I'm trying to do a fleet) GSM, GPRS or 3G modules that I can use with Arduinos? As I said, I need their location so one with GPS built in would be great.

EDIT:
The amount of devices in the fleet will change, so the entire network needs to be dynamic which is why having a GPRS/GSM module on each one would work so well.

title: Cheapest Arduino GPRS or 3G solution

Answers: 3

body:
Not many possibilities (for the phone part, I suggest a GPRS/3G shield), but not wanting to discourage you, if you are thinking about "a fleet", forget about:

low power (the phone radio needs power, some say you need > 1A for both Arduino plus the shield, depending on your distance to the antenna). you must add the GPS part. Even if you communicate just a fraction of the time, you need instant power for feeding the radio.

low price (gprs shields are not cheap, starting at some 25€, and gps shields about 20€). and don't forget that you need a SIM card with a data plan for every unit....

Depending on what are you trying to achieve, I'd try with less expensive (RF communications, for example) to avoid carrier costs and hardware costs, at the price of a more complex development.
If you want to publish to a web service, you can always make your minions transmit to a centralized Raspberry PI, for example, that would take the task of bridging with the Internets, or your mastermind...:-D

body:
a few new ones have hit the scene recently. There's one by the folks that made the particle board (the electron supports 2G and 3G). There is also a kickstarter by sixfab that made one for the pi-zero footprint (but it's a standard raspberry pi GPIO and also has USB connection support or you can bread-board it to an arduino). They make a more expensive plate on standard RPi footprint that supports laptop-style WWAN modules (bought separately) so it can do 3G or 4G/LTE.
One of the better one's I've seen recently is actually part of the AT&T offerings (I believe avtel is the one that put the packages together for them). If you google AT&T IoT starter kit, they have four different offerings, with the lowest being $59. (it's apparently used as just a modem and can be connected via gpio style pins or via usb) It comes with a sim with 300Mb and 300 SMS messages good for up to 6 months from date of activation.
There are a few higher end chips coming out with LTE and 4G support also from Simcom (the makers of the Sim900 based devices core chip). Boards I have seen built on their LTE based devices run in the $80-120 range so, unfortunately they don't qualify as cheap.
As of yet, I haven't seen anything with 3G or higher under the $40 mark though. Most of them start above $50 and go up. Maybe by the time 2G is completely phased out, LoRa will be well saturated?

body:
If you are finding Cheapest and working module you can you SIM800L less then 4$.

[![Sim800L][1]][1]

    aliexpress.com/item/Free-Shipping-Smallest-SIM800L-GPRS-GSM-Module-MicroSIM-Card-Core-BOard-Quad-band-TTL-Serial-Port/32708504554.html

You can find many other cheap alternative but they does not work properly.

Sim800 have good support and you can find many examples to use this with arduino.

Many other model also available in market as per your requirements.

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


body:
I have tried to connect a GSM dongle to a Intel Galileo Gen2 board and test the functionality of sending and receiving SMS through it.I know that it is easier to use a GSM shield to do above, but I'm currently doing a project in the way i mentioned above.Basically in Linux, we should know the serial port(like `ttyACM0` in `/dev` directory) correspond to the device to communicate with it(Using AT commands).

but when i tried it in Galileo board it doesn't show such a serial port.but it detect device because `lsusb` command shows the device.

does anyone can help me to solve this matter?

title: Connecting GSM Dongle to Intel Galileo-Gen 2

Answers: 1

body:
Try updating the firmware. I'm not sure if this affects also ACM type serial ports, but the initial version of the firmware was not even creating standard /dev/ttySx, rather some weird proprietary interface.
Luckily this was fixed later on. So, in case you are still running the FW that the board came with, chances are you are having these weird serial ports.


body:
I bought an OV7670 camera and I would like to use the following code:
https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno

But I wonder whether it is possible to use SPI instead of I2C when I transfer the image data through Arduino to other breakout boards.

title: Transferring OV7670 data with SPI port

Answers: 1

body: I2C is not used to get the pixel data. That is used only to configure the ov7670. You can read the pixel data by reading the IO PORTS and then send the data via SPI.


body:
I have included the **RF24Network** library in my project. I tried to use the Simple Transmit/Receive example from [here][1] but when it calls the **network.begin()** my arduino restarts. I placed some **Serial.println()** in order to understand where is the problem. This problem appears only in my Arduino Mega 1280. I tried the same code on my Arduino Pro mini and it works like a charm. What causes this? How to fix that? It is very important to use the specific library. Thanks in advance.

  [1]: https://maniacbug.wordpress.com/2012/03/30/rf24network/

title: Arduino resets when I call network.begin()

Answers: 1

body: The problem was that the RF24Network library is **not compatible** with the version of Arduino IDE I have. I downloaded Arduino IDE v1.0 and now it works like a charm. I will send an email to maniacbug to tell him about the problem.


body:
hej guys,

recently I upgraded to Arduino's 1.6.4 IDE just to find out, that I can't seem to upload anything to my board. More specifically: The 1.6.4 IDE is not giving me the option to select the /tty/ board from the serial port list. I am avid Sublime Text 2 user, so obviously I tried to select the port in Stino and voilá: I was **able** to upload it to my boards.

Since I wanted to sort out if this is a software or hardware problem, I started to experiment with all my boards:

(all of them official boards, no clones)

 - 2 x Arduino Micro
 - 1 x Arduino Uno r3
 - 1 x Arduino Duemillanove
 - 1 x Arduino Mega 2560 r3
 - 12 x Teensy 3.1
 - a bunch of different USB cables.

none of these boards were registered by the Arduino 1.6.4 IDE, even after restarting the software and the computer several times. i'd only get this in my port selection:
![serial ports only showing /cu/][1]

funny enough, my terminal told me the /tty/ device was there. here with the uno connected:

    Dash:~ julianh$    ls /dev/tty.*
    /dev/tty.Bluetooth-Incoming-Port
    /dev/tty.Bluetooth-Modem
    /dev/tty.usbmodemfa131

I also tried to re-install FTDI drivers, with no results.

only when I installed the old (trusty) 1.6.1 version, I was able to upload again.

all of the boards are also working fine. I just used my uno and mega another machine a few days ago for some side projects.

can someone confirm this problem with the new IDE 1.6.4 on OSX Yosemite 10.10.3? or is there any solution available online?

thanks!

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

title: Arduino 1.6.4 not showing any /tty/ options in Serial ports

Answers: 1

body:
I had the same problem when updated to 1.6.4, but with a Spark fun Pro micro.
Did a "reset to bootloader" on the pro micro, and hit upload, and it worked
 out nice and it still does!


body:
I am currently working on a project, where I design a PID-Controller for a 2-axis stabilization with brushless-propeller-motors.

My question is: Does an Arduino UNO have enough computing power to perform this task in a useful manner? [Arduino UNO Specs][1]

And secondly: If the UNO was really too slow for this task, would the newly released Arduino ZERO PRO perform at an acceptable rate? [Arduino ZERO PRO Specs][2]

Thanks for your help and inputs in advance!

  [1]: http://www.arduino.cc/en/Main/ArduinoBoardUno
  [2]: http://www.arduino.cc/en/Main/ArduinoBoardZero

title: Arduino UNO/ZERO PRO, enough computing power for PID-controller?

Answers: 1

body:
Assuming you're not doing anything too fancy, yes, it should be fine.

There's even a library to do all the work for you: http://playground.arduino.cc/Code/PIDLibrary


body:
I have two projects in my Visual Studio Community 2013 solution.

I created a project for Arduino, and create another project for Test. When I run the project tests without adding the Arduino project reference, it run ok, but when I add the Arduino project reference I get it error:

    LNK1561: entry point must be defined D:\VisualStudioArduino\PrinterProject\LINK PrinterProject

What is the entry point for Arduino project?

It does not generate any file like a dll or main file?

What can I do to solve this error?

## UPDATE I

I also tried this configuration in the Arduino Project but I get the same error:

    Properties -> Linker -> System -> SubSystem to "Windows (/SUBSYSTEM:WINDOWS)"

## UPDATE II

I am using Visual Micro extension. But the problems is when I try to compile the Test project. Then I recreate this scenario with a C++ console application and create a simple class, and create a test project and added the console application reference to test project and it worked. Then my doubts is about to how do I configure a Test Project to test my Arduino project.

title: Testing Arduino with Visual Studio Community 2013 raise LNK error

Answers: 4

body:
Visual Studio knows nothing about an Arduino project. Why would you be trying to reference it from the other project.  Short answer is that you are not  understanding how to use Visual Studio and / or Arduino. Are you using it with some plugin for visual studio? If you are more than likely it does not support being part of a multi solution (at least that has been my experience with them).

Long answer is give some more details about what you are trying to do, including code from both projects.

Update: Sorry but this is not an Arduino topic. You are fundamentally incorrect in your understanding of how compilers and linkers work and what they are for. As are the other answers.  You can not reference a project compiled for an Arduino, from a project compiled for Windows, period.  I ask you to explain what you were trying to do and I would give you some idea how to accomplish that, but you did not answer. Yes you can use Visual Studio to compile your Arduino project, I do it every day. But I do not 'reference' it from another project on Windows. Do you have any idea what a reference is?

update 2: You can not create a test suite for an Arduino project, at least not in the traditional way. You can not even debug an Arduino project in the traditional way.  Arduino is for prototyping, and very basic beginner stuff, and nothing more. What you are asking about is more traditional development, and the Arduino is not for that (and does not do it very well).

Create 2 separate solutions. One with only your visual micro project for the arduino, and another separate solution with a regular C++ or C# project, not a test project or anything special, just a plain console, or winforms, or WPF project.  The 2 pieces of code must be run at the same time (F5), and probably connect to each other via the serial port, but it depends on what you are doing.

This IS NOT testing in a traditional sense. This is test running a project. The traditional sense of testing is to test isolated portions of code, which is different, and again, can not be done with an Arduino and visual studio.  Since the Arduino only remotely provides 2 wire debugging, and I have never heard anyone actually get it to work at all, you can NOT do any traditional debugging or testing with an Arduino. Instead you are limited to beginner hacks (serial.print).

body: I use Visual Studio Community Edition 2013 along with the Visual Micro extensions, which I think is what you need as the "missing link" between VS and Arduino.

body:
You are trying to build a Windows program.  You need a main() function as an entry point.  I suspect that when your code is built through the Arduino IDE it adds in a main function in.
You can tell Visual Studio to build your files differently by defining some build rules, but it sounds like someone may have done this sort of thing by looking at the other answers.
But the easiest short term solution would be copying and pasting into the Arduino IDE.

body:
The best place for answers is in the [Visual Micro forum][1].

1. Be sure about is that the main .ino source file of your Arduino project matches both the name of the Visual Studio project and the name of the folder they existing in. For example:

 -   Folder = Sketch1
 -   Master Source = Sketch1.ino
 -   Visual Studio Project Name = Sketch1

This ensure Visual Micro will compile the project and also it will be compatible with the Arduino Ide.

2. With two projects in a Visual Studio solution it is important to note which is the "Startup Project". You can control which is the startup by right clicking a project in the explorer and clicking "Set as Startup project". The project name will then appear in **bold**.

The startup project affects which project is uploaded/started/debugged when you click any of the "Start" commands.

3. The menu item "Build>Configuration Manager" allows you to exclude your Arduino project from Visual Studio Win32 builds but changing this option should not normally be required.

4. You can right click each project and click "Start>New instance" to override the current "Startup project" and specifically build and upload a project.

**Summary**

If the build/upload fails and you see the visual studio c++ compiler error that you have described above this means that Visual Micro is not handling the build process for the project.

Therefore, please confirm point *1* is correct by trying out build task described in point *4* above.

It would be useful to know which build command you are selecting when the problem happens.

  [1]: http://www.visualmicro.com/forums