body:
I'm making a project where my plan is to take sensor input from the Arduino, and then pass that info (by serial/usb connection) through either a laptop or a Raspberry Pi and convert it to Json and send it to a webservice in asp.net c#, where it gets stored in a database, and then the data can be shown on a website, so the visitor can see live data from the Arduino sensor on the site and also be able to see what the sensor measured yesterday, last month, or the average for a extended period of time, or a graph.

It might be easier to illustrate what I'm talking about:

![enter image description here][1]

The PC / RPI part is optional, it can be using either one.

There are a few options, as I see it, as to which methods could work. But I am unsure about how to implement them and what programs to use for it.

First one is to log data to a file on the PC/RPI and then have some shell script either listen for changes and then combine a Json string with the newly added info to the file and send it of to the webservice.

Second one is to somehow take the Serial data from the Arduino and have some shell script or program listen for any data coming from the Arduino and converting it to Json, and sending it of to the webservice. The pro's by this method would be omitting the extra "file-step", but it would make the system more vulnerable to any interruptions in the connection.

Does anyone have experience with doing something like this? Or maybe have an idea how I can do what I'm trying to do ? Or just a nudge in the right direction, as to which approach you think is best, or what programs I could/should use.
Any help is very much appreciated!

Best regards
Daniel

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

title: How to send Json to a webservice from pc/RPI with live data from Arduino(serial)

Answers: 1

body:
I'm kind of tackling the same thing at the moment.

I have been using MQTT for a while for things like this. Including on an Netduino, an Arduino, and today a LEGO NXT.

But it is TCP based. I have been wanting to use serial, not TCP (ethernet) for a while, and when the need came for the NXT, it was time to write my own bridge to existing code.

I runs on the same host as the MQTT broker, but listens to a serial port, and mirrors the data to a TCP MQTT broker.

The code is turning out to be much simpler than I expected, I should have done this months ago.

Nxt Side

    while (true)
 {
  float x, y, z;
        DIMUreadGyroAxes(IMU, x, y, z);

  char json[128];
  sprintf(json, "PUBnxt/Gyro,{\"x\":%f,\"y\":%f,\"z\":%f}\n", x, y, z);
  nxtWriteRawHS(json, strlen(json), 0); // wireless serial over xbee
  wait1Msec(50);
 }

PC side

     void Serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort p = sender as SerialPort;
            while (p.BytesToRead > 0)
            {
                string line;
                try
                {
                    line = p.ReadLine();
                }
                catch (IOException)
                {
                    throw;  // +++timeout
                }
                // parse it, it should be CMDtopic[,payload]
                if (line.Substring(0, 3).Equals("PUB"))
                {
                    int commaIdx = line.IndexOf(',', 3);
                    string topic = line.Substring(3, commaIdx - 3);
                    string payload = line.Substring(commaIdx + 1);
                    Console.WriteLine("{3}: {0}, publish topic({1}) payload({2})", p.PortName, topic, payload, DateTime.Now.ToLongTimeString());
                    Mqtt.Publish(topic, System.Text.Encoding.UTF8.GetBytes(payload));

                }
                else if (line.Substring(0, 3).Equals("SUB"))
                {
                    string topic = line.Substring(3);
                    Console.WriteLine("{0}, subscribe topic({1})", p.PortName, topic);
                    throw new NotImplementedException("MQTT Subscribe not implemented yet");
                }
                else
                {
                    //Debugger.Break();   // ignore it, framing error
                    Console.WriteLine("{0}, Data dropped", p.PortName);
                }
            }
        }

You might also want to look at [data.sparkfun.com][1]. A similar, complete concept, already existing.

  [1]: https://data.sparkfun.com/


body:
I'm using a sonar sensor to detect proximity, and need to control the brightness of an LED strip in direct relationship to the distance detected. For example, as someone moves toward the sonar, the strip needs to dim.

I'm using map() to do it now crudely but it's way too abrupt and I'm not sure how best to achieve the effect I'm looking for. Ideally, as the person moves toward the light, it very smoothly fades out in relationship to the person's movement/pace.

Initial thoughts / questions:

-- Can I use a more refined number type to set the LED brightness other than int?
-- Do I need to do something more complex where I detect the delta in the person's movement and use the loop to fade the LED from one value to another? Seems complicated...

Any help / ideas on this would be much appreciated! Existing code is below if it helps.
Claudia

    //variables needed to store values
    long pulse, inches, cm;

    //LED VARIABLES
    int frontPin = 6;    // front strip connected to PWN pin 5
    long interval = 8000; // interval at which to do something (milliseconds)
    int val;

    void setup() {
      //This opens up a serial connection to shoot the results back to the PC console
      pinMode(frontPin, OUTPUT);
      pinMode(pwPin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
        //Used to read in the pulse that is being sent by the MaxSonar device.
      //Pulse Width representation with a scale factor of 147 uS per Inch.

      pulse = pulseIn(pwPin, HIGH);
      //147uS per inch
      inches = pulse/147;
      //change inches to centimetres
      cm = inches * 2.54;

      if (inches < 36){
        detect();
      }
    }

    void detect(){
      Serial.print(inches);
      Serial.print("in, ");
      Serial.println();

      val = inches;
      val = map(val, 6, 36, 0, 255);

      analogWrite(frontPin, val);
      Serial.print("mapped value is ");
      Serial.print(val);

      delay(500);

    }

title: Fade LED strip using proximity and map() function

Answers: 1

body:
The biggest problem is that by forcing the code to use integral inches you've restricted it to 31 discrete values. And since the brightness response of a PWMed LED is non-linear you effectively have *very* large steps in brightness when the LED is dim.

`pulseIn()` has *much* more flexibility with regards to its range so use the raw value directly instead of converting it to "pretty" values.

    val = map(pulse, ..., ..., 0, 255);


body:
I am trying to communicate with a client(PC) from my arduino (set up as a server with a sim900 module connected via UART). I have successfully got it to register its IP address with a dynamic DNS provider (no-ip.com) and set up a TCP server using the AT+CIPSERVER command for the sim900. All this is done in setup(). After that in loop() it waits for a client to connect. The moment a client connects the problem arises. The code is:-

    void loop()
    {
      while(Serial.available() <= 0);
      int x=0;
      char server_recv_string[30];
      while(Serial.available()>0)
      {
        server_recv_string[x] =  Serial.read();
        delay(10);
      }
      Serial.println(server_recv_string);
      sendATcommand2("AT+CIPSEND",">","ERROR",1000);
      sendATcommand2("I hear you\x1A","SEND OK","ERROR",5000);
      while(Serial.available()>0)  // I dropped this in to clear out the input buffer.
      {                            // Doesn't help
        Serial.read();
        delay(10);
      }
      Serial.flush();
    }

The sendATcommand2 is a function as given below. I don't think that has any fault in it because it seems to work fine for all the other commands in setup. However this is the code:-

    int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
        char* expected_answer2, unsigned int timeout){

        uint8_t x=0,  answer=0;
        char response[100];
        unsigned long previous;

        memset(response, '\0', 100);    // Initialize the string

        delay(100);

        while( Serial.available() > 0) Serial.read();    // Clean the input buffer

        Serial.println(ATcommand);    // Send the AT command

        x = 0;
        previous = millis();

        // this loop waits for the answer
        do{
            // if there are data in the UART input buffer, reads it and checks for the answer
            if(Serial.available() != 0 && x < 100){
                response[x] = Serial.read();
                x++;
                // check if the desired answer 1  is in the response of the module
                if (strstr(response, expected_answer1) != NULL)
                {
                    answer = 1;
                }
                // check if the desired answer 2 is in the response of the module
                else if (strstr(response, expected_answer2) != NULL)
                {
                    answer = 2;
                }
            }
        }
        // Waits for the asnwer with time out
        while((answer == 0) && ((millis() - previous) < timeout));

        return answer;
    }

The when I monitor it on the serial terminal I get infinite sends to my client. Its like this:

     AT+CIPSEND
     I hear you

     AT+CIPSEND
     I hear you

     AT+CIPSEND
     I hear you

     AT+CIPSEND
     I hear you

     // And on and on and on.

Any idea why this is happening? If you guys need any more information, please do tell me.

Thanks

Taz

title: How to send data to sim900 only once in loop()

Answers: 1

body:
You can use a boolean variable to decide if you are going to execute the send command. You can set the variable to true in the setup and to false after the command is executed.

If you introduce the send call inside an *if (your boolean variable == true)*, it will only be executed in one loop iteration.

You can execute it again anytime you like setting the variable to true at any moment.


body:
I'm using Serial.read(); to read keyboard input from the serial monitor.
It only sends the characters after hitting enter or clicking the "send" button.
Is there a way to read keyboard input without having to use "enter"?

title: Reading keyboard input

Answers: 1

body: Not with the Serial Monitor built into the Arduino IDE. It is possible to use an external terminal program with buffering disabled though.


body: I purchased a ACS711 Hall effect-based linear current sensor (http://www.pololu.com/product/2197) and when i read the input it's basically always the same. After doing some research I think it's because there is only a 10bit AD converter and since the current is only changing a little bit it's not enough to catch the change. For my situation I'm pulling around 40-90ma idle and when the motor turns on it jumps up so I want this sensor to see that but it only jumps up to about 120ma. Any tips on how to fix this? Maybe a different sensor? Can I use an amplifier to boost the analog signal?

title: How can I increase resolution for current sensor?

Answers: 2

body:
In default configuration, the Arduino's ADC has a range of 0v-Vcc (5v or 3.3v depending on the model). If you are sure your input voltages will always be way lower than Vcc, spreading the ADC's resolution over that range is a waste of accuracy. What you need to do is to **[properly configure your analog reference voltage][1]**.

Basically, this is a way of telling your Arduino "instead of spreading your ADC's bits over a range of 0v to Vcc, just cram all that accuracy between 0v and `[refVoltage]`."

So:

 - Measure the highest analog output your sensor will give.
 - Setup a voltage divider to output a little more than that
 - Connect the voltage divider's output to the AREF pin
 - in `setup()`, declare `analogReference(EXTERNAL);`

And that's basically it. As noted, in this specific case you'd probably be better off buying another sensor altogether. However, you won't always have that luxury, and knowing how to set the analog voltage reference always comes in handy.

  [1]: http://arduino.cc/en/Reference/AnalogReference/

body:
First, let's look at where you are now.  The sensor you have reports current changes at 110mV per amp.

That means 40mA => 4.4mv, 90mA => 9.9mv, and 120mA => 13.2mv -- all very small voltages and small changes in voltage.

Let's work backward, tho.  A 5V Arduino in typical ADC mode has a resolution of about 5 mV (5 V / 1024 counts), whilea 3.3V Arduino would have a resolution of about 3.3 mv).  Divide those step sizes by 0.11V/A sensitivity and you'll see that a different of 1 count on the ADC will represent about 45ma (5V Vcc) or 30 ma (3.3V Vcc).  But there is always inaccuracy and noise, so it's going to be hard to reliably distinguish between 90mA and 120 mA (using your figures).

You can improve that somewhat by switching to a sensor with higher sensitivity (and lower maximum range) like https://www.pololu.com/product/1185 which improves the sensitivity to 185 mV per amp.  The step size of the ADC converters would translate to about 26 mA (@5V) or 17.5 mA (@3.3V).  That's still pretty tight.

You **might** be able to manage with the more sensitive sensor and a 3.3V Arduino - if you use capacitors to filter out the electrical noise on the sensor to ADC input, and you average multiple readings in your code to further smooth the values.  But it would be marginal.

So you need to amplify the sensor.  Yes, you could do that with an external amplifier, like an op Amp.  A transistor is more difficult because you need it to stay fairly linear which gets trickier, and you may need more than one stage - so an op amp is easier.

There's another tricky factor - you need to compare the voltage from the sensor to some reference - Vcc/2 for your sensor, and 2.5V for the more sensitive one.  The current is proportional to the difference between the sensor reading and that reference (the current going one way for sensor output above reference, the other way for sensor output below reference).

I'll mention another option - you could use an Arduino Mega or Leonardo.  These chips offer the option of differential inputs (one pin goes to the signal, and one to the reference), and they have built in selectable amplifiers with up to 200x amplification.  That should give you plenty of resolution, without needing to use external active analog circuitry.

You will still need to filter the sensor output to smooth spikes from the motor (current spikes translated to voltage spikes by the sensor).  You may need to also filter the Arduino Aref input with a cap.

Suppose you were to use an Arduino Mega or Leonard with the sensor you have.  You'd want a Vcc/2 reference, which could simply be two identical resistors (say 10K ohm) between Vcc and Ground as a voltage divider (and maybe a cap to ground for filtering).  You would still probably need to calibrate by finding the ADC value for no current as your reference and subtract that from the reading you get when current is flowing.


body:
I'm working on a project were we are trying to attach accelerometers to soccer players and capture various aspects of movement data.  Breadboarded circuits are coming along nicely and I'm now looking for how to best protect sensors we can mount on players.  (All wire at the moment unfortunately - BT next.)

Although I can find ways to protect the sensor for sensor damaging impact (we are essentially interested in player impacts with the ball or ground) there are other aspects of protection I'm not sure about.  Any recommendations on how to protect from moisture without increasing bulk too much, minimizing cushioning which could affect the data and of course avoid adding anything that could injure the player?  I have come across other examples of movement studies, but they have been by musicians or other situations that do not include outdoor weather and sweaty bodies.

title: How to protect sensors used on atheletes?

Answers: 1

body:
The only way this is ever done is with some kind of product casing. You can buy pre-fab cases for electronic projects, but to get something really slick and appropriate for your purpose, you're gonna have to make something yourself. You might look into 3D printing.

Something like this might work: https://www.sparkfun.com/products/8601

For protection from salt-water, this product is worth a look: http://www.corrosionx.com/

There's some different products there, but I've seen a demo of that product, where we ran an entire RC airplane system, servos, motors, and receiver, UNDER WATER.


body:
I recently purchases and make a Arduino RBBB with a BUB II from Modern Device. I ordered the package found [HERE][1]. I built everything according to the instructions, but when I connect it to my laptop (running Ubuntu 14.10), I get the following in dmesg

    [63415.213391] usb 3-1: new full-speed USB device number 63 using xhci_hcd
    [63415.381403] usb 3-1: device descriptor read/64, error -71
    [63415.485225] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 26.
    [63415.485240] usb 3-1: hub failed to enable device, error -22
    [63415.597236] usb 3-1: new full-speed USB device number 64 using xhci_hcd
    [63415.709154] usb 3-1: device descriptor read/64, error -71
    [63415.813102] xhci_hcd 0000:00:14.0: Setup ERROR: setup context command for slot 27.
    [63415.813116] usb 3-1: hub failed to enable device, error -22
    [63415.925108] usb 3-1: new full-speed USB device number 65 using xhci_hcd
    [63415.925270] usb 3-1: Device not responding to setup address.
    [63416.129120] usb 3-1: Device not responding to setup address.
    [63416.332902] usb 3-1: device not accepting address 65, error -71
    [63416.444973] usb 3-1: new full-speed USB device number 66 using xhci_hcd
    [63416.445174] usb 3-1: Device not responding to setup address.
    [63416.649008] usb 3-1: Device not responding to setup address.
    [63416.852734] usb 3-1: device not accepting address 66, error -71
    [63416.852813] usb usb3-port1: unable to enumerate USB device

It is repeatable every time I insert. lsusb does not register it. I have read that I should switch out the cable, but it is brand new (and I don't have another to test with. I was wondering if there is something evidently wrong with my circuitry. I posted pictures

![Top Down][2]
![Side][3]
![Bottom][4]
![Side][5]

  [1]: http://moderndevice.com/product/rbbb-bundle/
  [2]: https://i.stack.imgur.com/z1911.jpg
  [3]: https://i.stack.imgur.com/fVuSE.jpg
  [4]: https://i.stack.imgur.com/XI3Iq.jpg
  [5]: https://i.stack.imgur.com/RNRVh.jpg

title: Arduino RBBB - Device not accepting address

Answers: 1

body:
I fixed it. Here is how I did it.

First, I tried connecting just the BUB II to via the USB. Same error, thus I ruled out the Arduino RBBB as the source. I then decided that perhaps it was the voltage jumpers (black things on the pins sticking out in the first picture). After removing them, it works under dmesg, yielding the below.

    [  214.044563] ftdi_sio 3-1:1.0: FTDI USB Serial Device converter detected
    [  214.044687] usb 3-1: Detected FT232RL
    [  214.044696] usb 3-1: Number of endpoints 2
    [  214.044704] usb 3-1: Endpoint 1 MaxPacketSize 64
    [  214.044712] usb 3-1: Endpoint 2 MaxPacketSize 64
    [  214.044718] usb 3-1: Setting MaxPacketSize 64
    [  214.045209] usb 3-1: FTDI USB Serial Device converter now attached to ttyUSB0

Thus I wanted to put them back on so I wouldn't lose them. I proceeded to try various combinations till it worked. Ultimately, I ended with 5V for VOUT and VL for LGLV. If that is a bad idea, someone please comment, but it works.

May this help someone else.


body:
I want to make a timer library. The cpp file I have written is:

    #include "avr/interrupt.h"
    #include "Arduino.h"

    #include "AllTimer.h"

    AllTimer::AllTimer()
    {}

    void AllTimer::dofun(void)
    {
        TIFR1 |= _BV(OCF1A);
        TCCR1B = 0X00;
        digitalWrite(13,!digitalRead(13));
    }

    void AllTimer::setTimer(void)
    {
        TCNT1 = 0x0BDC;
        TCCR1A = 0x00;
        TCCR1B = 0x00;
        TCCR1B |= (1<<CS12) && (1<<CS10);
        TIMSK1 |= (1<<TOIE1);
        sei();
    }

    ISR (TIMER1_OVF_vect)
    {
        dofun();
    }

And the header file:

    #ifndef AllTimer_h
    #define AllTimer_h

    class AllTimer{
    public:
        AllTimer();
        void setTimer(void);

    private:
        void dofun(void);
    };

    #endif

While compiling the file i am getting the following error:

    sketch_jan05a.cpp: In function ‘void __vector_13()’:
    sketch_jan05a.cpp:34:9: error: ‘dofun’ was not declared in this scope

title: Error: Function not declared in the scope

Answers: 3

body:
Because in the call:

     dofun();

you should put from which class you are calling that function.
In your case:

    AllTimer::dofun();

in that case your function must be declared as static method.

EDIT:
Thanks to the comment:

I'm not pretty sure if your code reflects what you want to do. Because you can create your timer after defining the class:

    Alltimer mytimer;

and call the method as a normal function (it must be declared as ***public***):

    ISR (TIMER1_OVF_vect)
    {
        mytimer.dofun();
    }

But it is hard to say since I m not sure what you want to do.

body:
`dofun()` is currently declared as a private member function, meaning you can't call it directly. It can only be called internally by an instance of the `AllTimer` class.

It looks like you probably want to declare it as a public static function instead. To do that, remove the `private` specifier from the class declaration, and put `static` before the function declaration. Your header should look something like this:

    class AllTimer
    {
    public:
        AllTimer();
        void setTimer(void);
        static void dofun(void);
    };

You will then need to change the ISR to include the class name in the call:

    ISR (TIMER1_OVF_vect)
    {
        AllTimer::dofun();
    }

body:
Answering here because I do not have enough rep to comment.
At each iteration, the value in the timer counter must be reloaded.
Either the ISR or dofun are responsible to reload TCNT1.


body:
what is the fastest serial read the Mega can do?
begin.Serial1(1024000) is accepted for compiling, but reading jibberish

any suggestions on a faster device?

title: what is fastest allowable serial baudrate?

Answers: 2

body: It depends mainly on CPU frequency, see *USART/Baud rate settings* in datasheet. For example at 16MHz it might go up to 2Mbps. But you need also consider error in baudrate which is important if communication with "3rd party" device.

body:
The Arduino Mega 2560 runs at 16 MHz. There are online calculators making this easy, as the calculation is not a straight and simple formula.

http://wormfood.net/avrbaudcalc.php

which shows using 16 MHz

| Baud Rate | UBRR(dec) | UBRR(hex) |  % of error      |
|----------:|----------:|----------:|------------------|
|      300  |     3332  |   0x0D04  |  0.0             |
|      600  |     1666  |   0x0682  |  0.0             |
|     1200  |      832  |   0x0340  |  0.0             |
|     2400  |      416  |   0x01A0  |  0.0             |
|     4800  |      207  |   0x00CF  |  0.2             |
|     9600  |      103  |   0x0067  |  0.2             |
|    14400  |       68  |   0x0044  |  0.6             |
|    19200  |       51  |   0x0033  |  0.2             |
|    28800  |       34  |   0x0022  |  0.8             |
|    38400  |       25  |   0x0019  |  0.2             |
|    57600  |       16  |   0x0010  |  2.1 - Barely OK |
|    76800  |       12  |   0x000C  |  0.2 - GOOD      |
|   115200  |        8  |   0x0008  |  3.7 - BAD       |
|   230400  |        3  |   0x0003  |  7.8 - BAD       |
|   250000  |        3  |   0x0003  |  0.0             |

Where it is noticeable that the Mega's Arduino boot loader uses

    mega.menu.cpu.atmega2560.upload.speed=115200

which is above the acceptable 1% error rate.

While it is possible to support different baud rates than stated above, it is not advisable, as the above values are the standard values. Values in between are very atypical and likely not trustworthy on the corresponding other side of the connection.

As I see your above example is 1024000, it is also worth noting that HardwareSerial.cpp implements a method to convert the requested baud rate to configuration of the USART, and I would not necessarily trust it for non-standard baud rates, especially on older version of the Arduino IDE. You may want to try the latest 1.5.8+ and verify the rate.


body:
I'm attempting to write data over a serial line to the arduino, however I don't want to use the arduino IDE but rather use the command line.

In order to do this I have the following commands:

    $stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
    $echo s123 > /dev/ttyACM0
The code on the receiving end checks whatever or not the input is s123 and if it is starts blinking. I have tested this using the arduino IDE and it worked, however this did not work.

The sketch looks like this:

        void loop(){
         if(Serial.available()==4){
           byte b1,b2,b3,b4;
          b1=Serial.read();
          b2=Serial.read();
          b3=Serial.read();
          b4=Serial.read();
            if(b1=='s'){
                   digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
                   delay(1000);               // wait for a second
                   digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
                   delay(1000);               // wait for a second
                   digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
                   Serial.println("the cow has landed");
              }
         }

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

the output of

    stty -F /dev/ttyACM0 -a

was :

    speed 9600 baud; rows 0; columns 0; line = 0;
    intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W;
    lnext = ^V; flush = ^O; min = 0; time = 0;
    -parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts
    ignbrk -brkint -ignpar -parmrk inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
    -opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
    -isig -icanon -iexten -echo -echoe -echok -echonl noflsh -xcase -tostop -echoprt -echoctl -echoke

Thank you

title: communicating with arduino over serial via terminal

Answers: 1

body:
This was fixed this morning after a reboot and upgrade command, still don't know which one of these fixed it but it seems to work now.

Ah figured it out we were using the 0 and 1 rx gates to communicate over serial rather then usb and as the used power supply turned out to be only 5V rather then 9-12V it didn't quite work as intended.


body:
I'm working on a kite-related project where I'm using Arduino + accelerometer to track data while a kite is in the air. I am struggling a little with the best approach - help on the following questions / issues would be a huge help:

-- how best to grab data only while the kite is in the air? just detect with numbers, use a switch? other ideas?
-- how best to collect the data and transfer to computer for visualization (likely with processing but looking at other options). i'm using this project in workshops with kids in low-income neighborhoods in brazil, so will have limited resources. a laptop will be available -but use of mobile also ideal.

Thank you!
Claudia

title: collecting & visualizing sensor data - best approach?

Answers: 1

body:
Several possibilities; Both at little cost, but since you have an accelerometer, I know your budget is not 0.

1) use a shield with an SD card on the arduino to log the information to a file on the SD card.  Open it later from a laptop or PC.  Hopefully it will have enough room to store data that you can ignore later for pre-flight, post-flight time.  If not, simply add some fixed delay to the start of your program (loop 5 times; wait 1 minute;)

2) some form of remote, like an XBee, or even a wireless WiFi Shield. The setup can be complicated but that would be ideal for real time visualization on a laptop at the flying site.

3) probably the easiest/least expensive - a cheap bluetooth transmitter.

![eBay Bluetooth $3 USD][1]

[eBay][2]

This method would allow a bluetooth mobile to collect and visualize the data. This device connects to the serial lines on an arduino, (pin 0&1) and standard Serial.Write() function can be used.  Any terminal program for your mobile will be able to receive the data. You could also get fancy and write your own if you want to visualize it. You may be able to find something already existing, like [this][3]

![enter image description here][4]

In cases 2 & 3 you will need a way to xmit the data. I use MQTT. A protocol just for this, but it is TCP only. I also use it with JSON (eg [Json for Arduino][5] to manage the data.  You will need to find the same. Look at MQTT-SN as a possibility, or you can just write your own serialization protocol based around JSON without too much difficulty.

  [1]: https://i.stack.imgur.com/16Gte.jpg
  [2]: http://www.ebay.com/itm/Wireless-Bluetooth-RF-Transceiver-Module-serial-RS232-TTL-HC-06-for-Arduino-/231441772518
  [3]: http://www.tigoe.com/pcomp/code/arduinowiring/140/
  [4]: https://i.stack.imgur.com/4UA1c.png
  [5]: https://github.com/interactive-matter/aJson


body:
I have been trying to find any Arduino or similar prototyping board that uses this MCU

![enter image description here][1]

http://www.pcmag.com/article2/0,2817,2453987,00.asp

But the smallest and more robust ones I have been able to find are Microduino and Espruino pico, none of which use this.

Are there any prototyping boards that use these?

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

title: Are there any KL03 "arduinos"?

Answers: 1

body:
This development board uses a chip from the KL03 family:
http://www.freescale.com/webapp/sps/site/prod_summary.jsp?code=FRDM-KL03Z

However, as you can see, it uses the arduino uno form factor (like all their other freedom boards), so it's probably not what you were expecting with respect of size.

If you are looking for a dev board that you can prototype with (easy access to pins and all that) I doubt you can get anything significantly smaller than a teensy (https://www.pjrc.com/teensy/), which also uses a more powerful ARM M4 core. There has been quite a few kickstarters with tiny arduino-compatible boards, but I am not quite sure how many you can actually buy at the moment.


body:
I'm attempting to hook up an arduino uno with a Sparkfun Oled. I downloaded the example program and made these changes:

    #define PIN_RESET 3  // Connect RST to pin 3
    #define PIN_DC    4  // Connect DC to pin 4
    #define PIN_CS    10 // Connect CS to pin 10
    #define DC_JUMPER 0

I connected everything according to Sparfun's walkthrough. I also wired accordingly. However, I cannot seem to get the Oled to do, well, much of anything. I have tried switching the MOSI and MISO to see if that makes a difference, but it doesn't seem to have any effect.

I'm using:
pin 13 - clock (in the picture I was trying pin 8 for the clock but I have tried both)

pin 12 - MISO

pin 11 - MOSI

pin 10 - CS

pin 4 - DC

pin 3 - RESET

Can anyone tell me what's going wrong? I've tried to figure it out for a good long while now and I can't make the display do anything productive.

Thanks

![enter image description here][1]

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

title: Wiring Issues with Sparkfun Oled

Answers: 1

body:
Have you connected the `GND` pin from the `UNO` to the breadboard?  I can't hardly tell.  But it looks like you are also using 5V to power it?

How are you powering the `UNO`?  Is it just 3.3V?  I'm powering mine with a 5V but have level converters connected.

Mine:

![UNO with OLED][1]

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


body:
I have a black Thermistor with the number 503 on it.

I know that I would need a 50k resistor as a voltage divider.

I don't get to convert the number I am getting. I get the number 340 when my house is at 64*F.
I bought a kit on Amazon and it came with it and there is no documentation.A test with multimeter has shown at 17*C I get 30k ohms.

This is how it is wired:

    [Ground] -- [50k-resistor] -- | -- [(503)thermistor] --[Vcc (5v)]
                                  |
                             Analog Pin 0

title: How to use 503 Thermistors for temperature?

Answers: 3

body:
Here is a [link to Jameco][1], one supplier of a 503 thermistor - it is a negative-coefficient thermistor. They have a link to a data-sheet for it. I can't say for sure that this is your device, but a simple experiment with your ohm-meter should confirm it.

  [1]: http://www.jameco.com/1/1/1127-ntc-503-r-negative-temperature-coefficient-ntc-thermistor.html

body:
First of, **503** means 50 x 10^3, ie **50K Ohm**: that is the maximum resistance of this thermistor (the higher resistance occurs for lower temperatures). However, having just that without any precise reference may prove difficult to find a relevant datasheet that could help you calculate the temperature from the measured voltage.

I think what could work well is just simple calibration by establishing a mapping between
the value returned by `analogRead()` and the temperature measured by a real, good precision, thermometer.

Establighing the mapping for 2 extreme temperatures would provide a **first approximation** on computing any temperature from the read value.

However, such an approximation would not be very accurate because thermistors are **not linear**, ie their resitance don't vary linearly with temperature.

What you can try to do then, is to increase the number of mapped *value<->temperature* with regular intervals of temperatures; then you can use linear approximation between two consecutive mapped values, which would provide better results.

The difficulty here is to "produce" the temperatures for which you want to find the mapped value: if you can spend one year for that, then just let the chqanging seasons operate that for you :-) otherwise use what you can find at home: fridge, oven, fan, heater...

body:
I found some code for a 10k thermistor and modified it for a 50k and cut out the code to display Celcius.  I found this on the Arduino playground posted by: Milan Malesevic and Zoran Stupic.

Origional code is found here: http://playground.arduino.cc/ComponentLib/Thermistor2

This is what I came up with and it returned the proper temp in F for a 503 Thermistor.

    #include <math.h>
    // enumerating 3 major temperature scales
    enum {
      T_KELVIN=0,
      T_CELSIUS,
      T_FAHRENHEIT
    };

    #define EPISCO_K164_10k 4300.0f,298.15f,50000.0f  // B,T0,R0

    float Temperature(int AnalogInputNumber,int OutputUnit,float B,float T0,float R0,float R_Balance)
    {
      float R,T;

    //  R=1024.0f*R_Balance/float(analogRead(AnalogInputNumber)))-R_Balance;
      R=R_Balance*(1024.0f/float(analogRead(AnalogInputNumber))-1);

      T=1.0f/(1.0f/T0+(1.0f/B)*log(R/R0));

      switch(OutputUnit) {
        case T_CELSIUS :
          T-=273.15f;
        break;
        case T_FAHRENHEIT :
          T=9.0f*(T-273.15f)/5.0f+32.0f;
        break;
        default:
        break;
      };

      return T;
    }

    //example of use #2
    // using numbers instead of episco k164 definition
    // this time reading from analog input 2
    // getting result in fahrenheit

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

    void loop() {

     Serial.println("********");
     Serial.println("Temp");
     Serial.println(Temperature(2,T_FAHRENHEIT,4300.0f,298.15f,50000.0f,10000.0f));
     Serial.println("********");
     Serial.println(" ");

     delay(500);
    }

Good luck!!!!


body:
I've been playing with [Groove Bluetooth Module][1] (HM-11) and for some reason my computer can see it, but none of my cell phones can.

I've tried two Huawei P7 (BL 4.0 + BLE) as well as some Samsung Galaxy & some older sony with Bluetooth 2.0. None of the cell phones can see the device. Any ideas?

  [1]: http://www.seeedstudio.com/wiki/index.php?title=Grove_BLE_v1&uselang=en

title: Bluetooth module discovered by computer and not smartphones

Answers: 0


body:
I wrote a simple program for controlling an LED using mobile. So, I bought the HC-05 bluetooth module configured it and then connected it to  the arduino.

This is the code that I wrote for it.

<!-- lang-all:cpp -->

    int ledPin1=13;
    int state;
    int flag=0;

    void setup()
    {
        pinMode(ledPin1, OUTPUT);
        digitalWrite(0,HIGH);

        second:
        Serial.begin(9600);
    }

    void loop()
    {
        if(Serial.available() >0)
        {
            state = Serial.read();
            flag=0;
        }
        if (state == '0')
        {
            digitalWrite(ledPin1, LOW);
            if(flag == 0){
                Serial.println("led off");
                flag=1;
            }
        }
        if (state == '1')
        {
            digitalWrite(ledPin1, HIGH);
            if(flag == 0){
                Serial.println("led on");
                flag=1;
            }
        }
    }

Everything is working cool with the serial monitor. But, I'm not able to control it using my mobile. I gave an input 1 in serial monitor and if showed "led on". the same thing appears on the commanding interface of the app used in the mobile. So, the bluetooth is transmitting information from the arduino to mobile but I'm not able to send commands from the mobile and control the led. I tried using various apps like  Blueterm, Ardudroid etc but, the situation remains the same.

What am I doing wrong? Is there something wrong with the code?

I'm using Arduino Uno.

title: Problem with hc-05 bluettoth module

Answers: 2

body:
Your android app might be sending extra characters like "end of line", which will cause the return value of `Serial.read()` to be other than `1` or `0` after the first byte. Nevertheless, it looks like it should still turn on or off the LED as soon as it reads the first byte, and do nothing when it reads the following bytes. I have used the "hyperterminal rs232" app successfully to send single characters, maybe give that I try to see if it helps and ensure it is configured at the correct baud rate.

I would recommend to send back to the serial stream the characters read, to ensure they have been received correctly, so I would change this:

    if(Serial.available() >0)
    {
        state = Serial.read();
        flag=0;
    }

to:

    if(Serial.available() >0)
    {
        state = Serial.read();
        Serial.print(state);
        flag=0;
    }

**Edit:**

Just realised this in `setup()`:

    digitalWrite(0,HIGH);

You are setting the receive pin of the UART peripheral to hight, so that is probably why you are not reading data from your phone.

body:
Why don't you try making another code.
If you want to use library, use `#include <SoftwareSerial.h>`

Do not use `digitalWrite(0, HIGH)` in `void setup(){...}`

Declare `ledPin = 13;`

Use only `pinMode` and `Serial.begin(9600)` in `void setup()`

In `loop()` do ask `if (Serial.available()){...}`


body:
I have no idea why this is happening, but after I open COM port to talk with my Arduino (I click "Open" in RealTerm), the state of some pins goes from high to low for about 2 seconds and then goes back to high. Here's my code:

    void setup()
    {
      pinMode(5, OUTPUT);
      digitalWrite(5, HIGH);
      Serial.begin(9600);
    }

    void loop()
    {
    }

In this case pin 5 will behave this way. I've checked it also for pin 6 and pin 8 and they behave in the same manner. I suppose more pins act like that. Why is this happening?

title: When I open a COM port some pins on Arduino Uno goes low for about 2 seconds

Answers: 2

body:
What you see is expected: that's because opening the USB connection to the UNO will automatically trigger a reset of the ATmega chip of the board, hence your sketch will be executed from scratch, ie `setup()` will be called again then your `loop()` repeatedly.

Hence what you observe in detail:

1. open USB connection from PC
2. open USB connection on Arduino UNO
3. UNO USB chip (an ATmega16u2) triggers a RESET of the MCU (an ATmega328P-PU)
4. On reset, the MCU sets all pins to INPUT, i.e. high impedence, **hence no voltage can be measured on any pin**
5. Then the bootloader starts, performs some intialization and starts your sketch
6. Your sketch executes first `setup()`, so your pin is put in OUTPUT mode and set to HIGH: **its voltage is thus measurable (5V)**
7. your sketch `loop()` gets executed "forever" i.e.until a new reset or power supply disconnection

body:
The arduino is reseting because of the serial port initializing. If you want to avoid it, you can put a 120 ohm resistor between 5v and reset.

[Source](http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection)


body:
Currently I am trying to get a Mindwave Mobile device to operate with an Arduino Uno. I'm following the guide [here][1].

  [1]: https://learn.sparkfun.com/tutorials/hackers-in-residence---hacking-mindwave-mobile

However the sample code given doesn't work very well. I have been trying to get a more consistent output but to no avail.

MindWave Code :

<!-- language: lang-cpp -->

    #include <SoftwareSerial.h>     // library for software serial
    SoftwareSerial mySerial(5, 6);  // RX, TX
    int BAUDRATE = 57600;

    // checksum variables
    byte payloadChecksum = 0;
    byte CalculatedChecksum;
    byte checksum = 0;              //data type byte stores an 8-bit unsigned number, from 0 to 255
    int payloadLength = 0;
    byte payloadData[64] = {0};
    byte poorQuality = 0;
    byte attention = 0;
    byte meditation = 0;

    // system variables
    long lastReceivedPacket = 0;
    boolean bigPacket = false;
    boolean brainwave = false;

    void setup() {
      Serial.begin(57600);       // Bluetooth
      delay(500);
      mySerial.begin(4800);      // software serialz
      delay(500);
      Serial.print("Communicating... ");
      mySerial.print("Communicating... ");
      mySerial.println();
    }

    byte ReadOneByte() {
      int ByteRead;
      // Wait until there is data
      while (!Serial.available());
      //Get the number of bytes (characters) available for reading from the serial port.
      //This is data that's already arrived and stored in the serial receive buffer (which holds 64 bytes)
      ByteRead = Serial.read();
      return ByteRead; // read incoming serial data
    }

    unsigned int delta_wave = 0;
    unsigned int theta_wave = 0;
    unsigned int low_alpha_wave = 0;
    unsigned int high_alpha_wave = 0;
    unsigned int low_beta_wave = 0;
    unsigned int high_beta_wave = 0;
    unsigned int low_gamma_wave = 0;
    unsigned int mid_gamma_wave = 0;

    void read_waves(int i) {
      delta_wave = read_3byte_int(i);
      i += 3;
      theta_wave = read_3byte_int(i);
      i += 3;
      low_alpha_wave = read_3byte_int(i);
      i += 3;
      high_alpha_wave = read_3byte_int(i);
      i += 3;
      low_beta_wave = read_3byte_int(i);
      i += 3;
      high_beta_wave = read_3byte_int(i);
      i += 3;
      low_gamma_wave = read_3byte_int(i);
      i += 3;
      mid_gamma_wave = read_3byte_int(i);
    }

    int read_3byte_int(int i) {
      return ((payloadData[i] << 16) + (payloadData[i + 1] << 8) + payloadData[i + 2]);
    }

    void loop() {
      // Look for sync bytes
      // Byte order: 0xAA, 0xAA, payloadLength, payloadData,
      // Checksum (sum all the bytes of payload, take lowest 8 bits, then bit inverse on lowest
      if (ReadOneByte() == 0xAA) {
        if (ReadOneByte() == 0xAA) {
          payloadLength = ReadOneByte();
          if (payloadLength > 169) //Payload length can not be greater than 169
            return;
          payloadChecksum = 0;
          for (int i = 0; i < payloadLength; i++) {     //loop until payload length is complete
            payloadData[i] = ReadOneByte();             //Read payload
            payloadChecksum += payloadData[i];
          }
          checksum = ReadOneByte();                     //Read checksum byte from stream
          payloadChecksum = 255 - payloadChecksum;      //Take one’s compliment of generated checksum
          if (checksum == payloadChecksum) {
            poorQuality = 200;
            attention = 0;
            meditation = 0;
          }
          brainwave = false;
          for (int i = 0; i < payloadLength; i++) { // Parse the payload
            switch (payloadData[i]) {
              case 02:
                i++;
                poorQuality = payloadData[i];
                bigPacket = true;
                break;
              case 04:
                i++;
                attention = payloadData[i];
                break;
              case 05:
                i++;
                meditation = payloadData[i];
                break;
              case 0x80:
                i = i + 3;
                break;
              case 0x83:                         // ASIC EEG POWER INT
                i++;
                brainwave = true;
                byte vlen = payloadData[i];
                //mySerial.print(vlen, DEC);
                //mySerial.println();
                read_waves(i + 1);
                i += vlen; // i = i + vlen
                break;
            }                                 // switch
          }                                   // for loop

    /*
          if (bigPacket) {
            if (poorQuality == 0) {
            }
            else {                            // do nothing
            }
          }
    */
          if (brainwave && attention > 0 && attention < 100) {
            mySerial.print(attention, DEC);
            mySerial.println();

            Serial.print(attention, DEC);
            Serial.println();
          }
        }
      }
    }

Often, the serial monitor stops display new values that stems from the Mindwave. Any suggestions on how I could modify the code to get it to run more smoothly will be greatly appreciated.

title: Enabling quicker and more accurate MindWave Mobile detection?

Answers: 2

body:
I have just spotted this question because I had a similar issue: the while condition reading Serial data is blocking.

I've rewritten the parsing part a little bit, which you can see [here][1].

This makes it smoother to run things in parallel, but it takes about the same time to accumulate a big packet of brainwave data.

  [1]: https://arduino.stackexchange.com/questions/9666/how-to-avoid-blocking-while-loop-reading-serial

body:
No use in reinventing the wheel!

> Brain is an Arduino Library for parsing data from Neurosky-based EEG
> headsets. Tested units include the Star Wars Force Trainer and Mattel
> MindFlex.
>
> It's designed to make it simple to send out an ASCII string of
> comma-separated values over serial, or to access processed brain wave
> information directly in your Arduino sketch. See the examples for code
> demonstrating each use case.

https://github.com/kitschpatrol/Brain

Install the library, and set it up like this:

    #include <Brain.h>

    // Set up the brain parser, pass it the hardware serial object you want to listen on.
    Brain brain(Serial);

    void setup() {
    // Start the hardware serial.
    Serial.begin(9600);
    }

    void loop() {
    // Expect packets about once per second.
    // The .readCSV() function returns a string (well, char*) listing the most recent brain data, in the following format:
    // "signal strength, attention, meditation, delta, theta, low alpha, high alpha, low beta, high beta, low gamma, high gamma"
        if (brain.update()) {
        Serial.println(brain.readErrors());
        Serial.println(brain.readCSV());
        }
    }

Can't guarantee that it will work, but if you have the TX pin of the bluetooth hooked up to the RX pin of the Arduino I'm pretty sure it will work.


body:
I'm brand new to arduino but I'm trying to figure out how to set up a WASD steering system for my robot I made.

I have the physical setup all ready but I don't know the code to use that would allow me to use my computers keyboard. I would like to still have my keyboard attached to my computer while I do this. *I.E. I don't want to manually plug the keyboard into arduino*.

I asked this on [Robotics stack exchange](https://robotics.stackexchange.com/questions/5302/code-control-your-arduino-with-keybaord) but they said to ask here.

A list of functions/blocks Iof code that is applicable would be the best answer, but I'll take anything that'll get my bot moving :)

**Edit** I'm using a wireless keyboard, but my arduino is connected via USB.

title: Control arduino with keybaord via computer

Answers: 1

body:
The problem with using the keyboard is the device would have to be tethered to your computer. If you mean for this "robot" to be an explorer, that limits its choices. If it's an arm or something that stays in place, you're fine using the typical serial libraries to monitor your keyboard for input like Chris suggests.

Unfortunately, I don't know of any way to simply plug in the USB keyboard and take in keys. Usually, serial communication is processed between two systems much like two people texting each other. When you see the light blinking on your phone, you know you have a text and how to open it to retrieve the message. In the case of the Arduino, it's checking for a flag bit called RX for the received message and flags a bit for transmitting a message (TX). Each system then pulls down its message and interprets it. In the case of your sketch, you'll be looking for this flag and schedule an action whenever it's checked. Read about Serial communications here and work through the examples to get a feel for it. Because you probably want a real-time response, it might be worth your while to check out interrupts, as well. These are sudden events that get flagged (such as receiving your text) and get handled immediately instead of waiting for the program to refresh and search for the values manually. As a final note, baud rates are the calculated time frames you and your recipient agree on. It would be difficult to receive a full message if you kept cutting off your friend, so it is with computers. This stuff can kind of be tricky at first, but keep at it. Nothing is more ridiculously satisfying than getting that response character from your device.

There's a neat tutorial for getting your Arduino to work through your iPhone here, but it requires an ethernet board, which means a router and wireless board.

Without knowing what you intend to do with it, it's hard to say how to help, but I hope this gets you into it.


body:
We have two labs - one in 1st floor and other at 2nd floor. We are connected by intercom - both the labs has one device each. The issue is that the person who sits near the intercom is busy through out day answering the intercom and reaching out to the person for whom the call is made for.

This is very tiresome and hence I wish to automate this. I have an Arduino Mega 2560 board. My plan is to make Arduino receive the call ask for the person whom the caller is reaching out and play the name loudly over speaker in all rooms of labs (to attended the phone). If the user does not turns up even after 3 repeated times of calling - disconnect the call. If the user answers the phone by picking up the receiver then turn the conversation speaker mode off until call has not ended.

I have Arduino Mega 2560 board which has 4 serial ports but I am not user what would be the circuit to make this functionality workable? What are the extra h/w required and concept of its implementation.

title: Self answering a Intercom and playing louldy for person to response

Answers: 1

body:
Let's try to break it down to several components:

* **Interfacing with POTS** (Plain Old Telephony System):
  There is [a nice article][1] by Joe Doll describing how to interface an Arduino and POTS. POTS involves high voltage during both idle and ringing time (48 V DC, superimposed 90 V AC) and the circuit itself is [mostly analog][2]. You can find the required parts and their values in his article, which goes down into the nasty details in a spectacular fashion. Here is the analog circuit, involving the Arduino, from his post:

![Arduino interfacing POTS from Joe Doll's website][3]

Consider that there are other projects performing similar task in a different manner, like [this one][4], and [this one][5] which specifically explains how to record sound from an old rotary phone.

* **Play/Record sound from Arduino Mega 2650:**
There are many projects that describe how to [Play][6] or [Record][7] sound using Arduino. Most involve a SD card to store the wav files. There is also the option of an MP3 shield, that comes with a pre-built SD card slot, such as [this one][8]. They are fully documented and are easy to interface with.

* **Code that encapsulates the Logic**:
Here you could decide how many times the Arduino should play the recorded name, and what happens if the user won't answer. The disconnection will be done utilizing the POTS interface you created in bullet #1. In addition, you should handle the logic of what happens when the user does answer. It is not clear what you mean by 'receiver', but if you plan to have a remote extension or similar, some extra work will be required.

As a side note, it might be easier to create/re-use a walkie-talkie kind of wireless communicator, accompanied by an Arduino, to signal or broadcast the names of the people called. This might not include reuse or interfacing with the current intercom device, but by thus I believe it will make development easier and faster.

  [1]: http://ww.joes.com/intercom/index.html
  [2]: http://www.joes.com/intercom/circuit.html
  [3]: https://i.stack.imgur.com/iEReN.jpg
  [4]: http://brohogan.blogspot.co.il/2009/12/telephone-interface.html
  [5]: http://blog.andrewstella.com/2013/12/new-project-arduino-rotary-phone.html
  [6]: http://www.instructables.com/id/Arduino-playing-wav-files/
  [7]: http://www.instructables.com/id/Arduino-Mega-Audio-File-logging/
  [8]: https://www.sparkfun.com/products/10628


body:
I have a popular bluetooth module JY-MCU version 1.06 (picture below). Before i insert it to my arduino project I want to configure the name, bound speed and the pass code using usb-to-serial link. But I am facing a problem where the device does not respond to commands. Please let me explain.

I send the module to programming mode by applying +5V on 'key'

Then I send commands using CoolTerm program:

    AT+NAMEmyArduinoProject
    > OKyour set name

Ok. setting the name works as expected. But that is the only thing that worked for me. Other commands give no response:

    AT

    AT+BAUD2

    AT+VERSION

    AT+VERSION?

Maybe you had this happen to you? I am I sending wrong commands or doing something wrong? Please help me to figure out how to control this module.

![enter image description here][1]

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

title: Programming bluetooth module JY-MCU v1.06

Answers: 2

body: OK, I figured it out. It looks like CoolTerm was sending wrong line endings. Thus the only command that worked was name change as it interpreted the extra symbols as part of the name specification. Now I am using in built Arduino serial communication and it works like a charm!

body:
The protocol is peculiar.

You are to send the command unterminated within one second.

For example the AT command comprises the two characters AT and nothing more, no line ending at all. And the command must be completed within one second.

So,
AT[cr][lf] will just be ignored.


body: Is it possible to connect two Ethernet shields to arduino? And if yes, how can I distinguish them in the code?

title: Arduino two Ethernet shields

Answers: 1

body:
The ENC28J60 Shields have a Chip-Select-Pin (CS) so you could select between the two shields with this.

[![https://upload.wikimedia.org/wikipedia/commons/f/fc/SPI_three_slaves.svg][1]][1]

I'm using the EN28j60 with the Ethercard library and I'm not sure if this could handle two Ethernet shields because you have to **set the CS pin at init on the first call in the function**, and can't change it at runtime.

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


body:
I accidentally misconnected a USB BUB II to a Arduino RBBB (atmega 328), and it no longer uploads code. Here are the symptoms, I think the BUB II is fried. I am using Ubuntu 14.10.

 - Code won't upload with error `ser_recv(): programmer is not responding`
 - The RBBB board will reset is I hit the button. Evidenced by the LED flashing in port 13
 - Prior code runs as expected
 - dmesg behaves normally upon USB connection
 - When I short the Rx and Tx terminals of the BUB II, I can send instant reply messages via the Serial Monitor

Does this sound like the USB BUB II is broken? Or is is possible that some component on the RBBB board is fried?

title: USB BUB II - Misconnection and no longer uploads

Answers: 1

body:
Well, I asked too soon. I tend to do this.

I had to switch the board configuration to Arduino Uno and it worked


body: I'm new to electronics. Professionally I'm a software developer. I want to know whether it is possible to program Atmel AVR 8-bit and 32-bit Microcontrollers using Arduino IDE. If yes could any one guide me on the process or direct me to any site where I can learn about it.

title: Programming Arduino

Answers: 3

body:
Yes, it is possible. In fact, this is how the whole 'Arduino' concept works - programming 8/32 bit AVR microcontrollers with the Arduino IDE.

> program Atmel AVR 8-bit and 32-bit Microcontrollers using Aurdino IDE

This has two parts actually:

**1. Generate compiled HEX targeting AVR**

Using the Arduino IDE you could utilize the Arduino libraries (aka working with assist utility functions like `digitalWrite` for example), which are built on top of the AVR tool-chain. The official Arduino IDE comes with pre-built support for several 8-bit/32-bit Atmel AVR micro-controllers, the full list of supported boards can be found on the Arduino official website or in [this Wikipedia page][1].
**You did not specify a specific MCU**, therefor you should check if the MCU you would like to work with is in that list.

**2. Uploading an Arduino sketch to a compatible AVR**

Arduino IDE uses [avrdude][2] under the hood. avrdude is

> an utility to download/upload/manipulate the ROM and EEPROM contents
> of AVR microcontrollers using the in-system programming technique

(From their website).

The best place to start is the official Arduino.cc website, in the ['Getting Started' section][3]. If you haven't picked any specific Atmel AVR chip yet, consider that each has slightly different features, size, I/O pins etc. so make sure to research a bit before purchasing one (reference the table in the Wikipedia link above to compare between the different kinds).

  [1]: http://en.wikipedia.org/wiki/List_of_Arduino_boards_and_compatible_systems
  [2]: http://www.nongnu.org/avrdude/
  [3]: http://arduino.cc/en/Guide/HomePage

body:
[http://arduino.cc/][1] is good place to start. It includes articles about how to get started, library references, and user forums. The Arduino IDE will certainly get you started, but as an experienced developer you'll most likely hit its limitations pretty quickly.

Later, or quite possibly sooner(!) you can use same toolset (compiler, loader, libraries) in several less limiting environments: Eclipse IDE, edit/make at the command line, and Atmel's AVR Studio. C and C++ are mainstream; I've seen references to the existence of (but never tried) AVR Forth and AVR python.

Though you'll see occasional references to an 'Arduino language' it's really nothing more than C++ with some attempt to be smart about detecting references to library packages and auto-inserting the relevant `#include`s.
You probably won't want to take advantage of such shortcuts, and keep to good programming practices, if you think you'll ever want to move up from the Arduino IDE.

I personally use Eclipse (supplementing with a few command line tools) and I'd recommend it once you've tried the Arduino IDE.

  [1]: http://arduino.cc/

body:
Just to complement the other responses. You can program some AVR chips using the Arduino IDE, but for it to work out-of-the-box just by using a USB cable it needs to be an Arduino or "Arduino compatible" board, mostly because these come with the [Arduino Bootloader](http://arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader).

The bootloader is a small piece of software that runs at power-up and is responsible to load your program into the chip (as well as other configuration stuff, for more info read the previous link). If the AVR chip does not have the bootloader already flashed, then you will have to use a programmer (connected to its ISP pins) to burn it first.

So, it's not like you can just buy random AVR chips or development boards online and start using them. But taking in consideration the wide selection of official boards and "Arduino compatible" ones, you should be able to find something to fit your needs.


body:
I have the following setup and sketch.

The problem is that when I click the button it works sometimes, but other times it executes On Off straight after On as if it's executing twice.

This is after pressing the button only 7 times:

    Off
    On
    Off
    On
    Off
    On
    Off
    On
    Off

I thought that was the whole point of a state machine? That it continues to execute the next state (not multiple times at random).

Very very confused with this one.

![enter image description here][1]

    //http://www.arduino.cc/playground/uploads/Code/FSM.zip
    #include <FiniteStateMachine.h>
    //http://www.arduino.cc/playground/uploads/Code/Button.zip
    #include <Button.h>
    //http://www.arduino.cc/playground/uploads/Code/LED.zip
    #include <LED.h>

    const byte NUMBER_OF_STATES = 2; //how many states are we cycling through?

    //initialize states
    State On = State(ledOn);
    State Off = State(ledOff);

    FSM ledStateMachine = FSM(On);     //initialize state machine, start in state: On

    Button button = Button(2, INPUT_PULLUP); //initialize the button (wire between pin 12 and ground)
    LED led = LED(13);                 //initialize the LED
    byte buttonPresses = 0;            //counter variable, hols number of button presses

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

    //poor example, but then again; it's just an example
    void loop(){
      if (button.uniquePress()){
        //increment buttonPresses and constrain it to [ 0, 1 ]
        buttonPresses = ++buttonPresses % NUMBER_OF_STATES;
        switch (buttonPresses){
          case 0: ledStateMachine.transitionTo(On); Serial.println("On"); break;
          case 1: ledStateMachine.transitionTo(Off); Serial.println("Off"); break;
        }
      }
      ledStateMachine.update();
    }

    //utility functions
    void ledOn(){ led.on(); }
    void ledOff(){ led.off(); }
    //end utility functions

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

title: SMlib State Machine Library not working as expected

Answers: 2

body:
Maybe you need some sort of **debouncing**? There's a [tutorial][1] on the Arduino site that I think will sort your problem out.

  [1]: http://arduino.cc/en/Tutorial/Debounce

body:
It doesn't look like the state machine is a problem here. More likely it's a problem of the button bouncing, as you don't have any code or circuitry to guard against it.

A button is typically a very simple component which doesn't necessarily make/break connections cleanly. Sometimes it will have a brief intermittent connection, making it look like it's been pressed/released multiple times. This is referred to as bouncing.

There's lots of material online about debouncing, whether in hardware or software. The top answer here may help:

 * https://arduino.stackexchange.com/questions/408/why-does-my-sketch-report-too-many-button-presses/411#411


body:
Okay 2 questions. If I am to replace the Arduino with an ATmega328 programmed with a standard blink on pin 13, is this configuration correct, do I still need oscillators and whatnot?

![Simple breadboard circuit with LED on pin 13 of ATmega328][1]

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

Second question is, what is the max voltage I can power the ATmega328 with without frying it? I have seen conflicting answers of this on the net. Some have said 5V while some say 6V can someone clarify?

title: Can I use an ATmega328 alone without anything and what is the max voltage I can power the atmega328 with

Answers: 3

body:
The [datasheet][1] describes the electrical and clock requirements of the chip, and AVR042 describes the external hardware configuration required. Decoupling, analog voltages, external crystal or oscillator if required.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf

body:
If you take a look at the [Standalone Arduino][1] on the Arduino website, then this is what you require:

[![Standalone Arduino][2]][2]

Note that there is one slight error in the guide, which I have highlighted here, [Arduino Standalone - photo shows incorrect pin wired to MOSI][3].

There is a video on how to achieve, more or less, the same thing, [1-Day Project: Build Your Own Arduino Uno for $5][4].

  [1]: https://www.arduino.cc/en/main/standalone
  [2]: https://i.stack.imgur.com/EYXT3.jpg
  [3]: https://arduino.stackexchange.com/questions/10392/arduino-standalone-photo-shows-incorrect-pin-wired-to-mosi
  [4]: https://www.youtube.com/watch?v=sNIMCdVOHOM

body:
I have a page describing [How to make an Arduino-compatible minimal board](http://www.gammon.com.au/breadboard). The minimal setup would be:

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

That excludes the circuitry for uploading your code.

By the way, in the image in the question you have an LED with no resistor. That will damage both the LED and the Atmega328. You need a **current-limiting resistor**.

---

> do I still need oscillators

Not if you program the fuse to use the internal oscillator.

> Some have said 5v while some say 6v can someone clarify?

The datasheet says 1.8 to 5.5 V operating range with an **absolute maximum rating** of 6 V.

This is what the datasheet says about absolute maximum ratings:

> This is a stress rating only and functional operation of the device at these
or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.

Page 2 of the datasheet says:

>  * Operating Voltage:
>  * 1.8 - 5.5V

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


body:
The following link to the library defines arduino pin 5 for input pin for signal.

 https://www.pjrc.com/teensy/td_libs_FreqCount.html

But the problem is I'm using an 16x2 LCD display with the arduino pin 5. The display needs pin 5 to work. So the question can solved in two ways,to both of which I don't know the answer.

1. Change LCD pin number to other pin. (Tried it was a failure. I've probably done it wrong)

2. Change the input pin for the freqcount library.

Any idea how to get past this bottleneck?

title: How to change input pin of FreqCounter Arduino Uno/Dumilanove library?

Answers: 1

body:
The library makes use of the hardware peripheral Timer 1 which has its input on pin 5 of the Uno.

It can't be changed.  You have no choice in that.

You will have to move the LCD to another pin instead.


body:
So I have to get this function done but I'm not so bright and got confused.
(excuse me! I'm total noob)

The function is basically inputing text using five buttons, directional buttons and an ok button. The up and down buttons will be used to cycle through letters (a-z), and the left and right buttons will be used to control which array to cycle letters.

The control will be:

 - up button (up): ASCII-1 (z, y, x...)
 - down button (dw): ASCII+1 (a, b, c...)
 - right button (ri): array[i] ~> i+1 (go to next character/array)
 - left button (le): array[i] ~> i-1 (go to previous character/array)
 - ok button (ok): confirm text and changes the limit to stop function looping

I can't get it work with this code I write.
<!-- language-all: lang-cpp -->

    void intext()
    {
      int lim=16;
      lcd.setCursor(0,1);
      lcd.print(input);
      for(i=0; i<lim ; )
      {
        if(digitalRead(dw)==HIGH)
        {
          if(input[i]<'a')
            input[i]='z';
          if(input[i]>'z')
            input[i]='a';
          input[i]=input[i]+1;
          delay(1000);
        }
        if(digitalRead(up)==HIGH)
        {
          if(input[i]<'a')
            input[i]='z';
          if(input[i]>'z')
            input[i]='a';
          input[i]=input[i]-1;
          delay(1000);
        }
        if(digitalRead(ri)==HIGH)
        {
          delay(1000);
          i=i+1;
        }
        if(digitalRead(le)==HIGH)
        {
          delay(1000);
          i=i+1;
        }
        if(digitalRead(ok)==HIGH)
        {
          lim=i+1;
          delay(1000);
        }
      }
    }

    void loop()
    {
      lcd.begin(16,2);
      lcd.setCursor(0,0);
      lcd.print("Type your text:");
      intext();
      lcd.setCursor(0,0);
      lcd.print("Success!!");
      lcd.setCursor(0,1);
      lcd.print(input);
    }

The result I wanted it to be is like this:
first you got the "type your text:" on the first row and blank in the second row.
our cursor is in the first column of the second row, so we can cycle through the alphabet letters. if you press right you can edit the next column of second row. you can get to the previous column in second row by pressing left. you can input up to 15 characters.
after done typing pressing ok will stop the typing and you will see "Success!!" in the first row and typed text in the second row.

Please help. I'm stumped.
Thank you.

title: Simple Text input using 5 buttons

Answers: 1

body:
Several issues in the code you posted:

* Every change to the text you do inside the `for` loop, will not be reflected to the LCD until the for loop will end (when `i<limit` will no longer be a true statement). You might want to add an additional code, inside the `for` loop and outside any of its conditional statements, that will repeatedly set the cursor and print `input` to the LCD. Something similar to the code you have prior to the `for` loop:

        void intext()
        {
          ... // rest of the code until the for loop

          for (int i; i<limit; )
          {
            ... // all the conditions for up/down/left/right/ok

            lcd.setCursor(0,1);
            lcd.print(input);
          }
        }

* Another problem is that when the user clicks *left*, the counter should be decremented, not incremented, and you should check for left boundary:

        if(digitalRead(le)==HIGH && i>0) // left boundary check added
        {
           delay(1000);
           i=i-1; // and not i=i+1;

        }

* After clicking *Ok*, and since the `for` loop does not increment `i`, the condition in the `for` loop (`i<limit`) will stay true, and the loop will not end until the user will click *Right* once more. To mitigate this, change the following

        if(digitalRead(ok)==HIGH)
        {
          lim=i; // and not: lim=i+1;
          delay(1000);
        }

Otherwise, the user will have to click *Right* for completion, to increment `i` once more.

* **jfpoilpret** comment about pull up/down is very important. Make sure you use pull up/pull down resistors in order to prevent [input debounce][2] (more details inside this link).

  [1]: http://en.wikipedia.org/wiki/Off-by-one_error
  [2]: http://arduino.cc/en/Tutorial/Debounce


body: A photoresistor is already a resistor and will limit the voltage in the circuit. Why can't this be connected to a pin and measured? Why is a second resistor needed to connect the photoresistor to ground?

title: Why do you need a second resistor when using a photoresistor/LDR?

Answers: 6

body:
This isn't strictly an Arduino question, but I appreciate that things like photo-resistors are common early projects for Arduino users.

Resistors (and other components) don't really limit the voltage in the circuit as such. Rather, each component in a series circuit gets a proportion of the total voltage. That proportion is determined by its resistance.

If you only have one component, then the entire voltage is dropped across it no matter what resistance it has. Changing the resistance in that situation would only affect the amount of current flowing through it.

You need the second resistor as a fixed reference point. You know how much voltage it will get if both resistances are equal, and that the relationship between voltage and resistance is (hypothetically) linear. You can therefore use that to figure out what resistance the other component has, e.g. the photo-resistor.

As a side note, the second resistor can also play an important role for safety. Without it, you could potentially end up with a short-circuit if the other component's resistance goes too low.

body:
The simple answer is that **voltage** is very easy for the Arduino to measure, while **resistance** is not, and most sensors such as Photoresistor (LDR), flex sensor, thermistors and more - are actually a variable resistors.

The main reason it's hard to measure resistance changes is that the Arduino (and most IC) contain a tiny system called **Analog to Digital Converter (ADC)**. This system translates changes in **analog voltage** to a series of 1's and 0's that can be in turn converted to an Integer for example.

The ADC is designed to read *voltage* changes, and if we want to use the Arduino's **analogRead** (which utilizes the ADC) to get the Photoresistor readings for example, we will need a way to convert the changes in *resistance* to changes in *voltage* - and a voltage divider is the easiest way to do it.

It is true that the sensor is already a resistor, and as such it should change the voltage across it. But you would have trouble measuring the voltage changes, since there is no reference point except for Vcc (5V) and Ground:

![Circuit that contains only a photoresistor][1]

In contrary, when using a voltage divider, you have a well defined reference point to measure the voltage changes:

![Circuit with photoresistor and voltage divider][2]

  [1]: https://i.stack.imgur.com/0sGbf.png
  [2]: https://i.stack.imgur.com/AdbgC.png

body:
also another big reason for it is if you have just in series, a power source, an LDR and say a bulb, then the bulb may come on as soon as the LDR resistance gets low enough, then it will get brighter as the resistance keeps decreasing.
If configured with more resistors in a potential divider with a transistor and the bulb at the collector side, then you can vary the resistors to define the exact amount of light that will allow approx 1.6V (?)(whatever voltage turns the base into a conductor anyway), and therefore the light at which the bulb will suddenly turn on with a constant power supply direct from the power source through a fixed resistor if needed.

So in series an LDR will vary the current with light around the circuit, in a divider and transistor it functions as a light dependant switch

body:
Accurate measurement of resistance requires a precise current source (http://www.digikey.com/product-search/en/integrated-circuits-ics/pmic-current-regulation-management/2556448?k=current source).

Ohm's law, V=IR or  R=V/I states that for linear components, the value of resistance in the circuit can be estimated by the ratio of the applied voltage divided by the current.  With a simple voltage divider, as the resistance of the sensor changes so does the current in the circuit.  So measuring the voltage at the junction does not necessarily provide an accurate indication of the current in the circuit.  Both the imposed voltage and current should be controlled to obtain accurate measurements.

body:
Unlike other electric components, a photoresistor(or light-dependent resistor,LDR,or photocell) is a variable resistor. This means its resistance can depend according to light intensity.

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

I will go first with half of the circuit diagram to understand clearly.

The resistance of a photoresistor decreases with increasing light intensity.
Strong Light —> LDR resistance(decreases to 0ohms) So the 10k(ohm) resistor sees closer to 5V.

The resistance of a photoresistor increases with decreasing light intensity.
Dim Light —>LDR resistance(increases to infinity).

So, the 10k(ohm) resistor only gets a little voltage.

Here is the full circuit diagram that you want to ask why second resistor is needed.

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

  [1]: https://i.stack.imgur.com/z3AcL.png
  [2]: https://i.stack.imgur.com/lYIyo.png

The key point is Arduino board also has Vcc(5V) and ground. So, there is no current if the potential difference is zero. Therefore, firstly, Vcc(5V) will flow through the photoresistor and go to the 10k(ohm) resistor.

Then, since there is a parallel circuit, arduino will get the same voltage as the 10k(ohm) resistor. So this LDR resistor does the function of a pull-up resistor which draws the current to VCC.

body:
I THINK NONE OF THE ABOVE ANSWERS ARE CLEARLY DEFINING THE SOLUTION. I WILL ANSWER WITH RESPECT TO THE WORKINGS OF AN LDR CIRCUIT  WITH A LIGHT BULB THAT SWITCHES ON IN THE DARK AND OFF IN LIGHT.

LETS ASSUME THAT WE HAVE AN LDR ONLY CONNECTED IN SERIES TO A LIGHT BULB. THE LDR IS ALREADY ACTING AS A VARIABLE RESISTOR AND HENCE WILL ALLOW CURRENT TO FLOW IN THE PRESENCE OF LIGHT, (LIGHT INTENSITY BEING DEPENDANT ON THE CURRENT RESISTANCE) AND WILL LIMIT THE CURRENT WHEN IT IS DARK. THIS MEANS THAT THE BULB LIGHTS UP IN LIGHT AND IS OFF WHEN IT IS DARK. THERE IS NO PRACTICAL USE FOR THIS. I WANT THE BULB TO LIGHT IN THE DARK AND SWITCH OFF IN THE PRESENCE OF LIGHT.

SO WHAT I DO IS ADD A RESISTOR IN SERIES TO THE LDR. THIS RESISTOR HAS A FIXED RESISTANCE MUCH LOWER THAN THE LDR AT ITS HIGHEST RESISTANCE BUT MUCH HIGHER THAN THE LDR AT ITS LOWEST RESISTANCE. THE BULB ELECTRIC PATH IS CONNECTED BETWEEN THE LDR AND THE RESISTOR. PLEASE NOTE THAT THE RESISTOR IS PLACED ABOVE THE LDR.

NOW LOOK AT IT IN TERMS OF CURRENT FLOW.

WHEN THERE IS LIGHT, THE LDR RESISTANCE IS LESSER THAN THE RESISTOR. HENCE THE CURRENT FLOWS FROM THE BATTERY TO THE RESISTOR AND A SIGNIFICANT PORTION OF THAT CURRENT CONTINUES TO FLOW IN SERIES THROUGH THE LDR AND BACK TOWARDS THE BATTERY. THE REMAINDER OF CURRENT IS CARRIED OVER TO THE BULB ELECTRIC PATH WHICH IS NOT SUFFICIENT TO LIGHT THE BULB. HENCE THE BULB STAYS OFF IN THE LIGHT.

WHEN ITS DARK, THE LDR RESISTANCE IS HIGHER THAN THE RESISTOR. HENCE THE CURRENT FLOWS FROM THE BATTERY TO THE RESISTOR AND INSTEAD OF CONTINUING TO THE LDR WHICH IS CONNECTED IN SERIES, IT TAKES THE PATH OF LEAST RESISTANCE TOWARDS THE BULB. THE LDR RESISTANCE HAS EFFECTIVELY BLOCKED THE CURRENT FROM FLOWING THROUGH IT AND DIRECTED IT TOWARD THE BULB. HENCE THE BULB LIGHTS UP IN THE DARK.

IN TERMS OF PRACTICAL USAGE THIS IS MOST IMPORTANT CONCEPT. ALL OTHER REASONS FOR USING A SECOND RESISTOR WITH AN LDR ARE SECONDARY.


body:
I am working on a project for grade 10 computer science.  I am supposed to make a piano that has 7 keys using a capacitive sensor, and the piano is supposed to teach you songs like Twinkle Twinkle Little Star by illuminating the LED corresponding with that key and then playing that tone on the speaker.  There is also a "random scales" part where you are timed and have to press the keys as fast as you can as they light up.  Unfortunately, I have come into a few problems.

1. I ran out of outputs and have to use a shift register. I have no idea on how to control each of the outputs.
2. When the game starts I want there to be 2 options a song and a random scales using `randomSeed` however I have NOT found a way for them to pick which option. I think I can do user input by typing or by them just pressing a key but I am not sure.
3. I am pretty new on Arduino so anything helps.

Finally I am using the Arduino Uno and that is why I am short pins because I have 1 gnd 1 speaker and the rest key inputs.

title: 7 Key Educational Piano with Capacitive Sensor

Answers: 0


body: Despite many articles on the topic of vehicle platforms, none of them seem to recommend the best one to start with. Later on I am sure I will seek an exact kind of chassis for autonomous vehicle construction, but now I am looking to learn the basics of this area of the Arduino world. If you could give me a simple recommendation for the general category of vehicle platform to use it would be much appreciated. I will be using an ultrasonic distance sensor coupled with a servo motor to detect obstacles, so it is a very simple project. Thank you so much.

title: What is the best vehicle platform to begin with (e.g. tracked, four-wheel drive)

Answers: 1

body:
SparkFun's Magician Chassis is a very simple, very flexible chassis for starting out. Also comes as part of the RedBot Kit.

![enter image description here][1]

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


body:
I'm starting a decently sized project around arduino/ATMELavr, and I came to wonder if there are any commonly accepted C/C++ coding standards or style guidelines specifically aimed at embedded C++/arduino.

I've worked mostly with python recently, and came to love the PEP8 guidelines, and the associated pep tool (which checks syntax consistency with the style guide).
Similarly, I've used jslint and similar tools for javascript, as I find they help keeping your code base homogeneous, and avoid wasting time and commits on silly typos, and arguing over where the braces should go.

Any similar tools for C++ or more specifically arduino C++?

title: coding standards for bigger projects

Answers: 1

body:
In my experience (15 years in industry, 30 total), **this does not matter**. What matters is having good developers who understand code written in ANY valid style. I currently work at a large bank, and there's 2 different bracket styles being used in our code, and nobody cares. Good developers don't care about this. We care a lot more about the code being valid, error-free, and efficient. If you do that, I don't care where your brackets are.

Yes, there are style guides for C++ but you don't need to use them. This is a good one though...

http://google-styleguide.googlecode.com/svn/trunk/cppguide.html

I am not aware of any style tools that integrate into Arduino IDE. There are some style tools that integrate into Eclipse though - and if this is important to you and your team, I strongly suggest using Eclipse for development. The Arduino IDE isn't really for large projects.

http://astyleclipse.sourceforge.net/ - but Eclipse doesn't really need this, it has a pretty good built-in formatter.


body:
I have five accelrometer sensors (MMA 7361) connected to the analog channels of Arduino Duemilanove. I am using the following code to read the data. (I am reading from only one axis from each sensor.)

    #include <avr/io.h>
    #include <avr/wdt.h>

    int sensorValue = 0; // value read from the pot

    void setup()
    {
     Serial.begin(9600); // initialize serial communications at 9600 bps:
    }

    void loop()
    {
     // read the analog values:

     int i=1;

     Serial.print("ACS#");

     for(i=0;i<5;i++)
     {

      sensorValue = analogRead(i);
      Serial.print(sensorValue);
      Serial.print("#");

      delay(10);
     }

     Serial.println("");

    }

I am using a delay of 10 after reading each sensor. What should the value of the delay I should be using after reading one sensor to get the correct values from the sensors?

title: What should be the delay to be given for reading accelerometer

Answers: 1

body:
A delay is not needed.

What can be more beneficial, though, is making a dummy reading between each real reading.  This gives the ADC more of a chance to settle on the right reading without the Sample and Hold capacitor being influenced by the previous reading.

The simplest way is just to duplicate your `analogRead` line so it's done twice.


body: I just recently bought an Arduimu v3. Rather annoyingly they did not supply an FTDI cable. I'm going for an FTDI cable where the I/O pins are configured to operate at 5v. I assume this is the right but I don't want to fry this board. Is this cable OK?

title: 5V FTDI cable for Arduimu V3

Answers: 2

body: Yes, as long as the board is 5V

body: A 5V cable would be fine, or for about the same price, I would recommend an [Adafruit FTDI Friend](http://www.adafruit.com/product/284) which is configurable between 5V and 3.3V.


body:
For some purpose we need to communicate with Arduino using more that one SIM card, but still like to use an only GSM shield.

So, the idea is to use several SIM holders, to commutate each of six SIM wires to the sim we currently use. But it is still the question

1) How we should handle the gsm module itself? Is it okay for it if the SIM wire will be commutated to another SIM when it is in the middle of something? May be we should power off the module before, but it unclear how to do it programmatically when it is installed on the top of Arduina Mega 2560

2) should we commutate all six wires, or may be there are few signal ones and another shouldn't be never commutated?

3) what is the best way to do this commutation? Relays/transistor switches and so on?

title: Several SIM with Arduino GSM/GPRS shield

Answers: 1

body:
You should reset the [shield](http://arduino.cc/en/Main/ArduinoGSMShield), and keep reset, while switch sims. The reset is on pin 7.

If you look at [the schematic](http://arduino.cc/en/uploads/Main/arduino-gsm-shield-schematic.pdf), you can see there are only 3 lines, plus a GND and VDD. The GND and VDD you can probably share between the different sims. The SIM_RST, SIM_SCK and SIM_DATA need to be switched.

I think you should use a [MUX](http://en.wikipedia.org/wiki/Multiplexer) for that, but that is not my area of expertise. Note that at least the DATA line is bi-directional.


body:
I'm very new to arduino related stuff so this question might be really easy to answer.
I don't understand how multiple PWM outputs are supposed to work. Look at the pic.
![enter image description here][1]

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

In the first(1) case we are using short signal width which would be close to motor staying still. In this case, as can be seen, short pulses follow each other, so does the code.

    motor1.writeMicroseconds(shortWidth);
    motor2.writeMicroseconds(shortWidth);
    motor3.writeMicroseconds(shortWidth);
    motor4.writeMicroseconds(shortWidth);

when motor4 ended it's output, motor1 starts it's pulse again causing non-problem consequent pulses.

In the second(2) case pulse is wider which corresponds to setting motor speed close to maximum. After motor1 finishes generating width, it's time for motor2 to generate one. But when it does, motor1's period comes to end and it has to start generate width again, but arduino is busy generating pulse of motor2.

How does PWMs work in this case?

title: Help to understand multiple PWM working together

Answers: 0


body:
So I will admit that I am a noob to Arduino. I have some experience programming microcontrollers, and that was back in the day (about 4 years ago - such as the Freescale 68HC12) so up until this point I thought I was experienced enough to get this Arduino Mega2560 rocking with AVR C using Atmel Studio and avrdude by lunch...

Wrong.

I believe I'm getting held up at what's possible...

**What I want to accomplish:** Write and compile a program in AVR C within Atmel studio. Use the hex file that was built and download that to the Mega. (Keep in mind I was planning on using USB and Arduino as my programmer between PC and ATMega2560 as per this gentleman's example... https://balau82.wordpress.com/2011/03/29/programming-arduino-uno-in-pure-c/ -- however, I was not using his code and he was compiling using avr-gcc...)

**Question:** Is this possible?

Using avrdude when attempting to write the file I get this message... (and my blinking LED goes dark for a few seconds before returning to normal operation)

![avrdude error][1]

When I searched the internet for this issue it was never related to avrdude, but rather a communications issue. I've verified my bootloader is still ok (uploaded other sketches with no issues).

It's certain that I am missing something minor, but this is my first day using Arduino so go easy on me!

Thanks

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

title: Cannot program Mega2560 using Atmel Studio 6.2 and avrdude

Answers: 0


body:
I am trying to output something every one second with the following code.

    volatile uint64_t timerCounts = 0;
    double timenow,pretime;
    void setup()
      {
         Serial.begin(19600);
         noInterrupts();
         TCCR2A = TCCR2B = 0;
         TCNT2 = 0;
         OCR2A = 124; //Zero Relative 125
         TCCR2B = B00001101;  //prescaler = 1024
         TIMSK2 |= (1 << OCIE1A);
         interrupts();

         Serial.print("Begin... \n");
      }

      //**********************************************************************
      //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
      //  16Mhz / 125 / 1024 = 125 Hz    0.008s

      ISR(TIMER2_COMPA_vect)
      {
         timerCounts++;
         if (timerCounts == 125){
            Serial.print("1s");
            timerCounts = 0;
         }
      }  // end of TIMER2_COMPA_vect

      void loop()
      {

      }

In the above code, I have set the `OCR2A `(output compare register) to 124``, which is well below `256`(2^8). A user defined counter is also used.

However, when I execute the programme, the interval between consecutive outputs is less than 1 second.

When I change it to timer 1, the interval becomes roughly 1 second.
When I change it to timer 0, the interval becomes longer than 1 second.

Anyone knows why?

Thanks.

title: Weird Arduino timer behaviour

Answers: 1

body:
OCR2A doesn't do anything because the timer is in 'normal' mode. In normal mode the timer will just count to 256, not 125. Which would mean the you get a serial.print every 2.05s.

You need to use CTC mode. Do this by setting the `WGM21` bit to 1.

    TCCR2A = _BV(WGM21);


body:
    int val1 =(mfrc522.uid.uidByte[0]);
    int val2 =(mfrc522.uid.uidByte[1]);
    int val3 =(mfrc522.uid.uidByte[2]);
    int val4 =(mfrc522.uid.uidByte[3]);

    String valA=String(val1);
    String valB=String(val2);
    String valC=String(val3);
    String valD=String(val4);
    uID=valA+valB+valC+valD;

The function above with `mfrc522.uid.uidByte[x]` is from the `MFRC522.h` Library by Miguel Balboa and it is initialized as byte there. But when I initialize the val1 to val4 as byte, the desired number doesn't appear. I don't intend to print the uID to serial (as someone may suggest that to readily print to serial as it converts it automatically to some ASCII strings), but instead in the `client.print()` of the Ethernet library along with other codes. I want to save it into another "greater" variable in terms of speed and memory allocation. The Arduino community warns about the use of `String` as it uses additional decoding which is not needed as well as may crash Arduino and make Arduino run out of memory. And somehow, I experience some lagging or hanging in the serial, which I thought maybe due to the use of Strings variable. Please help me. I've read some `sprintf()` concatenations and `free()` but not well documented, I'm quite confused on their explanations. :)

title: Is there any way that the values here be converted to another variable and not string?

Answers: 2

body:
The UidByte[] is a 10 character array, loaded with the tag ID (this is an RFID reader) by the library.

Your code is attempting to put a character value into integer variables.

What you mean to do (I think) is to read the string as a number - this would be `val=atoi(mfrc522.uid.uidByte)` which relies on there being only numeric data in the ID string - or at least, will only read the leading numbers (if any). Also, there are 10 characters in the string - if you want to limit this to 4 you will need slightly more code.

If you have a tag on which you set the ID then this is usable, for your tags at least; but you can't rely on numeric uid's being universal.

If your intent is, as you say, to include it in a longer string, then the overhead of atoi is completely unnecessary and you should just handle it as a string. I think you have misunderstood the warnings about strings, there isn't a problem just handling short chunks of fixed-length data as strings, and I think you are inadvertently causing trouble by extra conversions.

body:
`sprintf()` is a nicer way to do that (imo), however, there's nothing wrong with what you've done-- if you don't have a ton more code, I'd continue to use it.

It's simple and that's a lot more important that speed most of the time. Also, the likely memory usage isn't enough to worry about.

In my experience, once I got past 1500 bytes SRAM (dynamic) memory usage, I ran into trouble. But my projects have a ton of code. I've read through the `String` class code and it's totally reasonable-- you're not likely to experience lag there.

[My bet is that the lag is due to the timeout period](https://www.arduino.cc/en/Serial/SetTimeout), try making it smaller.


body:
I'm attempting to read data from my SD card, but I have strange behavior and can't figure out why this is happening.

I'm using **CardInfo** from the Arduino example and am trying to read the data from my SD card.

I'm faced with two different problems, but maybe they can be related:

**1:**  If I format my SD card from my Mac (FAT32), if my card is still empty, the program can read my card and output the right information. But if I add data from my Mac to the SD Card, card.init never initialise, and my data are never read (because of the hidden files). If I remove those hidden files, but let only the expected files be, the program never find them, like if my card was still empty. I don't know how to handle this.

**2:** From my Arduino, if I feed the card from the 3.3 V output, I get the

> Card type: SD2 Could not find FAT16/FAT32 partition. Make sure you've
> formatted the card

It only works on 5 V (but the card type becomes SDHC). So I've tried to feed my card with another 3.3 V/5 V supply (my Arduino is grounded to this supply as well), but this is only working on 5 V. On 3.3 V my card isn't detected. My wires to the SD card are about 15 inch. I don't know if it can affect it drastically, but this is the only 'weird' thing about this circuit. By the way I naively think my 3.3 V supply should handle that.

Here are my materials:
- Arduino Duemilanove

- For the SPI wiring I'm using pin 10 for SS.
- Using the Cardinfo from the Arduino library.

title: Struggling with SD card read on Arduino

Answers: 3

body:
First of all, use 3.3 V. You need a logic-level converter.

Then you have to understand SPI is not the main protocol used by SD cards, and that Arduino should use SDSC to be sure, as some libraries are SDSC only.

Then you may have a hardware problem (from *[FAT32/SDHC library for Wave and other shields][1]*):

> SDHC cards have a 3.3 V bus so most Adruino shields, like the Wave Shield, use a resistor voltage divider to shift bus levels from 5 V to 3.3 V. These voltage dividers can not meet the 10 ns rise time for most SDHC cards."

Also using an external power source *may* solve your trouble.

  [1]: https://forums.adafruit.com/viewtopic.php?f=31&t=8738

body:
I recommend you get a [MicroSD card breakout board](http://www.adafruit.com/products/254) from that link, or something similar. That's around $US 15.

![Micro SD breakout board][1]

That includes the logic level converters. That particular board is for the **micro* SD card, but similar converters could no doubt be found for an SD card. Or use that one with a micro-SD card and just get an SD converter for when you plug it into the Mac.

I personally have used the [SDfat library](https://github.com/greiman/SdFat) without any problems. However since he started rewriting it, I did have some issues. I have a [backup of an earlier version](http://gammon.com.au/Arduino/SdFat-master.zip) which might be useful if the live library doesn't work for you.

You might be best off not formatting the card, but leave it as factory formatted. That will probably be compatible with the Mac, and also the SDfat library.

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

body: Mac OS X will default to using the GPT partition table to format the card, even in FAT32. This does not work with the standard Arduino library for SD cards I've found. You must use MBR.