message:
Why does pulse sensor shows gaps when I move it?

I modified the serial code in this way and I don't think the gap is produced by my edit even because it made it even before:

    //////////
    /////////  All Serial Handling Code,
    /////////  It's Changeable with the 'serialVisual' variable
    /////////  Set it to 'true' or 'false' when it's declared at start of code.
    /////////

    void serialOutput(){   // Decide How To Output Serial.
     if (serialVisual == true){
         arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
     } else{
          sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
     }
    }

    //  Decides How To OutPut BPM and IBI Data
    void serialOutputWhenBeatHappens(){
     if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
        //ASCII Art Madness
        Serial.print(BPM);
        Serial.println("");

     } else{
            sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
            sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
     }
    }

    //  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
    void sendDataToSerial(char symbol, int data ){
        Serial.print(symbol);

        Serial.println(data);
      }

    //  Code to Make the Serial Monitor Visualizer Work
    void arduinoSerialMonitorVisual(char symbol, int data ){
      const int sensorMin = 0;      // sensor minimum, discovered through experiment
    const int sensorMax = 1024;    // sensor maximum, discovered through experiment

      int sensorReading = data;
      // map the sensor range to a range of 12 options:
      int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

      // do something different depending on the
      // range value:
      switch (range) {
      case 0:
        Serial.println("");

      }
    }

    63

    63
    63
    63
    63
    62
    62
    62
    62
    62
    62
    62
    63
    62
    63
    64
    63
    63
    64
    64
    65
    65

    65
    68
    74
    78
    86
    95
    105
    112
    123
    141
    167
    154
    136
    128
    123
    125
    123
    127
    132
    104
    93
    92
    92
    89
    83
    77
    73
    69
    65
    70
    70
    71

You can find all the code here:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

In the code I posted there is some code I don'f find useful but I can't delete it for reason linked to variables used for other functions I don't know I'm using.
You can also see huge changes in the heart rate that surely don't reflect the reality.

body:
One of the possibilities is when you move your finger, the sensor grip loosened and doesn't count a "beat". So the sensor emits `data = 0`, and it will cause

    Serial.println("");

in your switch-case.


sender: user

message:
Can I use two sensors with different baud rate without problems on arduino?

One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.

What do you think?
The first sensor is the pulse sensor, while the other is the gsr sensor by grove.
Link: http://pulsesensor.com/
Link 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

sender: assistant

body:
You can only have one sensor on one serial port, and the baud rate is set on the serial port.

So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.


body:
> One sensor has a baud rate of 115200, the other 9600. I think this
> will create problems in the serial because I can only choose one baud
> rate.
>>Why do you think the sensor has a baudrate?

Both the sensors seem to use the "serial connection" of the Arduino to log their information.

> What do you think? The first sensor is the pulse sensor, while the
> other is the gsr sensor by grove. Link: http://pulsesensor.com/ Link
> 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor
>> I think it'll work fine.

Looking at the facts of your sensors, the pulse sensor does have some kind of weird low-level timing/ADC access. But your Grove GSR sensor can basically be read out through an analog input.

**So what to choose?**

You could choose 9,6k or 115k2 (9600 or 115200). It wouldn't make all that much difference. 9600 or 115200 will work fine. 115200 is a lot faster, but for debugging purpose 9600 is used, since it's often default and (often) more reliable.

**Wrapping up**

I don't think there is an issue with the two serials. You can easily log both messages to the same serial output.

Try using 115200 since timing is essential in your case, you want your sensor to be response/fast.

They do both use the same analog to digital converter on your board. An Arduino can't check both sensors at the same time. But by switching between them very fast, you will get a resolution that's good enough.


message:
Power problems stacked Arduino shields

I have a weird problem. I am currently building a BB-8. Therefore, I am using an Arduino Uno. On top, I have stacked an Adafruit Motor Shield v2.3 and, again, on top of this, I have stacked the Sparkfun USB Host Shield. The Arduino is powered by a 9V-Block battery, the motors are powered separately by two 18650 Li-Ion batteries. To control the two Pololu motors, which have a stall current of 1.6 amps each, I use a Xbox 360 wireless controller, where the receiver is connected to the USB Host Shield.

Now to my problem. Every seems to work fine, until i cover everything with a styrofoam hemisphere. Yes, you've read right. If that happens, the controller signals is lost and does not connect again, unless I restart the Arduino. I have uploaded a small video on [youtube][1], where you can see the problem.

I guess, this is a power problem, since this issue does not occur, when I connect the Xbox receiver to my Mac. Has anyone an idea, how to solve this problem?

I already tried another power source. And the USB host shield should give enough power, since the specs are saying, that 500 mA is no problem, and hit is exactly the USB 2.0 spec. The combination of the shield shouldn't be a problem, too. I carefully chose this shields, because the motor shield is just using the pins A4 and A5, the USB host shield is using some of the digital pins, so I think there is no interference.

Thank you for your help.

**EDIT**
I have tested it a bit more now and i think i can reduce the probable reasons. First, i tried some other power supplies, from AA batteries on the VIN pin to external power adaptors. Next, i tried other xbox receivers and controllers. I also tried a playstation 3 controller with a Bluetooth dongle. Nothing solved the problem. I also covered the Arduino with other things than styrofoam, like a garbage can, cardboard and some metal box. This worked, so the problem was only with styrofoam. Now i haven't covered the Arduino, but i slowly got closer. About 20 cm from the Arduino, it stopped working. My clue: static electricity. Do you think this can be a problem? And if yes, how can i solve this?

  [1]: https://youtu.be/kabobDlFX2s

body: Those 9v batteries are not known for their ability to supply current. Their best uses are long-term powering of low-current standby devices like smoke detectors. I'd first try replacing it with 4 double- or triple-A cells, whatever you can scrounge up for a quick test. My guess is when you cover the robot the Xbox receiver's current demand increases just enough to crash or reset something. A-cells may supply enough more current without the voltage sagging.


body: So, I solved the problem. As is mentioned in my question, the problem was static electricity. I primed the styrofoam sphere with some special primer to make the styrofoam a little more stable and so on. That's it. Luckily I didn't touch the Arduino with the sphere. I think it would have damaged the Arduino.


message:
Setting Up a JavaEE app on an Arduino Yun Board

I'm looking for some reference material to start on a project I'd like to do.

I have an Open House at my school. My group project has been to create a little timesheet app using JavaEE. I just started looking for how to do this and if I can. But I would like to wow people a bit by setting this up using an Arduino Yun board. I know it has WiFi and I'm pretty sure I can run Linux on the little guy.

Any help would be greatly appreciated.

body:
Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has.
Java EE is magnitudes bigger (and bugger) than that.

You might try with Java SE embedded, the smallest profile might fit to 11Mb:
http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf
and then you can roll your own web server.

(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).

What you can try is Raspberry PI, which works well with network, and Java (SE).
Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish_4_on_the_raspberry


message:
Connect a USB slave into Arduino using FTDI

Probably I'm asking a nonsense question but I'm new at interfaces.

I want to connect an USB barcode scanner to an Arduino (Uno or Mega). I've read that I need a USB host shield to achieve this. But I don't have any. I have a FTDI, so I suppose I could plug the USB output of the scanner into the FTDI and connect the FTDI to the UART port of Arduino. Then, I would be passing the USB output to Serial.

Is it correct? Thanks and sorry if I said something stupid!

body:
No, that is completely wrong.

In USB you have *hosts* and *devices*. A *device* has to connect to a *host*. Your FT232 is a *device*. The barcode scanner is a *device*. Both of them need to be connected to a *host* for them to do anything.

So you need a USB *host* shield to act as that host.

However - check the manual for your barcode scanner: it may well have a RS-232 mode that it can be switched into (may need a different cable attached).


message:
Micro USB to USB adapter m/m

I'm looking into working with an Arduino micro, and I'd like to be able to plug it into my computer directly(without a cable). I've been looking around, and the best thing that I found was [this](http://www.gearbest.com/usb-flash-drives/pp_241630.html?currency=USD&gclid=Cj0KEQjwz-i3BRDtn53Z5Z7t4PUBEiQA23q2ADLBLxSTh67ggFcvjZenuXTcFK6nriQfRnaFchLybM8aAuhx8P8HAQ). The reason I haven't bought the linked adapter is because I've seen a number of bad reviews of the seller with close to half of the reviews being 1-star. Anybody have an idea where I can find something similar?

EDIT: I'm going to be using this for security testing, emulating a rubber ducky usb, so I need the computer to recognize the Arduino as an HID, not an arduino, but I also (obviously) need to be able to load my code onto it

body:
That adapter is not suitable. Not only is it the wrong gender on the large end, but it is designed for a completely different purpose.

That is an "On The Go" adapter which is designed for connecting things with a USB A plug (such as a memory stick, etc) to a mobile phone's USB socket.  It is not suitable for connecting things to an Arduino.

I have never heard of an adapter like you want, but I have heard of Arduino-like boards that plug direct into a computer like you want. One example is the [Digispark from Digistump](http://digistump.com/products/1) which is an ATTiny85 on a USB plug.


message:
Get strings from Serial.read()

I want to read strings from `Serial.read()` to send them later.

To get the data from the Serial monitor I'm doing this:

<!-- language: c -->

    String stringOne  = "";
    int  incomingByte;

    if (Serial.available() > 0) {

      while(Serial.available() > 0)
      {
         incomingByte= Serial.read();
         stringOne = String(stringOne + String(incomingByte));
      }

      Serial.println(stringOne);
      stringOne = "";

The issue is that when I type:

    'a'

I got:

    '97'
for
    'abc'

I got

    '979899'

so on and so forth.

What should I do in order to get the same string I type?

body:
You're adding the ASCII value of each char to your string, hence you get numbers. See the various String constructors at:
https://www.arduino.cc/en/Tutorial/StringConstructors

Either cast the read byte to a char:

    stringOne = String(stringOne + String((char)incomingByte));

or consider receiving characters as chars, instead of ints:

    char incomingByte;

There is a perfectly valid one-method call which does all of this hassle easier and more efficiently: https://www.arduino.cc/en/Serial/ReadStringUntil

Note that you'll sooner or later anyhow have to add a framing prototcol. For example, you're sending down text commands to Arduino, and each command is separated by a new line character. ReadStringUntil will handle that very nicely.


body:
Instead of using:

    while(Serial.available() > 0)
      {
         incomingByte= Serial.read();
         stringOne = String(stringOne + String(incomingByte));
      }

Use the following to cast them to character:

    while(Serial.available() > 0)
      {
         char incomingByte= Serial.read();
         stringOne.concat(incomingByte));
      }
    Serial.println(stringOne);
    stringOne="";


message:
How to make servo rotate for angle bigger than 180°

Connected servo motor (180°) to Arduino Uno R3.

Currently I am using a servo motor which have rotation angle specified as 180°, but I have a requirement to rotate to certain angles greater that 180°.

So do I need to go for a *continuous rotation servo motor (360°)*, so that I can stop the motor at different angles greater than 180°, was my assumption true, will continuous rotation servo motor satisfy this requirement?

I am referring to [Servo - Generic High Torque Continuous Rotation (Standard Size)](https://www.sparkfun.com/products/9347)

Current code, which I am using 180° servo motor.

<!-- language: c -->

    Servo myservo;
    int pos = 0;
    void setup() {
      myservo.attach(9);
    }

    void loop() {
       {
        myservo.write(180);
        delay(15);
      }
    }

body:
No. The continuous rotation servo rotates _continuously_ and you can not control where to stop. You can control the rotation direction and the speed at a little.

What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.

Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

 * steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
 * steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
 * steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)


message:
Thermistor value correct on Uno backwards on Nano

EDIT: upon further investigation: I found out that if I wired it Thermistor > resistor > GND values go one direction. If I wired it Thermistor > Resistor > 5v, it goes the other direction. So my new question: Which way is correct? One sketch assumes it works one way, and one the other.

I have some Thermistors from [here][1]. I have an Arduino Nano and an Arduino Uno, both set up identically with pictures of the wiring below. On the sketch below, when I heat up the thermistor the value increases on the Uno and decreases on the Nano.

    // which analog pin to connect
    #define THERMISTORPIN A0
    // resistance at 25 degrees C
    #define THERMISTORNOMINAL 10000
    // temp. for nominal resistance (almost always 25 C)
    #define TEMPERATURENOMINAL 25
    // how many samples to take and average, more takes longer
    // but is more 'smooth'
    #define NUMSAMPLES 5
    // The beta coefficient of the thermistor (usually 3000-4000)
    #define BCOEFFICIENT 3950
    // the value of the 'other' resistor
    #define SERIESRESISTOR 9800

    int samples[NUMSAMPLES];

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

    void loop(void) {
      uint8_t i;
      float average;

      // take N samples in a row, with a slight delay
      for (i=0; i< NUMSAMPLES; i++) {
           samples[i] = analogRead(THERMISTORPIN);
       delay(10);
      }

      // average all the samples out
      average = 0;
      for (i=0; i< NUMSAMPLES; i++) {
         average += samples[i];
      }
      average /= NUMSAMPLES;

      Serial.print("Average analog reading ");
      Serial.println(average);

      // convert the value to resistance
      average = 1023 / average - 1;
      average = SERIESRESISTOR / average;
      Serial.print("Thermistor resistance ");
      Serial.println(average);

      float steinhart;
      steinhart = average / THERMISTORNOMINAL;     // (R/Ro)
      steinhart = log(steinhart);                  // ln(R/Ro)
      steinhart /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
      steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
      steinhart = 1.0 / steinhart;                 // Invert
      steinhart -= 273.15;                         // convert to C

      Serial.print("Temperature ");
      Serial.print(steinhart);
      Serial.println(" *C");
      Serial.println();

      delay(1000);
    }

On the sketch below, the Uno is backwards and the Nano is correct. I'm sure there's something simple I'm missing, but I sure can't find it. Any suggestions?

    #include <math.h>

    double Thermistor(int RawADC) {
     double Temp;
     Temp = log(10000.0*((1024.0/RawADC-1)));
     Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
     Temp = Temp - 273.15;
     Temp = (Temp * 9.0)/ 5.0 + 32.0;
     return Temp;
    }

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

    void loop() {
      int val;
      double temp;
      val=analogRead(7);
      temp=Thermistor(val);
      Serial.print("Temperature = ");
      Serial.print(temp);
      Serial.println(" F");
      delay(1000);
    }

[Nano Wiring][2]

[Uno Wiring][3]

  [1]: http://www.amazon.com/100-Temperature-Measurement-Thermistors-MF52-103/dp/B0087YI1KW/ref=sr_1_1?ie=UTF8&qid=1459212561&sr=8-1&keywords=thermistor
  [2]: https://i.stack.imgur.com/QQ8Fs.jpg
  [3]: https://i.stack.imgur.com/kIM29.jpg

body:
There is no "correct" way. The thermistor and the resistor combine to make a voltage divider. Whether the thermistor is connected to +5V (AKA R1) or to GND (AKA R2) determines the formula to use to calculate the resistance.

The general form is:

              R2
    Vout = ------- x Vin
           R1 + R2

To solve for R2 (thermistor connected to GND) you re-arrange to:

                     1
    R2 = R1 x --------------
              (Vin/Vout) - 1

To solve for R1 (thermistor connected to +5V) it's:

         R2 x Vin
    R1 = -------- - R2
           Vout

Vin, of course, is 5V, and Vout is a voltage you calculate from the analog reading on the Arduino.

Once you have the resistance you can then calculate the temperature. That part doesn't change regardless of the orientation of the thermistor.


message:
How can I exactly put my sensor at 4 Hz readings?

I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor with this code:

    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    const long interval = 1000;
    void setup(){
      long sum=0;
      Serial.begin(9600);
      delay(1000);

      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
       Serial.print("threshold =");
       Serial.println(threshold);
      }

    void loop(){
      int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;
      delay(250);
      }

There is the delay way to skip milliseconds or the `millis()` function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.

Here's what I am trying

    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    const long interval = 1000;
    unsigned long startTime=millis();

    void setup(){
      long sum=0;
      Serial.begin(9600);
      delay(1000);

      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
       Serial.print("threshold =");
       Serial.println(threshold);
      }

    void loop(){

      if((millis() - startTime) % 250 == 0) {
       int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;

      }
      }

body:
Something like this should do it:

    const byte LED = 13;
    unsigned long lastReading;
    const unsigned long INTERVAL = 250;

    void setup()
      {
      pinMode (LED, OUTPUT);
      }  // end of setup

    void loop()
      {
      unsigned long now = millis ();
      if (now - lastReading >= INTERVAL)
        {
        lastReading = now;
        digitalWrite (LED, HIGH);
        delay (50);  // simulate reading delay
        digitalWrite (LED, LOW);
        }
      }  // end of loop

This code saves when we are *about to* do a reading, and uses that as the basis for when to do the next one. This eliminates the reading time from the equation. In my example code I throw in a 50 ms delay to prove the point.

The LED flashes exactly at 250 ms intervals.


body:
The difference between your first code and the second one is that the first one is blocking execution when it reaches the `delay` function, but the second code keeps running without being blocked.

Now your algorithm has a drawback, the loop may or may not reach the `if` condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :

 unsigned long T = millis();

 ...

 if( millis() - T >= 250 ) {
  ... // sensor stuff
  T = millis();
 }

This idea is also presented in this article <https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay>.

Another approach is to use Timers and Interrupts, but this is far more complicated (<http://playground.arduino.cc/Code/Timer1>).


body:
Both other answers are correct, but my usual way of dealing with this is

    unsigned long startTime = 0;
    #define MEASURE_PERIOD 250
    ...
    void loop()
    {
     if((millis() - startTime) >= MEASURE_PERIOD)
     {
      startTime += MEASURE_PERIOD;
      // Do your job, such as
      int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;
     }
    }

The difference between this way and the other ones (Nick's way, i.e. saving `millis` and setting the `startTime` variable to it, or nico's one - which is worse - , to set it again), is that this way if there is some error (e.g. 260ms between two calls) it gets recovered by the next cycle (which will be of 240ms), while in their way it is not.


message:
How to perform a data transfer to an external server

So I'm doing a project that involves getting sensor data from several sensors, and then sending them to an external server when a tragic occurs. But I've been having trouble figuring out how to send this data, and I am welcome to advice (I'm still relatively new to Arduino coding).

I'm using an Arduino mega, with a sim900 GSM shield and an SD card. The sensors are just analog reads and a GPS.

I've looked into FTP, a Xively account and http requests to a web server but couldn't figure it out.

body:
There is a good example of using the **SubmitHttpRequest()** in this article:
[GPRS Shield SIM900 Arduino][1]

You could easily modify:
**mySerial.println("AT+HTTPPARA=\"URL\",\"www.yourwebsite.com/testing.php\"");**

to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like:
http://**yourwebsite.com**/testing.php?**sensor1**=5&**sensor2**=10

  [1]: https://roysoala.wordpress.com/2012/11/20/gprs-shield-sim900-arduino-get-data-application/


message:
Need to make an action just once when condition is reached

I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.

I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over.
How can I make it to sound just one time?

Here is my code:

    #include <PCM.h>
    const unsigned char sample[] PROGMEM = { //Here goes the sample
    };
    int low = 0;
    int mid = 0;
    int high = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (high > 50){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
      }
      else if (mid >50){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
      }
      else if (low > 50){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
      }
      delay(100);

body:
A possible solution to your problem can be the following:

    #include <PCM.h>
    const unsigned char sample[] PROGMEM = { //Here goes the sample
    };
    int low = 0;
    int mid = 0;
    int high = 0;
    bool first = true;
    bool second = true;
    bool third = true;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (high > 50 && first){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
        first = false;
      }
      else if (mid >50 && second){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
        second = false;
      }
      else if (low > 50 && third){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
        third = false;
      }
      delay(100);

In this way the sound for each level will be played only once. I hope this is what you were looking for.


body:
As an addition to the answer of Mattia.

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

I suspect you have something like:

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (resetVariables){
         first = true;
         second = true;
         third = true;
         resetVariables = false;
      }

      if (high > 50 && first){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
        first = false;
      }
      else if (mid >50 && second){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
        second = false;
      }
      else if (low > 50 && third){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
        third = false;
      }

      if(buttonPressed){
        resetVariables = true;
      }
      delay(100);
    }

A better practice would be to use another function

    void resetFlags() {
      first = true;
      second = true;
      third = true;
    }

And the main code would be:

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (high > 50 && first){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
        first = false;
      }
      else if (mid >50 && second){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
        second = false;
      }
      else if (low > 50 && third){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
        third = false;
      }

      if(buttonPressed){
        resetFlags();
      }
      delay(100);
    }

Would this be faster?

 - It would at least make your loop code more readable, instead of juggling flags around.
 - `resetFlags()`; would act immediately and independent from the flag checking etc.
 - It saves checking unnecessary if's (which equals a very little speed increase).
 - It saves 1 boolean (byte maximal in memory) which equals a very little memory/speed increase.

But why mind speed if you have a 100msec delay?
You could make it only output the water level when it changes. Then you can run the water checking extremely fast!
(It wouldn't spam your console, plus, writing to console takes considerable amount of time, compared to checking if's.)


message:
Arduino Pro Micro troubles

I recently bought a brand new Arduino pro micro from [Amazon][1], I set it up according to the instructions on [sparkfun][2], except that when I plug it in, Windows doesn't even show that it tried to install device driver software. I figured it might just be a windows 10 thing because the tutorial was written on windows 7, so I forged ahead, and updated the device driver for COM3 in device manager, and attempted to upload a simple test for HID emulation:

    #include <Keyboard.h>

    void setup() {
      Keyboard.write('z');
    }

    void loop() {
      Keyboard.write('a');
      delay(5000);
    }

It compiled just fine, and the IDE said it started uploading to the device, However, as it was uploading (or so I thought) I read a little farther and realized that the IDE wasn't set to use the right voltage (3.3V instead of 5V) I closed the IDE and reopened my sketch, changed the voltage to match up, and tried uploading it again. Here, it got stuck on the `Uploading...` text and so again, I closed the IDE.

Only the LED closest to the USB port is on, and it's solid green. I've connected to my computer using a Micro USB to USB adapter, and I initially plugged the board into a USB 3.0, but then switched to 2.0 to see if it made a difference. I have also tried it on Ubuntu 14.04 with no luck. I don't think it's bricked because if it was, my computer would still recognize it, but not know what it was (according to sparkfun), and as a result, I have yet to try the debricking method they suggest. Any thoughts?

  [1]: http://www.amazon.com/OSOYOO-ATmega32U4-arduino-Leonardo-ATmega328/dp/B012FOV17O?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00
  [2]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#installing-windows

body:
The Pro Micro, like the Leonardo, cannot automatically reboot into the bootloader like boards such as the Uno and Mega.  Instead it relies on the sketch running on it listening for a special combination of events (open the serial port, set the baud rate to 1200 baud, close the serial port) to activate the bootloader.

If, for whatever reason, you don't have a working sketch installed on the board (such as you aborted the upload part way through) then there will be nothing there to listen for the "reboot into bootloader" instructions.

So you need to manually enter the bootloader. Fortunately it should be easy enough, but timing is all important.

When you first plug the board in, or when you press the reset button, you get a few seconds where the board is in the bootloader.  On the Leonardo that is signified by the LED glowing and pulsating - I don't know off hand what is shown on the Pro Micro.

As long as you press the reset button just before you compile and upload your sketch, and as long as the upload portion doesn't take too long to start (tip: compile it before uploading, it makes it faster) it should then install the sketch into the board and from then on the auto-reboot should start working.

(Note: I haven't used a Pro Micro - this is all from my experience with the Leonardo which I believe uses the same bootloader.)


body:
You have to retrieve the VID/PID numbers your board actually has and change your boards.txt accordingly. On my Linux computer I made a USB connection with my corrupted pro micro clone, "lsusb" does not show it, but if I pull rst-pin down (pulse) "lsusb" does show it for a few seconds. Now I know the vid:pid numbers. I edited boards.txt (~/.arduino15/packages/Sparkfun/hardware/avr/1/1/5/:

promicro.build.vid=0x1b4f      (edited 1b4f with vid outcome of "lsusb")

promicro.menu.cpu.16MHzatmega32U4.build.pid.0=0x9205  (9205 edited)

Then in Arduino IDE I gave a reset pulse, the port showed up. I loaded the sample blinky script from sparkfun (https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#faq-change-pid), clicked "upload" and once again gave a reset pulse. The upload succeeded and my pro micro clone is back to normal.


message:
Arduino clone CH340G (ATmega328P), MIDI over USB

I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their `Teensy` connected to their laptop and reacting to MIDI signals over USB.

Not knowing anything, I bought my clone and soon learned about the whole `CH340G` limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (`ttymidi`) in order to send the signals to my Arduino clone.

I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of [V-USB][1] and the project [V-USB-MIDI][2] but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and `.h` header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the `CH340G`.

In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.

Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need `ttymidi` to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".

  [1]: https://www.obdev.at/products/vusb/index.html
  [2]: http://cryptomys.de/horo/V-USB-MIDI/index.html

body:
V-USB [bit bangs](https://en.wikipedia.org/wiki/Bit_banging) some GPIO pins so that they speak the low-speed USB protocol.
This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.

Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a *second* AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)

Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently.
If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.


message:
HC-05 to low cost AB shutter 3

I'm trying to connect a HC-05 to AB Shutter3 module. However, when I try to search AB Shutter3 address via AT commands (`AT+INQ`) I could not find AB Shutter3.

I want to integrate both, so that I can send commands from an AB Shutter button click to HC-05.

I also want to know whether the HC-05 needs to be in master or in slave mode.

body:
I rather suspect the AB Shutter 3 is a Bluetooth HID device (like a keyboard or a mouse). The HC-05 can only communicate with Bluetooth Serial devices, such as the HC-06 or systems that can emulate a serial device (such as a computer or a smartphone).

You won't get them to communicate no matter how hard you hit them.


message:
Arduino fried? Onboard blink ok; offboard blink not ok

EDIT :

I have plenty of weird bugs. I will open another thread, and come back to this one when I have better understanding, rather than completely modify this one halway through. Sorry to every answerer for my electronic incompetence which led me to ask the wrong questions; I hope the other thread makes more sense.

I have recently exhumed an arduino from a cupboard, and can't seem to make even a blinking LED circuit work correctly.

Here's the sketch :

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

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

This has been tried without the circuit, on pin 13, using the onboard LED, and it worked.

However, using the following circuit, it did not result in a blinking LED, using several pins (8, 9, 12, 13) and LEDS.

May I assume the arduino is fried?

Here is a thumbnail of the circuit : [![circuit picture][1]][1]

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

body: Try lighting up the LED without using any resistance in the middle, if that doesn't work try with a LED which consumes less current even if that doesn't work put the pin to HIGH state in code and measure the voltage of the given pin using a multimeter it should read above 3.3V. If neither of these work then you can be sure that your arduino is fried


body:
Here's a guide posted by Nick Gammon for checking if your Arduino is bricked [Is My Arduino Bricked ?][1]

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293


body:
It it possible the non-working LED got wired backward (it wouldn't be the first time!)? If the LED is clear enough, hold it up to the light and look inside the plastic bubble. There will be two bits of metal, one attached to each lead. One of them is significantly larger than the other; that's the cathode and it needs to be connected to the more negative side of the circuit. Here's a [picture][1].

  [1]: http://www.instructables.com/id/IDENTIFY-THE-ANODECATHODE-of-LEDs/


body:
You haven't exactly got the LED connected to pin 9, as in the code, have you?

I find it hard to believe that you can upload new sketches, but none of the pins work. Try pins 0 or 1, in the sketch, for example. Or the whole lot:

    void setup() {
      for (int i = 0; i < 20; i++)
        pinMode (i, OUTPUT);
    }

    void loop() {
      for (int i = 0; i < 20; i++)
      {
        digitalWrite(i, HIGH);
        delay(1000);
        digitalWrite(i, LOW);
        delay(1000);
      }
    }

Now methodically test every pin.

---

> What happens if you plug the white jumper into 5V rather than the current digital pin 12

<!-- -->

> The LED doesn't light.

Something's wrong with your testing. The processor cannot be powering up, and accepting new sketches, yet not have power to the +5V pin.


body: My arduino is not bricked, I just don't know how many things I don't understand about electronics, and make every single mistake I can make, especially while cabling.


message:
Arduino GPRS (GSM) shield (SIM900) no long pins

I have bought a SIM900 shield for an ordinary Arduino Uno board. The problem is that it doesn't have long pins on the bottom side, making it impossible to click on mu Arduino Uno.
The shield I have is this:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/ZOqzp.jpg
As you can see, there are identical pin spaces next to the red and yellow plastic female pin things. Can I just solder new pins in the free spaces and will it work like that?
I notice that the yellow and red plastic female pin holders on my board are on the free spaces in this picture. I supposed I can just use the adjacent foles to solder long pins so I can use it for my Arduino?

body:
Yes, you can.

There is two methods of making shields stackable:

1. Use the quite hard to source extra long pinned headers to go right through and down (such as these https://www.adafruit.com/products/85) , or

2. Use separate headers and pins and (if you are using through hole) offsetting them.

Your shield uses the second method, but the descending pins haven't been populated.  By populating those pins you are just completing the build.


message:
Diagnosing crashed Arduino Uno

I have an Arduino Uno connected to a motor controller over I2C. The Arduino accepts commands from a Raspberry Pi via the USB serial line.

I'm trying to diagnose a problem where the Arduino will become completely unresponsive. It's programmed to respond to a "ping" request every N seconds, and for some reason I can't identify, it seems to crash and no longer respond to any commands. However, the motor controller continues powering the motors.

Everything is powered from a 12V Li-Po battery, but everything is located behind 5V regulators. When this problem happens, the battery is fully charged and the motors aren't sourcing much current, and neither the motor controller or Raspberry Pi are effected, so I've ruled out a brownout.

My theory is there's some subtle programming error in my Arduino code that's causing an "exception", but I don't know how to identify it. I've tried adding special code to allow me to trigger one of these, by indexing an array outside of its limits or calling a null function pointer, but the Arduino stubbornly refuses to crash when I try to explicitly make it.

How do I diagnose an Arduino becoming unresponsive?

body:
Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:

    do {
        add_logs_in_suspicious_places();
        wait_until_it_crashes();
        analyze_logs();
    } while( ! i_know_why_it_crashes() );

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)


body:
There is an excellent [post][1] by Nick Gammon that covers a wide array of possible problems. Look into this, as might be useful.

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293


body:
If you have spare pins, add debugging LEDs. For example, toggle one at the start of `loop`, another at the start of another function, and so on. When the Arduino "crashes" the state of the LEDs should provide a hint as to where in the code it is.

>  but the Arduino stubbornly refuses to crash when I try to explicitly make it.

Typically you are indexing outside an array or using uninitialized memory. Your debugging code has moved the problem around enough to stop it happening (or appearing to happen).

If you amend your question and post your code we might spot something.


message:
2WD robot - logic error

I am making a basic 2WD robot using Arduino Uno with motor shield.
I am getting no compile errors - but something in my logic flow is not working as expected.

Expected Operation:

 1. Ping sensor does distance check.
 2. If distance is less than 5cm.
 3. Turn both Channel A & B motors half-speed for 1 second.
 4. Stop motors.
 5. Take new distance reading ping, start again.

What however is happening, is that channel A works as expected, but channel B motor keeps running??
Where is my code / logic mistake?

Later date I will add to `else` statement to turn one wheel to change direction.

    /*
     HC-SR04 Ping distance sensor:
     VCC to arduino 5v
     GND to arduino GND
     Echo to Arduino pin 7
     Trig to Arduino pin 8
     */

    #define echoPin 7 // Echo Pin
    #define trigPin 8 // Trigger Pin
    #define LEDPin 13 // Onboard LED

    int maximumRange = 1000; // Maximum range needed
    int minimumRange = 1; // Minimum range needed
    long duration, distance; // Duration used to calculate distance

    void setup() {
      // put your setup code here, to run once:

    Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

      pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
      pinMode(9, OUTPUT); /* Motor Channel A */

      pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
      pinMode(8, OUTPUT);

      }

    void loop() {

      /* Distance check begins */

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);

      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);

     //Calculate the distance (in cm) based on the speed of sound.
     distance = duration/58.2;

     /* End distance check */

     if (distance >= 5){
     /* Distance great enough to provide room to move */
      Serial.println("Move!");

      digitalWrite(LEDPin, HIGH); /* LED show movement */

      digitalWrite(12, LOW); /*move channel A motor half-speed */
      digitalWrite(9, LOW);
      analogWrite(3, 123);

      digitalWrite(13, HIGH); /*move channel B motor half-speed */
      digitalWrite(8, LOW);
      analogWrite(11, 123);

      delay(1000);

      digitalWrite(9, HIGH);
      digitalWrite(8, HIGH);
     }

     else {
     /* Send the distance to the computer using Serial protocol, and
     turn LED OFF to indicate successful reading. */
     Serial.println(distance);
     digitalWrite(LEDPin, LOW);
     }

     //Delay 50ms before next reading.
     delay(500);

    }

body:
I believe that your error is in that you declare `LEDpin` as pin 13 and then your motor B as pin 13 as well, that to me would result in errors when you write to the led in the else statement at the end of your code. I would recommend that you clean this up, don't use pins for different things. Try this first.

Your logic is ok in terms of functionality.

Also why is there inconsistency at this part on your code:

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

    digitalWrite(12, LOW); /*move channel A motor half-speed */
      digitalWrite(9, LOW);
      analogWrite(3, 123);

      digitalWrite(13, HIGH); /*move channel B motor half-speed */
     digitalWrite(8, LOW);
      analogWrite(11, 123);

Why do you say pin `12` must be` LOW` and `13 HIGH` when moving forward? Is this the way your un-mentioned circuit setup works, if possible could you add this info?


message:
Altering SoftwareSerial to transmit more than 1 byte at a time

I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.

One of the really good suggestions I have heard is to use [Manchester encoding][1] on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I *assume.*

Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems?
Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.

    size_t SoftwareSerial::write(byte* b)
    {
      if (_tx_delay == 0) {
        setWriteError();
        return 0;
      }

    // By declaring these as local variables, the compiler will put them
    // in registers _before_ disabling interrupts and entering the
    // critical timing sections below, which makes it a lot easier to
    // verify the cycle timings
    volatile uint8_t *reg = _transmitPortRegister;
    uint8_t reg_mask = _transmitBitMask;
    uint8_t inv_mask = ~_transmitBitMask;
    uint8_t oldSREG = SREG;
    bool inv = _inverse_logic;
    uint16_t delay = _tx_delay;

    //Doubtful of this loop ------------------
    for(int i = 0; i < 128; i++)
    {
      if (inv)
        b[i] = ~(b[i]);
    }

    cli();  // turn off interrupts for a clean txmit

    // Write the start bit
    if (inv)
      *reg |= reg_mask;
    else
      *reg &= inv_mask;

    tunedDelay(delay);
    for(int j = 0; j < 128; j++)
    {
      // Write each of the 8 bits
      for (long i = 8; i > 0; --i)
      {
        if (b[j] & 1) // choose bit
          *reg |= reg_mask; // send 1
        else
          *reg &= inv_mask; // send 0

        tunedDelay(delay);
        b[j] >>= 1;
      }
    }
    // restore pin to natural state
    if (inv)
      *reg &= inv_mask;
    else
      *reg |= reg_mask;

    SREG = oldSREG; // turn interrupts back on
    tunedDelay(_tx_delay);

    return 1;
    }

Here is the original function.

    size_t SoftwareSerial::write(uint8_t b)
    {
    if (_tx_delay == 0) {
      setWriteError();
      return 0;
    }

    // By declaring these as local variables, the compiler will put them
    // in registers _before_ disabling interrupts and entering the
    // critical timing sections below, which makes it a lot easier to
    // verify the cycle timings
    volatile uint8_t *reg = _transmitPortRegister;
    uint8_t reg_mask = _transmitBitMask;
    uint8_t inv_mask = ~_transmitBitMask;
    uint8_t oldSREG = SREG;
    bool inv = _inverse_logic;
    uint16_t delay = _tx_delay;

    if (inv)
      b = ~b;

    cli();  // turn off interrupts for a clean txmit

    // Write the start bit
    if (inv)
      *reg |= reg_mask;
    else
      *reg &= inv_mask;

    tunedDelay(delay);

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

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

    // restore pin to natural state
    if (inv)
      *reg &= inv_mask;
    else
      *reg |= reg_mask;

    SREG = oldSREG; // turn interrupts back on
    tunedDelay(_tx_delay);

    return 1;
    }

The serial buffer can only hold 64 bytes at a time, but I am using the following [code][2], courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.

  [1]: http://forum.arduino.cc/index.php?topic=63755.0
  [2]: http://www.gammon.com.au/serial

body:
Basically your code has changed the size of the RS-232 packet from 10 bits to 1026 bits. There is nothing "wrong" with that, but it doesn't really solve the problem of a missed start bit - if anything it makes it worse since instead of losing 8 bits you lose 1024 bits.

Synchronisation is best done separately to the transmission of packets, and for that you need your packet to be nice and short.

A packet consists of 10 bits - the first is a LOW and the last is a HIGH; everything else in between is data.  The trick is to provide a forced idle period before sending of *at least* the amount of time it takes to transfer one packet.  That way if the receiver is mistakenly in a receive loop for whatever reason the 10 (or more) bits worth of HIGH will effectively cause the receiver to finish whatever it is doing and get ready to receive your real byte.

If you have a hugely long packet (1024 + 2 bits) flushing the receiver before transmitting will take a very long time - rather than just one byte's worth of time it will be your entire packet's transmit time.

On top of that you then have the problem of byte order and data integrity checking.  Just sending two bytes (or 128 bytes) is not reliable. You need to wrap those bytes in a protocol including a start-of-packet indicator (0x55 0xAA is common, as is the special ASCII character 0x01: SOH), packet or payload length, and checksums.  Options for things like sequence numbers, acknowledgements, packet retransmission, etc can also be built in to increase the reliability of the protocol.

Rather than trying to reinvent the wheel by changing the underlying data layer transmission you should learn the OSI 7 layer model and implement your protocol at a higher level than the data layer.


body:
So far you have asked a *lot* of questions about your project which uses SoftwareSerial to send a lot of bits:

* https://arduino.stackexchange.com/questions/17864/how-to-transmit-more-than-1-byte-continually
* https://arduino.stackexchange.com/questions/16390/basic-serial-transmission-protocol
* https://arduino.stackexchange.com/questions/17326/synchronization-and-implementing-hamming-code-on-software-serial
* https://arduino.stackexchange.com/questions/22274/encoding-clock-signal-into-linear-block-codes
* https://arduino.stackexchange.com/questions/16393/how-to-fix-baud-rate-when-hardware-capacity-has-a-low-limit
* https://arduino.stackexchange.com/questions/17021/unable-to-tell-if-error-is-from-receiving-or-transmitting-end
* https://arduino.stackexchange.com/questions/17309/read-function-in-software-serial

And now we have another one (this question).

I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.

In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.

To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is `128 * 10 * 104.17 µs = 133.338 ms.`

To use your system you need 1024 bits plus one start and stop bit, so that is `1026 * 104.17 µs = 106.878 ms.`

So far you have only saved 26.46 ms.

You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?

Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for `10 * 104.17 µs = 1.0417 ms`. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you `millis` and `micros`. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.

As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an *8-bit byte*. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.

Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of `1024 * 104.17 µs = 106.670 ms` between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.


message:
How can I reduce the size of my sketch?

Looks like I'm overshooting the storage of my Adafruit Trinket:

    Sketch uses 5,600 bytes (105%) of program storage space. Maximum is 5,310 bytes.
    Global variables use 109 bytes of dynamic memory.

Any tips for reducing the footprint of my code?

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>
    #include <Wire.h>
    #include <RTClib.h>

    #define LEDPIN 1
    #define TONE 4
    #define BTNPIN 3

    RTC_DS1307 rtc;
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, LEDPIN, NEO_RGB);

    long fadeTime = 1 * 10000L; // X minutes
    int colorStops = 256;
    int delaySpeed = fadeTime / colorStops;
    int notes[] = {262,294,330,349};
    int timeHour = 14;
    int timeMinute = 43;
    uint32_t alarmLength = 5 * 60000L; // 5 minutes

    void setup() {
      rtc.begin();
      if(!rtc.isrunning()) {
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }

      pinMode(TONE,OUTPUT);
      pinMode(BTNPIN, INPUT);
      digitalWrite(BTNPIN, HIGH);

      strip.begin();
      strip.show();
    }

    void loop() {
      DateTime now = rtc.now();

      if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 0){
        // Fade in light
        for(int i = 1; i<colorStops; i++){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(i,i,0));
          }
          strip.show();
          delay(delaySpeed);
        }

        // Play tone after light fully bright
        for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
          }
          strip.show();

          beep(TONE, notes[random(0,3)], 50);
          delay(100);
        }

        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(0,0,0));
        }
        strip.show();
      }
    }

    void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
    {   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
      int x;
      long delayAmount = (long)(1000000/frequencyInHertz);
      long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
      for (x=0;x<loopTime;x++)
      {
        digitalWrite(speakerPin,HIGH);
        delayMicroseconds(delayAmount);
        digitalWrite(speakerPin,LOW);
        delayMicroseconds(delayAmount);
      }
    }

    bool kill() {
      if (! digitalRead(BTNPIN)) {
        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(0,0,0));
        }
        strip.show();
        return true;
      }
      else {
        return false;
      }
    }

body:
The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.

The order I look for things to reduce the footprint of an Arduino program are:

* data (e.g. large strings)
* libraries
* your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.

It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.

You use the <Wire.h> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.

You may also save a little space by replacing initialized variables which don't change to constants. Storing `25` in a variable takes 1 byte, plus 2 bytes every time you reference it; `25` in a constant gets optimized away, and will take up 1 byte every time you reference it.

As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.

Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.

You can also save some bytes by removing the clause `  if(!rtc.isrunning()) {
`, once you have set it up once.

**Additional**: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may *not* save you anything in the end.

You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.

Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds*1000)/(delayAmount*2)) = (50*1000)/(3817*2) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.

In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)*238 (make sure you store at least the random number, you don't want it to change during the loop!).

You now have:

    #define random_beep_length 7
    void random_beep (unsigned char speakerPin)
    {   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
        // Heavily modified!
      int x;
      unsigned char pitch = 2865+random(0,3)*238;
      for (x=0;x<random_beep_length;x++)
      {
        digitalWrite(speakerPin,HIGH);
        delayMicroseconds(delayAmount);
        digitalWrite(speakerPin,LOW);
        delayMicroseconds(delayAmount);
      }
    }


body: An option not already mentioned, but may be worth mentioning, would be to remove the bootloader and program the chip directly with a hardware programmer (or another Arduino). That will increase the available sketch memory from 5kiB to the full 8kiB on the chip.


body:
As already mentioned by AMADANON Inc. in his answer, you should qualify
as `const` all the constant variables at the beginning of the program.
This is probably the biggest space saver.

You can gain something like 100 bytes by using [direct port
access](https://www.arduino.cc/en/Reference/PortManipulation) instead of
pinMode/digitalRead/digitalWrite. In the case of the ATtiny85, you only
have port B, and the Arduino pin numbers are the same as the Atmel bit
numbers. So you would for example use `PINB & _BV(BTNPIN)` instead of
`digitalRead(BTNPIN)`.

There are a few optimization opportunities in `beep()`:

* pass only one parameter, as `speakerPin` and `timeInMilliseconds` are
  constants in your program
* have this parameter be `delayAmount` instead of `frequencyInHertz`,
  and store these delays, instead of the frequencies, in the `notes[]`
  constant array
* do not compute the number of iterations (the misnamed `loopTime`)
  beforehand, instead compute the elapsed time and loop until you reach
  the required time

Here is my version of `beep()` with these optimizations:

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

    void beep(int delayAmount)
    {
      for (uint16_t t = 0; t < BEEP_TIME*1000/2; t += delayAmount)
      {
        PORTB |= _BV(TONE);  // digitalWrite(TONE,HIGH);
        delayMicroseconds(delayAmount);
        PORTB &= ~_BV(TONE);  // digitalWrite(TONE,LOW);
        delayMicroseconds(delayAmount);
      }
    }

Notice that the loop variable is actually _half_ the elapsed time. This
saves a few bytes. Making the number of iterations constant, as proposed
by AMADANON Inc., also saves a few bytes (6 bytes in my test).

You should also remove all the calls to `strip.Color()`: replace every
instance of `strip.setPixelColor(np, strip.Color(r, g, b))` by
`strip.setPixelColor(np, r, g, b)`.

With all these optimizations combined, I am quite confident you will
gain more than the 290 bytes you need to fit your program in the
Trinket.


message:
RF 433 Module with VirtualWire: transmit and receive using the same Arduino board

**I was wondering if it was possible to work, in the same Arduino board, both Transmitter and Receiver RF 433 MHz modules. Is it feasible?**

Here is the schematics I tried:

1) a pushbutton toggles a state value (0 or 1) and triggers the RF transmitter to send it as a message to the receiver module

2) the RF receiver, whenever reading the message, turns on or off a LED according to the corresponding value (0 or 1)

[![RF 433 Modules with the same Arduino board][1]][1]

Here is the source code I wrote:

    #include <VirtualWire.h>

    #define BTN_PIN A0    // pushbutton que aciona a transmissao
    #define LED_PIN 13    // LED aceso ao receber o sinal
    #define TX_PIN   4    // ligado ao pino DATA do transmissor RF
    #define RX_PIN   7    // ligado ao pino DATA do receptor RF

    #define SPEED  5000   // velocidade de comunicacao (bits por segundo)

    int estado = 0;

    void setup() {
      pinMode(BTN_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);

      vw_set_tx_pin(TX_PIN);  // transmissor
      vw_set_rx_pin(RX_PIN);  // receptor
      vw_setup(SPEED);
      vw_rx_start();

      Serial.begin(9600);
    }

    void loop() {
      int pressionado = !digitalRead(BTN_PIN);
      char msg[4];

      if (pressionado) {
        estado = !estado;
        itoa(estado, msg, 10);

        vw_send((uint8_t *) msg, strlen(msg));
        vw_wait_tx();

        Serial.print("Mensagem enviada: [");
        Serial.print(msg);
        Serial.println("]");

        delay(500);
      }

      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      int recebido = 0;

      memset(msg, 0, 4);
      if (vw_get_message(buf, &buflen)) {

        for (int i = 0; i < buflen; i++)
          msg[i] = char(buf[i]);
        msg[buflen] = '\0';

        Serial.print("Mensagem recebida: [");
        Serial.print(msg);
        Serial.println("]");

        recebido = atoi(msg);

        Serial.print("recebido = ");
        Serial.println(recebido);

        digitalWrite(LED_PIN, recebido);
      }
    }

When I run it, according to Serial Monitor it sends the message. The problem is no message comes to the RF receiver.

**Does anyone have an idea of what could be wrong?**

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

body:
As said in the comment you definitely need an antenna on both modules.

It is also possible that you are not supplying enough power to the 433 Mhz modules. The Arduino is not capable of outputting much current and RF transmitters generally have large current spikes.

So I would recommend that you use a seperate power supply to power the modules (do not forget to keep common ground between the Arduino and the Transmitter.)

I have also heard that it is preferred to not maintain common ground between the transmitter and the receiver. So if all else fails then use two separate power supplies.


body:
These lines in the ISR in VirtualWire.cpp

        if (vw_rx_enabled && !vw_tx_enabled)
         vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;
and

        if (vw_rx_enabled && !vw_tx_enabled)
         vw_pll();

mean that the receive path code is just not executed while the transmitter is enabled.

It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.

You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.


message:
Wire.h not found newliquidcrystal

The arduino IDE can't seem to find the wire.h file when i'm using the [new liquid crystal library][1]. Does anyone know how to solve this? here is the code i'm using and the error message:

    /*-----( Import needed libraries )-----*/
    #include <Wire.h>  // Comes with Arduino IDE
    #include <LiquidCrystal_I2C.h>

    /*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    /*-----( Declare Variables )-----*/ //NONE

    void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

      lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

    // ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
        lcd.backlight();
        delay(250);
        lcd.noBacklight();
        delay(250);   }   lcd.backlight(); // finish with backlight on

    //-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

    // Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

    }/*--(end setup )---*/

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
        // when characters arrive over the serial port...
        if (Serial.available()) {
          // wait a bit for the entire message to arrive
          delay(100);
          // clear the screen
          lcd.clear();
          // read all the available characters
          while (Serial.available() > 0) {
            // display each character to the LCD
            lcd.write(Serial.read());
          }
        }   }

    }/* --(end main loop )-- */

Here is the compiler output

> Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"
>
> C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\I2CIO.cpp:35:26:
> fatal error: ../Wire/Wire.h: No such file or directory
>
>  #include <../Wire/Wire.h>
>
>                           ^
>
> compilation terminated.
>
> exit status 1 Error compiling.
>
>   This report would have more information with   "Show verbose output
> during compilation"   enabled in File > Preferences.

[1]: https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

body:
The liquid crystal library has to be installed in the same folder as the wire library:

    libraries/Wire/Wire.h (etc)
    libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.


message:
Using a SPI based ADC (ADE7912) with Arduino

I'm trying to use Analog Devices' isolated ADC [ADE7912](http://www.analog.com/en/products/analog-to-digital-converters/integrated-special-purpose-converters/energy-metering-ics/ade7912.html#product-overview) to build a native product for voltage and current sensing, using an Arduino as a microcontroller. The IC communicates with the Arduino using SPI (and SCK frequencies of 8,4,2 and 1 MHz), and I have followed the datasheet and written down some basic code using SPI-transactions and all, which seems to be giving correct results when I apply a positive voltage to the inputs of the ADC. I have two problems here:

1. When I try to display the SCLK, MISO and MOSI signals on an oscilloscope, the clock seems to have trouble maintaining its value (it becomes erratic and hence the SPI communication also misses some values etc.) Why is this happening?

2. When I apply a negative voltage to the ADC inputs, the IC does not really show any response to that even though it clearly supports negative voltage inputs to the ADC, as mentioned in the datasheet. This might be an IC related problem, but I am not sure.

Also, is there anyone who has built a library for this IC? Would be greatly obliged if they could share it.

body:
I have not written a full library, but I have recently been using the ADE7913 (same as ADE7912 but with an extra voltage channel) with an Arduino MEGA.

The basic sketch located [here][1] talks to the ADE7913 over SPI, and then prints the results of the measurement registers over serial (so you can see them using a serial monitor).

I have not yet done much measurement testing, so can't comment on the negative voltage issue you have seen, but the sketch sets up the ADE7913 to use the V2WV register for monitoring temperature, and converts the result into degrees C, so you should be able to tell if its working properly.

In terms of the issues you have been having with the SPI comms, I can offer the following suggestions based on my troubleshooting experience (I also had glitchy comms initially):

1. I'm pretty new to SPI, but my interpretation of the data-sheet is that the ADE791X chips use `SPI_MODE3` (i.e. SCLK is normally high, and samples are read on the trailing clock edge). I have found `SPI_MODE1` also works, but unless others can correct me would suggest using 3.
2. I found having physically long jumper wires (my prototyping is still on a bread-board) caused issues. I have read elsewhere that at frequencies in the ones of MHz, distances less than tens of meters shouldn't be an issue; but I shortened / tidied my wiring and it seemed to help.
3. I would run everything at lowest possible speeds to troubleshoot, i.e. set the ADC sampling rate to 1kHz (set `CONFIG` bits `5:4` to `11`), and set the SCLK at 250kHz.
4. In the attached sketch, I am reading the register values based on an interrupt from the `CLKOUT\!DREADY` pin. You have to be careful that this reading routine takes less than one ADC sampling time to read all the registers. There is a good explanation of this timing constraint in Figure 8 of [this application note][2]. The attached sketch also reports some timing information over serial to help with this.

Hope that helps,

- Khalid.

  [1]: https://github.com/khalida/ade7913/blob/master/ADE7913_VI_sense_board.ino.ino
  [2]: http://www.analog.com/media/en/technical-documentation/application-notes/AN-1332.pdf


message:
Rc switch library transmit using protocol 5

I'm trying to transmit using mode 5 with the rc switch library, but my reciever tells me that the data is using protocol 2. I'm using the RecieveDemo_simple example as a sniffer for 433 MHz and I'm recieving data with protocol 5 from a wireless electric plug that I want to replicate.

I am able to send the data, but it is using the wrong protocol most of the time.

Here's some output from the reciever:

    Received 15766156 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 5
    Received 15885740 / 24bit Protocol: 2
    Received 15885740 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 5
    Received 15885740 / 24bit Protocol: 2
    Received 15885740 / 24bit Protocol: 2
    Received 15885740 / 24bit Protocol: 5

The code:

    /*
      Example for different sending methods

      https://github.com/sui77/rc-switch/

    */

    #include <RCSwitch.h>

    RCSwitch mySwitch = RCSwitch();

    void setup() {

      Serial.begin(9600);

      // Transmitter is connected to Arduino Pin #10
      mySwitch.enableTransmit(10);

      // Optional set pulse length.
      // mySwitch.setPulseLength(320);

      // Optional set protocol (default is 1, will work for most outlets)
      mySwitch.setProtocol(5);

      // Optional set number of transmission repetitions.
      // mySwitch.setRepeatTransmit(15);

    }

    void loop() {

      /* Same switch as above, but using decimal code */
      mySwitch.send(15885740, 24);
      delay(1000);
      mySwitch.send(15766156, 24);
      delay(1000);

    }

body:
I would expect your sending protocol 5 just fine.

But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.

This is the definition of the two protocols from the code:

    { 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
    { 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted.
The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses.
Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.


message:
Upload sketch via Bluetooth using HC-06 module

I'm dealing with an application in which I need to upload sketches remotely to an arduino UNO board. I successufully managed to upload sketches using an HC-06 bluetooth adapter. The only problem is that I am forced to manually press the reset button once the bluetooth link is established. Is there a way to automatically reset the arduino, in a software or hardware way,  so that it will be able to accept and install the incoming and sketch?
Would it be enough to activate a digital pin connected to the reset at the right timing prior the upload process starts?

body:
Here's a instructable on how to reset the arduino with software

[Instructables link][1]

  [1]: http://www.instructables.com/id/two-ways-to-reset-arduino-in-software/


body:
Use a BJT/FET.

For a NPN, connect RST to COLLECTOR, a digital pin in series with a 220 ohm (or whatever’s appropriate) resistor to BASE, and EMITTER to GND.

Just bring the digital pin HIGH to reset your arduino.


message:
Proximity sensor without proximity sensor; is my hand magic, my competency crap, or my arduino fried?

here is a very simple circuit, with a LED between pin 2 and ground, and a loose wire in pin 8.

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

Here is the sketch that was intended for use with a small 4-contact switch like these in every arduino starter kit :

    int yellowCIn = 8;
    int yellowCOut = 2;

    void setup() {
      pinMode(yellowCIn, INPUT);
      pinMode(yellowCOut, OUTPUT);
    }

    void loop() {
      if (digitalRead(yellowCIn) == HIGH) {
      digitalWrite(yellowCOut, HIGH);
      }
      else {
        digitalWrite(yellowCOut, LOW);
      }
    }

However, simply moving my hand near the loose white wire is enough to light the LED, moving it away to put it off. As I am writing this, with the arduino connected by usb, rather than on the blue battery visible in the picture, I notice moving my hands away from the keyboard lights the led, moving them close to the keyboard powers it off...

So back to my title : are my hands magic, my electronics competency crap (well, it is, for sure) enough that I never heard of such a tremendous static electricity effect (and never fried one of the many computers I built from parts), or does this board have dire problems?

Thanks for your attention :)

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

body:
Try configuring your input pin as INPUT_PULLUP instead. This connects an internal pullup resistor to stop the input value from drifting around.

I would only use the "INPUT" mode on its own if I have that pin wired to something on the board and the levels won't be erratic.

Your hands are magic - they pick up interference from various sources and the high impedance input of the chip pick this up...

(There's a bit more on the modes here: [Arduino DigitalPins page][1])

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


body:
Nothing's broken; you have discovered  the nature of a floating pin.  Unfortunately, that means that strange things happen...

A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set.  To fix this, you need to add a [pull-up or pull-down resistor][1] (or activate the internal [input-pullup resistor][2]).

You can read about how to accomplish this [here][3].

  [1]: http://playground.arduino.cc/CommonTopics/PullUpDownResistor
  [2]: https://www.arduino.cc/en/Reference/PinMode
  [3]: https://learn.sparkfun.com/tutorials/pull-up-resistors


message:
Print the response from GSM shield

I have a GSM shield connected with my Intel Galileo board.

I intend to connect the board with serial communication at a baud rate of 115200 instead of the GSM library. I want to print the results of "at" commands in my serial window, how should I do it?

body:
I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using.
It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.

    void setup()
    {
      Serial.begin(115200);
      int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
     }

     void loop()
    {
       if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
        }
    }


message:
Arduino micro lost connection after first programming

I have just programmed a new micro, loaded the basic blink code in it. After that neither my laptop, nor my desktop sees it anyway with the following usb error:

    Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
    [Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
    [Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
    [Fri Apr  1 14:32:03 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
    [Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
    [Fri Apr  1 14:32:03 2016] usb 1-2: USB disconnect, device number 8
    [Fri Apr  1 14:32:03 2016] usb 1-2: new full-speed USB device number 9 using ohci_hcd
    [Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62

If I push the reset button on it it comes back a bit then disappears again:

    22620.495256] usb 1-2: New USB device found, idVendor=2341, idProduct=0037
    [22620.495263] usb 1-2: New USB device strings: Mfr=2, Product=1, SerialNumber=0
    [22620.495268] usb 1-2: Product: Arduino Micro
    [22620.495272] usb 1-2: Manufacturer: Arduino LLC
    [22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
    [22627.966141] usb 1-2: USB disconnect, device number 32
    [22628.432089] usb 1-2: new full-speed USB device number 33 using ohci_hcd
    [22628.572111] usb 1-2: device descriptor read/64, error -62

Anybody experienced this? I have tried to reconnect it multiple times to both computers, even tried a new cable doesn't help.

body:
The USB part of the Atmega32U4 needs quite a bit of software to operate correctly, which is either not included in the basic blinky example or you got a binary for a different Arduino model.

The syslog looks like there is a bootloader present after Reset for a couple of seconds..

    [22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
         ^
    [22627.966141] usb 1-2: USB disconnect, device number 32
         ^
.. which shuts down and starts blinky. This is documented on the [ArduinoBoardMicro] page.

Re-flashing the chip is a bit tricky in this state, as you must press the reset button at the "right" time just before the software wants to access the chip.

[ArduinoBoardMicro]: https://www.arduino.cc/en/Main/ArduinoBoardMicro


body:
> If I push the reset button on it it comes back a bit then disappears again:

That's exactly how it works. The Micro enumerates as a Serial interface for a couple of seconds after reset, enough time for you to upload a new sketch. If you don't upload in time, and unless your code specifies a serial port, the serial interface goes away. Blink doesn't use a serial port.

You need to quickly press and release Reset at the exact moment that the IDE says it is uploading, and the board should then detect the new sketch.


message:
Using map for DC motor instead of servo

I am trying to use map command which is used to power servo 180 degrees as the potentiometer moves...

 in fact what i want to do is just when i adjust my potentiometer to zero; stop the dc motor then after turn the pot to 512 analog value turn the motor to the left (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);)and then stop when it reach 512 then when adjust the pot back to zero turn the dc motor to the right (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);) but the think is what i am trying to do is exactly what we can do with the servo motor in the knob http://www.arduino.cc/en/Tutorial/Knob

I'm using a normal DC motor and l293D IC but I want to control the DC as knob method like the 200 degrees.

**Code**

    #define E1 11    // Enable Pin for motor
    #define I1 10    // Control pin a for motor
    #define I2 9     // Control pin b for motor
    const int analogPin = A0;
    int analogValue ;

    void setup() {
      pinMode(E1, OUTPUT);
      pinMode(I1, OUTPUT);
      pinMode(I2, OUTPUT);

    }

    void loop() {

      int analogValue = analogRead(analogPin);

      if(analogValue > 0 && analogValue < 512)  {

      analogWrite(E1, 255);
      digitalWrite(I1, HIGH);
      digitalWrite(I2, LOW);
        delay(100);
    } else
      analogWrite(E1, 255);
      digitalWrite(I1, LOW);
      digitalWrite(I2, HIGH);
     }

body:
It looks like you want to use the "analogValue" to control the direction and speed of your DC motor.  If this is correct consider using this:

          //This method assumes: The center position of the pot is the motor's 0 speed point,
          //(because this is an ideal speed to actually reverse the motor's direction).
          //A PWM control range of 0-255, and the ADC input range of 0-1023.

          //First create a relative speed value from "analogValue",
          //with the pot mid point at 0 speed, and pot high/low points being full speed.

          int motorSpeed = 0;
          if (analogValue < 512 )
          {
           motorSpeed = map(analogValue, 0, 511, 255, 0);
          }  //Note that mapped range is reversed to give 0 speed at mid point.
          else
          {
           motorSpeed = map(analogValue, 512, 1023, 0, 255);
          }

          //then replace each analogWrite(E1, 255) with:
          analogWrite(E1, speedValue);

          //you should also change "  if (analogValue > 2 && analogValue < 500) {  " to:
          if (analogValue < 512) {


message:
Trinket works with USB but not with wall adapter

My [Adafruit 5V Trinket][1] works fine when powered via USB connected to my computer (and the power going in to the Trinket is 5V), but if I use a 9V wall adapter with a microUSB adapter, it just powers on but doesn't seem to actually run the program on the Trinket.

Am I _over_ powering the Trinket and sending too much voltage to everything? If that's the case, is there some way to decrease the voltage?

  [1]: https://learn.adafruit.com/introducing-trinket?view=all

body:
Yes, you are probably over-powering the trinket. The trinket expects 5V on the USB connector. However, it has an voltage regulator on board that can take up to 16V.

The BAT pin is connected to the voltage regulator and can take anywhere from 5.5V to 16V.


message:
Reading sensor data, massaging it and performing operation based on transformed data

This is the outline of my project:

 1. interpret environment data (sensor, motor, etc..).
 2. Modify this data into a more usable form,
 3. send it back to the same motor for further operation from modified data.

As an example (this is not the project, but just an example to make sure I am being clear).

A motor moves a conveyor belt with various size flasks on it, some large other small. Depending on the reading of the position of the motor (from encoder) another process (filling the flasks) will take place.  If the first motor encoder data indicated the flask was small then the amount of liquid poured will be small. If large, the amount of liquid dispensed will be large.

More generally, read the location of an item based on motor encoder feedback.  Modify this data. Send this modified data back to a different motor so that it does something specifically as a function of the first motor encoder data.

I am able to send the original encoder feedback to a file, manually massage it and paste it into an Arduino script, compile and have everything work great. I just want to remove the manual steps (cut & paste) and data massaging (I'm looking to an Arduino program to do that).

To further complicate things, I want this process to be part of a distributable package that does not require further compiling. Reading from a sim card is fine.  Also, I am not too price sensitive as the Arduino is a small portion of the total cost of the final product.

I hope someone can give me some insight or pathway to a solution.
All the very best, John.

body:
Here's a back-of-envelope sketch, off the top of my head:

Conveyor belt driven by stepper motor, controlled by the Arduino.  Each step is a known distance.

Bottles are either of exactly two heights, at random.  Two [beam break sensors][1], one to determine where a bottle starts and one to determine whether it's tall or short.

Some sort of valve to control the water flow - I presume you have some idea how this can be controlled.  I don't, but washing machines have electrically-controlled valves so something broadly along those lines.  Controllable on/off by the Arduino.

Software on the Arduino steps the motor until it sees the start of a bottle (first beam broken).  Then uses second beam to determine whether the bottle is large or small.

Arduino switches on the water valve (outlet positioned exactly right to be above the bottle) for either 2s or 4s accoriding to bottle size, then off again.   (Water pressure and flow rate regulated independently, perhaps fed from a header tank).

Arduino steps motor more until it sees another bottle.

----------

No string concatenation in there, nor sorting of lists or need for a Raspberry Pi.  It's not clear to me why you'd need those things for the application described.

I'm not aware that you can program the Arduino in Python unfortunately.  Someone may know better.  C isn't hard though - get an Arduino and some LEDs or whatever, go through some tutorials, you'll get the hang of it.

  [1]: https://learn.adafruit.com/ir-breakbeam-sensors/overview


message:
How do I connect an 8x8 LED RGB matrix to an Uno?

I have [this 8x8 LED RGB matrix][1]. How do I get it connected to an Arduino Uno?

It came with no other wires/modules/connectors and has a veritable crap-ton of pins to connect.

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

  [1]: http://www.amazon.com/Geeetech-LED-Matrix-8x8-Display/dp/B007ZK4I10
  [2]: https://i.stack.imgur.com/a0aRi.jpg

body:
Because you have, unfortunately, decided to buy a product without a datasheet (and the product description can't even decide if it's common anode or common cathode!), you'll have to find a product which is similar that _has_ a datasheet, and determine by experimentation if the pinout matches.

For instance, [this Sparkfun LED matrix](https://www.sparkfun.com/products/retired/683) looks similar. Take a look at the datasheet for an internal schematic and manually verify the pinout.

Once you know the pinout, you can begin to figure out how to drive it. There are many ways to drive large numbers of LEDs, one of the simplest of which is a bunch of shift registers.

Getting yourself a couple of 595 SRs and playing with the matrix (hint: try and get a single colour working first, then add the others) would be a good place to start.

Alternatively, the display description says that it is compatible with "Arduino RGB LED Matrix Driver Shield". That may or may not be true, but looking at a schematic of that board would give you insight into how to drive the matrix. I believe that board uses a DM163 8x3 CC LED driver chip, which seems to be perfectly suited to drive the matrix, but buying and wiring that chip up may be non-trivial.


body: The idea is to use a shift register PMIC (power management ic), such as the MAX6971; you'll need a pair of them; each has 16 bits of output; if you want to really shave off a dollar, get four TPIC6C596.