body:
I have an Arduino Uno connected to a NodeMCU ESP01 module, communicating via serial pins. The NodeMCU is powered from the Arduino's 3.3V pin. My idea is that the ESP01 receives MQTT messages, sends them to the Arduino via serial and wait for the Arduino to reply and then publish MQTT messages back.

If I power the Arduino from my computer's USB, everything works fine.

If I use an external power supply 12V/1A, the ESP01 can publish and receive "standard" MQTT messages (meaning, it does not send messages to the Arduino and does not expect a reply). It just receives and directly replies (no Arduino involved).

The problem occurs if the ESP needs to query the Arduino for a result.

The Arduino is able to read and write (I see the correct text in the console) to the serial port, but the NodeMCU ESP01 has problems publishing MQTT messages. Sometimes it does not publish anything (the ESP probably is unable to read what Arduino sends over serial), sometimes it publishes destroyed characters (random text).

It looks like the current needed by the ESP module is not high enough, but it does not make sense for me, since the external power supply should be able to provide more current than USB. Any ideas?

This is my schematic:

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

**Code:**

In my ESP01 I have the following MQTT `onMessage` listener, If the topic is a query for the Arduino (topic is validated by the `handleQuery` function), then the topic is sent by UART to the Arduino, which listens for specific strings in the `loop` function. When the Arduino receives a string, it does some logic and writes a reply back to the ESP via UART (`Serial.print()`).

After the ESP sends a message to the Arduino, it sets listeners for strings, that end with character %. If the reply from the Arduino is received, then it publishes an MQTT message with the result.

    function onMessage(client, topic, message)
        if handleQuery(topic.."+"..message) then
            uart.write(0,topic.."+"..message)

            uart.on("data","%", function(data)
                if data=="quit%" then
                    uart.on("data") -- unregister event
                end

                if data ~= "quit%" then
                    client:publish(topic.."/response","REPLY:"..data,0,0)
                end
            end,0)
        else
            client:publish(topic.."/response","REPLY: Invalid query",0,0)
        end
    end

The reply from the Arduino has the following message format:

     REPLY:<value>%
     quit%

This solution works if the Arduino is connected to my desktop computer's USB. It does not work if it is powered from an external power supply. It seems like the ESP is not able to read what the Arduino wrote to UART with `Serial.println()` if powered from an external power source.

I have no idea why, because power supply should be able to deliver more current.

**Edit:**

I use the following Arduino clone: [eBay link][2]

  [1]: https://i.stack.imgur.com/8kVLV.jpg
  [2]: http://www.ebay.com/itm/SainSmart-UNO-R3-Board-ATmega328P-ATmega16U2-Free-USB-Cable-For-Arduino-/300948763268?hash=item4611f1b284:g:HygAAOSwB4NWxX3K

I tried to connect the ESP01 to the Arduino's 5V output with a voltage regulator (5V should deliver more current), and again, if the USB is connected, the ESP reads UART messages with no problem. If the Arduino is powered from an external power source, the ESP reads damaged characters. The only difference is that those damaged characters seems to be always the same. So perhaps some coding problems(?) or something like that.

So far it looks like a low current value is not a problem.

**Edit 2**

I removed from my code `print()` statement from the ESP/LUA code that I used for "debbuging". It printed to serial some messages for me. It seems that it cleaned traffic on Serial line a little bit.

Now I get most of the time correct characters, but the first character is missing, so instead of:

LOW% I get OW%

HIGH% I get IGH%

29.53% I get 9.53%

And from time to time I get String =]�quit%.

Perhaps some input buffer has a problem(?).

title: ESP01 connected to Arduino can't read from UART while connected from external power source

Answers: 2

body:
Can I just check when you plug your 3.3V ESP into a 12V power supply it stops working?  Is there a burning smell when you do this?  Are you using anything to drop the voltage to 3.3V?

You also say you are connecting the ESP to the Arduino's 5V supply.  Normally that's not a good idea either.

Also have you tied the ground of the Arduino to the ESP/12V PSU?  If the two devices don't share a common ground then they won't agree what 0V and so won't be able to talk to each other over serial.  Just run a wire from the Gnd on the Arduino to the Gnd on the ESP and they will jump into life.

body:
Use a proper level shifter on the RX and TX lines. You probably are marginal as far as signal level.

The problem is not the voltage into the ESP8266. It is the level out of the TX of the ESP8266 not being high enough for the Uno CPU. This marginal voltage can cause messed up characters. Often we can get away with it at this level but it is really a marginal situation. It is not a reliable thing to do.

Specification for Vin high is 0.7xVcc. 0.7 x 5.0v = 3.5 volts !!!!

Using a 3.3 volt level signal will often work into 5 volt logic but not always. I had learned this the hard way. I designed a medium run product that used a 3.3v derived TX signal into the 5 volt logic RX input. Worked fine in 30 prototypes. But about 20% failures when running a production order. Different batch of chips resulted in different high trip point.

Just because the practice of using 3.3volt logic into 5 volt CPUs is common it is NOT guaranteed to work. Read the spec sheet! Do the math.


body:
I have a problem with these two modules. I am trying to create a pulse sensor but also want to use a remote for some further functionality (menu system).
I have the code separated into two files, one for the main menu and the other for the pulse sensor. They work as expected individually but when i combine the code it only displays the pulse readings and doesnt allow me to use the main menu functionality.

    ISR(TIMER2_COMPA_vect) {                        // triggered when Timer2 counts to 124
      cli();                                      // disable interrupts while we do this
      Signal = analogRead(pulsePin);              // read the Pulse Sensor
      sampleCounter += 2;                         // keep track of the time in mS with this variable
      int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

      //  find the peak and trough of the pulse wave
      if (Signal < thresh && N > (IBI / 5) * 3) { // avoid dichrotic noise by waiting 3/5 of last IBI
        if (Signal < T) {                       // T is the trough
          T = Signal;                         // keep track of lowest point in pulse wave
        }
      }

      if (Signal > thresh && Signal > P) {        // thresh condition helps avoid noise
        P = Signal;                             // P is the peak
      }                                        // keep track of highest point in pulse wave

      //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
      // signal surges up in value every time there is a pulse
      if (N > 250) {                                  // avoid high frequency noise
        if ( (Signal > thresh) && (Pulse == false) && (N > (IBI / 5) * 3) ) {
          Pulse = true;                               // set the Pulse flag when we think there is a pulse
          IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
          lastBeatTime = sampleCounter;               // keep track of time for next pulse

          if (secondBeat) {                      // if this is the second beat, if secondBeat == TRUE
            secondBeat = false;                  // clear secondBeat flag
            for (int i = 0; i <= 9; i++) {       // seed the running total to get a realisitic BPM at startup
              rate[i] = IBI;
            }
          }

          if (firstBeat) {                       // if it's the first time we found a beat, if firstBeat == TRUE
            firstBeat = false;                   // clear firstBeat flag
            secondBeat = true;                   // set the second beat flag
            sei();                               // enable interrupts again
            return;                              // IBI value is unreliable so discard it
          }

          // keep a running total of the last 10 IBI values
          word runningTotal = 0;                  // clear the runningTotal variable

          for (int i = 0; i <= 8; i++) {          // shift data in the rate array
            rate[i] = rate[i + 1];                // and drop the oldest IBI value
            runningTotal += rate[i];              // add up the 9 oldest IBI values
          }

          rate[9] = IBI;                          // add the latest IBI to the rate array
          runningTotal += rate[9];                // add the latest IBI to runningTotal
          runningTotal /= 10;                     // average the last 10 IBI values
          BPM = 60000 / runningTotal;             // how many beats can fit into a minute? that's BPM!
          QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
        }
      }

      if (Signal < thresh && Pulse == true) {  // when the values are going down, the beat is over
        Pulse = false;                         // reset the Pulse flag so we can do it again
        amp = P - T;                           // get amplitude of the pulse wave
        thresh = amp / 2 + T;                  // set thresh at 50% of the amplitude
        P = thresh;                            // reset these for next time
        T = thresh;
      }

      if (N > 2500) {                          // if 2.5 seconds go by without a beat
        thresh = 512;                          // set thresh default
        P = 512;                               // set P default
        T = 512;                               // set T default
        lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
        firstBeat = true;                      // set these to avoid noise
        secondBeat = false;                    // when we get the heartbeat back
      }
      Temp = Thermistor(analogRead(tempPin));
      Sweat = analogRead(moisture);

      sei();                                   // enable interrupts when youre done!
    }

I think the problem is with the actual header file. When the IRemote is initialised, it calls sei() which then turns on the global interrupts.

Is there a way to solve this issue? I was thinking about something along the lines of each interrupt should be unique and shouldnt be dependent on the other, and is there a way to tell the compiler about a hierarchy of interrupts.

Thanks in advance.

title: IRemote with PulseSensor

Answers: 1

body:
1. ISR should be as short as possible. Set flag and let the main program to handle it.
2. Global interrupt flag is handled automatically (on AVR platform), so you don't have to call `cli()`.
3. Enabling interrupts in ISR handler might cause more problem than you can even imagine. Usual one is stack overflow caused by going deeper and deeper by another ISRs (or the same one, if it's longer than ISR period).


body:
I have the following SD card reader on the left side from Sparkfun. In the tutorial they have it connected directly into an Arduino Mini, which has BLK and GRN pins> I would like to connect it to an Arduino UNO. Where do I connect these pins or can I ignore them? Thanks for your help.

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

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

title: Where to connect BLK and GRN pins of Openlog board on my Uno?

Answers: 2

body:
It quite simple and stupid that they named the pins with those name. You simply connect:

BLK > ground

GRN > RESET

The weird pin abreviations can cause quite a bit of confusion.

**Extra** [links][1] for help.

  [1]: http://shallowsky.com/blog/hardware/pro-mini-to-ftdi-friend.html

body:
If you read the [page about the OpenLog board](https://learn.sparkfun.com/tutorials/openlog-hookup-guide) you can see (on the schematic link) what the pins mean:

[![OpenLog pins][1]][1]

I've added the labelling on the board in blue.  The GRN pin (DTR in the schematic) is actually an input, which resets the chip:

[![OpenLog reset][2]][2]

Thus:

* `GRN` should be connected to RESET on your Uno, so that when you reset the Uno, you rest the OpenLog.

* `TXO` (transmit out) on the OpenLog would be connected to serial input on the Uno (ie. digital pin D0 - labelled RX).

* `RXI` (receive input) on the OpenLog would be connected to serial output on the Uno (ie. digital pin D1 - labelled TX).

* You can see that `GND` and `BLK` are both ground pins, and thus should be connected to ground.

* `VCC` (RAW on their schematic) is the voltage input to the 3.3V very-low-dropout voltage regulator MIC5205 on the OpenLog. This will accept input voltages in the range 3.3V to 12V. (The datasheet seems to suggest a maximum of 16V, but it might get rather hot if you did that). Connecting VCC to +5V on the Uno would be satisfactory.

  [1]: https://i.stack.imgur.com/elNvb.png
  [2]: https://i.stack.imgur.com/Ec00k.png


body:
I'm making a soccer car with arduino. And I have this undocumented motor control shield. So I don't know how to program it. I've tried to code it as if it be an H bridge, but is not working. Someone know which are the pins that I have to use?
The plate is from DK Electronics, and says motor control shield for arduino.

Don't know why but the image can't be upload from my phone.

As I can't show more this way I have published on my Twitter account the image, if you can I'll be grateful.
Link: https://twitter.com/ricardovaras_99/status/789249497322889216

This is the code I used guided by some internet articles about the Arduino's original motors control shield.

     pinMode(8,OUTPUT);       //Channel A Brake Pin Initialize
     pinMode(9,OUTPUT);       //Channel B Brake Pin Initialize
     pinMode(12,OUTPUT);      //Channel A Direction Pin Initialize
     pinMode(13,OUTPUT);      //Channel B Direction Pin Initialize

title: Arduino motor shield

Answers: 1

body:
Judging by the fact that you agree it looks like [this](http://www.oddwires.com/motor-shield-for-arduino/), a search reveals it is a knock-off of the [Adafruit V1 motor shield](https://learn.adafruit.com/adafruit-motor-shield/overview).

Their page shows how to connect to it, and has example code and a library.

I don't really want to post a link-only answer, but the alternative would be to parrot the Adafruit page, which isn't really fair to them because this board wasn't even purchased from them.


body:
Is it possible to get GPS data without using a GPS, but instead using the internet provided from a 3G or 4G connection to get GPS data?

Maybe if you used the HTML5 geolocation API somehow?

I have already used a GPS module together with a GSM modem, but i only used the GSM modem for SMS and not potential internet capabilities.

The beneftis from this , besides cost, would be a smaller program, intended for arduino nano, as TInyGPS and TinyGPS++ libraries are already big enough.

So my question really is twofold:
1. Is there any way to utilize the internet connection from GSM modems (besides the obvious SMS/call function)?
2. Is there a way to utilize the internet connection to get GPS data, without using an actual GPS module?

title: Utilizing 3G/4G connection as gps

Answers: 1

body:
You cannot get GPS data without getting GPS data. That's like wanting to get milk from a cow without using a cow.

Some GSM modem modules also include a GPS chip. If yours does you can use that. If not then the closest you can get is:

* Country (or maybe city) the IP address is registered in
* Cell ID and location of the tower you are communicating with

Both of those are only very rough "somewhere within this square few miles" or "somewhere in this country" kind of data. Any more than that and you need GPS.

Mobile phones augment the GPS / Cell data with WiFi data by matching BSSIDs with an online database (within Google etc) to get rough location information.


body:
I have a very simple circuit, but my program is some what complicated.

Here is the circuit diagram:

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

Here is the code:

    /*
      01 - GND -------- GND
      02 - +5V -------- 5V
      03 - V0  -------- Potentiometer Middle
      04 - Reset ------ 9
      05 - Read/Write - GND
      06 - Enable ----- 8
      07 - Data0 ------ NC
      08 - Data1 ------ NC
      09 - Data2 ------ NC
      10 - Data3 ------ NC
      11 - Data4 ------ 10
      12 - Data5 ------ 11
      13 - Data6 ------ 12
      14 - Data7 ------ 13
      15 - +LCD ------- 5V
      16 - -LCD ------- GND
    */

    //include LCD library
    #include <LiquidCrystal.h>

    //Initialize an LCD object
    /*Pins should be mentioned in this order:
      Reset
      Enable
      Data4
      Data5
      Data6
      Data7
    */
    LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
    int onTimePin = A0;
    int onTime = 0;
    int offTimePin = A1;
    int offTime = 0;
    int ledPin = 13;

    void setup()
    {

      pinMode(onTimePin, INPUT);
      pinMode(offTimePin, INPUT);

      pinMode(ledPin, OUTPUT);

      //Begin the LCD interface
      lcd.begin(16, 2);

      lcd.print("ON  TIME : ");
      lcd.setCursor(0, 2);
      lcd.print("OFF TIME : ");

    }

    void loop()
    {
      onTime = map(analogRead(onTimePin), 0, 1023, 1, 3);
      lcd.setCursor(11, 0);
      lcd.print(onTime);

      offTime = map(analogRead(offTimePin), 0, 1023, 1, 9);
      lcd.setCursor(11, 1);
      lcd.print(offTime);

      digitalWrite(ledPin, HIGH);
      delay(onTime * 1000);

      digitalWrite(ledPin, LOW);
      delay(offTime * 1000);
    }

The above code works. But there is a small problem:

When I turn the potentiometer wiper, there is a delay.

It's obvious because when the loop completes, the changed value of potentiometer is displayed. So, I decided to do the same thing using interrupts. But only digital pins have interrupts.

I would like to know the solution for using interrupts on analog input.

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

title: Use interrupts with analog pins in arduino or another possible solution?

Answers: 2

body:
[Avoid `delay`](http://playground.arduino.cc/Code/AvoidDelay).

Very simplistic alternative:

    unsigned long lastLedToggleTime;
    unsigned long currentLedToggleInterval;

    void loop() {
      ...

      unsigned long now = millis();

      if ( (now - lastLedToggleTime) > currentLedToggleInterval) {
        lastLedToggleTime = now;
        // We need to toggle the LED now.
        if ( digitalRead( ledPin ) == LOW ) {
          // LED was LOW, so we set it HIGH and setup next toggling after onTime.
          digitalWrite(ledPin, HIGH);
          currentLedToggleInterval = (onTime * 1000);
        } else {
          // LED was HIGH, so we set it LOW and setup next toggling after offTime.
          digitalWrite(ledPin, LOW);
          currentLedToggleInterval = (offTime * 1000);
        }
      }
      ...
    }

Notice that we're dealing with 32 bit *unsigned* integer values here, which is why this code will work even if/when `millis()` rolls over to 0. Specifically, not only will `now - lastLedToggleTime` always return a positive value (because it is cast into the unsigned data type), it will also return the *correct* value due to two's complement representation and modulo arithmetic base 2^32.

Example: Let's just look at an 8 bit value for simplicity:

Say, `lastLedToggleTime` was at the last tick of the 8 bit timer value, i.e. `lastLedToggleTime == 255`. In the next timer tick, `now` will overflow to `0`, so next we have `now` - `lastLedToggleTime` = 0 - 255 = -255. In [two's complement](https://en.wikipedia.org/wiki/Two's_complement), this value would need (at least) 9 bits to represent (binary: `1 0000 0001`), but because we only have 8 bits of storage, the sign bit (MSB) is just discarded resulting in `0000 0001` binary = 1. We can see that 1 is the correct value for the number of ticks to get from 255 to 0; it's exactly one tick.

body:
You are looking for the bad solution for a simple problem. As Ignacio
Vazquez-Abrams puts it, the problem is you using `delay()`. The simplest
solution is to manage the timings with `millis()`. See the [Blink
Without Delay Arduino
tutorial](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay).


body:
I noticed there are two Gnd pins at the lower pin strip, and another on the upper strip.
Is there a difference in their purpose?

title: Gnd pins at the power pin strip VS Gnd pin at the IO pin strip

Answers: 1

body:
**In short, all the UNO ground pins are the same.**

They are just there to make your life easier. At the end of the day, GND is GND. There is no technichal difference. Just note that is is sometimes better if you share the 3 GND ports. Overloading a port might damage it. Check the [datasheet][1] for current limitations of the pins.

---

**EDIT**

The pins (literal pins of the IC) themselves are also different on the ATmega IC.

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


body: I am looking to modify the receiving hardware serial buffer size for the Arduino Mega. To do so I need to redefine it in `HardwareSerial.h` in the core code. However, I can't seem to find a copy of the Arduino Mega core code. A search for `HardwareSerial.h` on my computer returns no results. I am using Windows 10.

title: Where can I find the Arduino Mega core code?

Answers: 1

body:
Arduino Mega is part of the Arduino AVR Boards core. The location of that core depends on whether you are using the core version included with the Arduino IDE or have updated the core version using Boards Manager(in which case there will be multiple copies of the core installed on your computer but only the updated version will be used). The easiest way to find it is:

1.  Tools > Board > Arduino/Genuino Mega or Mega 2560
2.  File > Examples > EEPROM > eeprom_clear
3.  Sketch > Show Sketch Folder
4.  Move up folder levels until you reach the `avr` folder.
5.  If there is a version number folder in the `avr` folder then open that folder.
6.  HardwareSerial.h and the rest of the core files are located in `cores/arduino`.

Remember that you will need to redo any changes to the core after any Arduino IDE and/or Arduino AVR Boards updates.


body:
I want to make a stepper motor increase and decrease speed working with a HCSR04 sensor. The idea is that if the sensors detects an object the stepper motor is going to decrease, and stop as close as possile to the object.

I have made some code, and it is sorta working..

**My current code looks like this:**

    if (distance > 30)
    {
      digitalWrite(13,HIGH); // Output high
      delayMicroseconds(500); // Wait
      digitalWrite(13,LOW); // Output low
      delayMicroseconds(500); // Wait
    }

    if (distance > 20 && distance < 30)
    {
      digitalWrite(13,HIGH); // Output high
      delayMicroseconds(2000); // Wait
      digitalWrite(13,LOW); // Output low
      delayMicroseconds(2000); // Wait
    }

    if (distance > 10 && distance < 20)
    {
      digitalWrite(13,HIGH); // Output high
      delayMicroseconds(10000); // Wait
      digitalWrite(13,LOW); // Output low
      delayMicroseconds(10000); // Wait
    }

    if (distance > 1 && distance < 10)
    {
      //digitalWrite(13,HIGH); // Output high
      //delayMicroseconds(1000); // Wait
      digitalWrite(13,LOW); // Output low
    }

**But I thought it could be easier, So I made a function:**

    void velocity()
    {
     digitalWrite(13,HIGH); // Output high
     delayMicroseconds(500); // Wait
     digitalWrite(13,LOW); // Output low
     delayMicroseconds(500); // Wait
    }

Now my question is: Can I manipulate the delayMicroseconds to change if the distance changes? Is there a formula to do so?

**Entire code:**

    int trigPin = 11;
    int echoPin = 10;

    void setup()
    {
    pinMode(trigPin, OUTPUT); //Sensor
    pinMode(echoPin, INPUT); //Sensor
    pinMode(6,OUTPUT); // Enable
    pinMode(13,OUTPUT); // Step
    pinMode(12,OUTPUT); // Dir
    digitalWrite(6,LOW); // Set Enable low
    digitalWrite(5,LOW); // Set Step low
    Serial.begin(9600);
    }

    void loop()
    {
    //rotateleft();
    //Serial.println("ik draai nu exact een rotatie linksom");
    //delay(1000);
    //rotateright();
    //Serial.println("ik draai nu exact een rotatie rechtsom");
    //delay(1000);
    //velocity();

     //sensor
     long duration, distance;
     digitalWrite(trigPin, LOW);
     delayMicroseconds(2);
     digitalWrite(trigPin, HIGH);
     delayMicroseconds(5);
     digitalWrite(trigPin, LOW);
     duration = pulseIn(echoPin, HIGH);
     distance = (duration/2) / 29.1;
     Serial.print ("cm ");
     Serial.print (distance);

    //eigen creatie

    if (distance > 30)
    {
      digitalWrite(13,HIGH); // Output high
      delayMicroseconds(500); // Wait
      digitalWrite(13,LOW); // Output low
      delayMicroseconds(500); // Wait
    }

    if (distance > 20 && distance < 30)
    {
      digitalWrite(13,HIGH); // Output high
      delayMicroseconds(2000); // Wait
      digitalWrite(13,LOW); // Output low
      delayMicroseconds(2000); // Wait
    }

    if (distance > 10 && distance < 20)
    {
      digitalWrite(13,HIGH); // Output high
      delayMicroseconds(10000); // Wait
      digitalWrite(13,LOW); // Output low
      delayMicroseconds(10000); // Wait
    }

    if (distance > 1 && distance < 10)
    {
      //digitalWrite(13,HIGH); // Output high
      //delayMicroseconds(1000); // Wait
      digitalWrite(13,LOW); // Output low
    }

    //Own functions
    }

    void velocity()
    {
     digitalWrite(13,HIGH); // Output high
     delayMicroseconds(500); // Wait
     digitalWrite(13,LOW); // Output low
     delayMicroseconds(500); // Wait
    }

    void rotateleft()
    {
     digitalWrite(12,HIGH); // Set Dir high
     for(int x = 0; x < 200; x++) // Loop 200 times
      {
        digitalWrite(13,HIGH); // Output high
        delayMicroseconds(1000); // Wait
        digitalWrite(13,LOW); // Output low
        delayMicroseconds(1000); // Wait
       }
      }
      void rotateright()
      {
       digitalWrite(12,LOW); // Set Dir high
       for(int x = 0; x < 200; x++) // Loop 200 times
       {
         digitalWrite(13,HIGH); // Output high
         delayMicroseconds(1000); // Wait
         digitalWrite(13,LOW); // Output low
         delayMicroseconds(1000); // Wait
       }
     }

title: Stepper motor with HCSR-04 sensor

Answers: 1

body:
Assuming you have a distance variable containing the distance measured from your sonar sensor in cm. You can use that value to adjust the delay times in between your steps.

**EDIT** Modified code to increase speed when distance increases

    int time = 0;
    int timeWait = 1000; //interval in milliseconds between each distance reading
    int maxDelay = 1000;

    void velocity(int speed){
       int trim = 10;
       digitalWrite(13,HIGH); // Output high
       delayMicroseconds(maxDelay - speed*trim); // Wait
       digitalWrite(13,LOW); // Output low
       delayMicroseconds(maxDelay - speed*trim); // Wait
    }

    int readDistance(){
     //code to read distance
     return distance;
    }

    void setup(){
    time = millis();
    }

    void loop(){
       if(millis()-time > timeWait){ //only read distance if 1000ms has elapsed since the last reading
         time = millis();
         int distance = readDistance(); //your distance reading code;

       }
       velocity(distance);
    }`

**EDIT 2**

You'll also need something to handle upper and lower limits for delays (i.e. you don't want delayMicroseconds(0) or any negative numbers and  you don't want to include extraneous distance readings)


body: Am wondering if there is some way the Arduino can automatically power itself using through the 9v port in case the USB is disconnected, and afterwards if the USB is connected again it stop feeding from the 9v Input.

title: Power Arduino Over 9V automatically after being disconnected from USB 5V

Answers: 2

body:
The anwser is somewhat.

If you connect a 9V battery to Vin, I'll "take over" the power wheter if the USB is connected or not. Note tought that some problems may occur when both are connected at the same time (personnal opinion). See this [link][1] for more info.

**So in conclusion, if you have a USB, remove the 9V for power efficiency. Once you include the 9V though, it will take over control of the power on the ARDUINO.**

  [1]: http://www.open-electronics.org/the-power-of-arduino-this-unknown/

body:
there is one way you can make it.
you can use a temporary capacitor(with a voltage output near to 9v)(or a lipo battery) connected to arduino's voltage input pin and 9v battery connected to arduino with a transistor.
whatever program you are uploading to arduino, you can add a code that reads the serial port, and if serial port is not available then it opens the transistor's gate so as the capacitor gets discharged very quickly the 9v battery takes the job.when it gets the serial port again it closes the transistor's gate and arduino stops feeding upon battery and takes power from USB port.


body:
I have a unidirectional communication from NodeMCU (ESP8266) -> Arduino UNO. The communication works when I power both the devices to my computer. Note that since it is from NodeMCU to Arduino only, I don't use a voltage regulator. However, when I use a battery supply 9V and connect to DC jack or 9V battery, the serial communication doesn't work. I tried even with the voltage regulator.

It is mentioned that I use something between 9V-12V in the spec. Is it not working because 3.3V/5v from NodeMCU is not sufficient? How do I fix this problem?

 1. Currently for the voltage regulator "high", I am supplying 5V from
    Arduino. Should I provide another supply to pass 9v?

 2. Does it power on if I provide 5V to DC jack or Vin?

title: Serial communication between NodeMCU and Arduino doesn't work when I try to use the DC jack or Vin

Answers: 1

body:
9V "transistor" (PP3) batteries are very weak. They barely provide enough current to power the Arduino, let alone a power hungry device like an ESP8266.

You're basically trying to tow a caravan with a skateboard.


body:
Is there a way to set an Arduino pin as being both an input, and an output?

I was looking at tristates, I'm not sure if that is related, or if there is some other method.

Perhaps I can try switching states rapidly. on one pin. I'm just not familiar with how to do it, and I don't see anything about it on the Arduino site.

This is a function of other microcontrollers, such as PICs, but I'm not sure about AVRs and Arduino types.

title: Single pin as input and output

Answers: 2

body:
The source code for the [1-Wire][1] protocol is a great place to start when learning how to use a single pin for both input and output.

See also chap. 18. I/O-Ports in the ATmega328p [datasheet][2].

Cheers!

  [1]: http://playground.arduino.cc/Learning/OneWire
  [2]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf

body:
A tri-state pin is not both an input and an output, rather each pin can be in 1 of 3 states (High, Low, High Impedance). These are typically used on a bus, where many similar devices are connected.

AFAIK the Arduino does not support tri-state, but it is possible to implement a bus. This was done by using open collector/drain devices with a resistor pull-up.

This was a common method of implementing computer busses (more than 40 years ago with RTL logic), but suffers from slow speed, and low fan-out, due to capacitance.

It is still used for low speed short busses such as I²C and 1-wire.

In practice all devices are set as Input. When a device wants to communicate it is configured as Output.


body:
I was modifying [this][1] ADC Touch implementation, namely switching *analogRead* and *pinMode* to what I thought would be port manipulation equivalents.

 I get very different readings (better and more stable in my case).

So, what I think is equivalent is actually quite different. Can someone point the differences to me?

Original:

  pinMode(ADCChannel, INPUT_PULLUP);

  ADMUX |=   0b11111;
  ADCSRA |= (1<<ADSC); //start conversion
  while(!(ADCSRA & (1<<ADIF))); //wait for conversion to finish
  ADCSRA |= (1<<ADIF); //reset the flag

  pinMode(ADCChannel, INPUT);
  _value += analogRead(ADCChannel);

Modified:

  DDRC &= ~(1 << ADCChannel);
  PORTC |= (1 << ADCChannel);

  ADMUX |=   0b11111;
  ADCSRA |= (1<<ADSC); //start conversion
  while(!(ADCSRA & (1<<ADIF))); //wait for conversion to finish
  ADCSRA |= (1<<ADIF); //reset the flag

  DDRC &= ~(1 << ADCChannel);
  _value += analogRead(ADCChannel);

  [1]: https://github.com/martin2250/ADCTouch

title: ADC port manipulation

Answers: 1

body:
Your modified code doesn't disable the pullup on the pin.

    PORTC &= ~_BV(ADCChannel);


body:
   I hope this question isn't overly broad although it is more of a search for consolidated information.

BACKGROUND:

   I am new to the Arduino universe and am drawn in by the open hardware concept. After years of doing electronics projects with PICs, I have tired of iterative hardware prototyping and DIY printed circuit construction for small one-off projects. The lure of buying off-the-shelf hardware and doing minimal wiring on protoboards / shields is a powerful concept that I welcome.

The availability of the hardware from multiple sources (and it seems multiple designers) does present a small problem I have discovered. There appear to be small but important differences between Arduino boards from multiple sources.

As an example, I have found that the hardware PWM isn't always the same from one Arduino Board design to another. I find that the arduino.cc pages (including the Forums) appear to indicate that hardware PWM runs at about 487 Hz. However, my testing shows that on the Arduino 101, two of the four hardware PWM outputs run at 487 Hz while the other two run at 975 Hz. I did not find such details when researching board choices and comparisons. I am assuming that this difference may also exist on other board designs although I have only Uno, 101, and Mega2560 boards to play with at the moment.

A second example is that for at least the Arduino Uno and Arduino 101 board I have, the DC power input jack is 5.5mm/2.1mm, a very common size. However, the Arduino Mega2560 I have (third party) uses a 5.5mm/2.5mm DC input jack -- a standard albeit less common size.

Another difference is the well known differences in (TTL) RS232 port interface chips used. At least these are generally made known and documented so that you can plan in advance for differences that may or may not affect you.

Finally, I have found that on the Arduino 101, plugging in or unplugging (or turning on or off) DC power at the DC input jack (or Vin pin) forces a reboot of the Curie module on the board. I think this is caused by the use of the power management chip and power switching circuitry on the board. The Mega2560 does not show this reboot behavior whenever DC power is changed. (This reboot happens even if the USB source remains connected at all times.)

These sorts of minor differences can affect the choice of board one makes for a given project -- especially, if you develop an application on one board and plan to deploy it on another. (Example: develop on a Mega2560 yet intend on deploying on a Uno later to save cost.)

QUESTIONS:

1) Has anyone come across a Website / page that details many of the minor design differences between Arduino boards?
[Edit] I should have used the word _designs_ rather than boards in this question. I realize each vendor may have tweaks to a board but was more interested in detailed differences in the "official" design. Things like above would be interesting to know -- does the board reboot on application of DC input power? Are all PWMs running at the same default frequency, etc?

2) Are there any Web resources that might at least list other "oddities" with the different board choices? (i.e. PWMs at frequencies other than 487 Hz)?

Any pointers would be much appreciated.

title: Pointer to Hardware Differences Documentation For Arduino Boards?

Answers: 1

body:
You may find this helpful: [PTD0001 Arduino Comparison Rev 0](http://www.paynetech.co.uk/docs/PTD0001 Arduino Comparison Rev 0.pdf) - PDF - 245 KB.

Screenshot of above: [![Arduino comparison][1]][1]

Credit: [Payne Technologies Limited](https://www.paynetech.co.uk/)

That compares *some* models in a way you might find useful.

---

> I have found that the hardware PWM isn't always the same from one Arduino Board design to another

The PWM frequencies can be changed over quite a wide range. I have a [page about timers](http://www.gammon.com.au/timers) which describes a lot of their features.

According to the [Arduino reference page about analogWrite](https://www.arduino.cc/en/Reference/AnalogWrite):

>  The frequency of the PWM signal on most pins is approximately 490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on the Leonardo also run at 980 Hz.

By changing the hardware register you can change those frequencies. The frequency of 980 Hz is because of the compromise needed to get an approximate 1 ms interrupt for use by the `millis()` function:

    16e6 / 64 / 256 = 976.5625 Hz

In other words the clock speed of 16 MHz is prescaled by 64 and then counted to 256, giving that frequency.

Note that this is *almost* 1 ms. The code behind `millis()` and `micros()` functions compensates for that so that you get a reasonably accurate result.

By changing the prescaler, and "count to" point you can get lots of other frequencies. However if you do that to Timer 0 on the Uno (and similar boards) then you will throw out the calculations for the `millis()` and `micros()` functions (you can compensate for that, of course).

---

This only partly answers your question, but hopefully will provide a nudge in a useful direction.

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


body:
I've connected an Arduino Uno to a MAX7219 IC, which is connected to only one standard 8x8 LED matrix, and an ADXL355 3-axis accelerometer. I use the matrix initially, and turn on all LEDs, while taking the "rest" values for the accelerometer to base all other calculations on. However, what happens is the current spike the LEDs create messes up the values - they become closer to 300, instead of the 230 they settle on when the spike is over. I've tried preventing this by adding up to a 5-second delay between the LEDs turning on and the rest values being measured. However, the problem still persists, though to a somewhat lesser extent.

Are there any methods to prevent this more effectively?

title: Methods to prevent Accelerometer values changing from current spikes

Answers: 1

body: Adding a distinct power supply for the MAX7219, as suggested by @jfpoilpret, solved the issue.


body:
Thank you for reading this.

Generally there are libraries for GSM and Ultrasound sensors for the software called Proteus and you can simulate them along with you MCU and the interfacing peripherals and simulate .

I have big problem at my hand , I want to simulate ESP8266 or any other relevant wifi module with my Arduino (Simulation Libraries for Arduino are available ) and get the data from sensor , all in software . Then , I want the wifi device (in software ) to show an ip address , so that I can log the data to an online cloud .

The software and module does not have to be specific , I want to know , If there are any professional software that let you simulate IoT based systems.

I'am new to IoT designing and I'am always comfortable with simulating everything.

If you have any other similar guide on how to design and simulate IoT systems , Let me know .

Have a great day

title: Simulation of IoT based systems in Software

Answers: 2

body:
There are tools to simulate Arduino, but it's not meant for anything beyond basic (i.e. simple circuit). Support is limited, you can't just simulate any and every sensor and shields (e.g. LAN, Wireless). Furthermore, ESP8266 is so cheap that hardly anybody has actual use-case to simulate them. I suggest you work on a real device =)

If you need to simulate data stream into your cloud or IoT platform, I suggest you just spin up a machine and run some code to generate data.

body:
I don't know of any simulators, but you might be able to do it yourself.

What you could do is to add a hardware abstraction layer to your code.  When you are running on hardware this just passes the calls to the hardware, i.e. `HAL_digitalRead(D0)` calls `digitalRead(D0)`.  When you want to simulate the hardware then you #ifdef the simulated code in and it calls {return DigitalPins[GetIndexFromPinName('D0')]; }

The theory is very simple but I don't think its an easy task.  I am surprised someone hasn't done it already, because debugging in Visual Studio or GDB in pure software would be much easier than doing it on the hardware.

I've never use Proteus, so I don't know if that will fit in with how that works at all.


body:
I'm new to arduino, and I want to design a Simple Delivery Robot for Data Center, which has an arm to move items, and it follows line while moving.

I have no idea if there is a special arduino board for these types of robot or I can buy any arduino board.

title: What is the best type of Arduino board for simple delivery robot?

Answers: 2

body:
**ANWSER**

I would suggest you to use the Arduino UNO for all the shields that it has. Most Arduinos are so similar that it wont make a difference but the UNO has many shields to it, including a motor/servo shield which is going to be great for your project.

But at the end of the day, it's your project and you can pretty much use any of the boards listed below. They are just advantages and disadvantages of many popular board. Hope it helped you!

**The summary has been removed for the sake of respecting Stack Exchanges rules.**

body:
Arduino UNO is the best arduino board for simple projects.
but if you want to add modules like LCD screen and some wireless sensors like bluetooth and RF and you want to make it with more motors then you should probably use Arduino Mega. It is better to use simple DC geared motors.


body:
I think the below logic should work but its throwing error

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

    void loop() {
      int soil_moisture = analogRead(A0); // read from analog pin A3
    //  int soil_moisture = pinMode(AO);
      Serial.print(“analog value: “);
      if (soil_moisture < 30) {
        Serial.println(“Dry soil”);
      }
      if ((soil_moisture > 300) && (soil_moisture < 700)) {
        Serial.println(“Humid soil”);
      }
      if ((soil_moisture > 700) && (soil_moisture < 950)) {
        Serial.println(“water”);
      }
    }

error i get is

    Arduino: 1.6.12 (Mac OS X), Board: "Arduino/Genuino Uno"

    analog_soil_moisture_v02.ino:16: error: stray '\342' in program
       Serial.print(“analog value: “);
       ^
    analog_soil_moisture_v02.ino:16: error: stray '\200' in program
    analog_soil_moisture_v02.ino:16: error: stray '\234' in program
    analog_soil_moisture_v02.ino:16: error: stray '\342' in program
    analog_soil_moisture_v02.ino:16: error: stray '\200' in program
    analog_soil_moisture_v02.ino:16: error: stray '\234' in program
    analog_soil_moisture_v02.ino:18: error: stray '\342' in program
         Serial.println(“Dry soil”);
         ^
    analog_soil_moisture_v02.ino:18: error: stray '\200' in program
    analog_soil_moisture_v02.ino:18: error: stray '\234' in program
    analog_soil_moisture_v02.ino:18: error: stray '\342' in program
    analog_soil_moisture_v02.ino:18: error: stray '\200' in program
    analog_soil_moisture_v02.ino:18: error: stray '\235' in program
    analog_soil_moisture_v02.ino:21: error: stray '\342' in program
         Serial.println(“Humid soil”);
         ^
    analog_soil_moisture_v02.ino:21: error: stray '\200' in program
    analog_soil_moisture_v02.ino:21: error: stray '\234' in program
    analog_soil_moisture_v02.ino:21: error: stray '\342' in program
    analog_soil_moisture_v02.ino:21: error: stray '\200' in program
    analog_soil_moisture_v02.ino:21: error: stray '\235' in program
    analog_soil_moisture_v02.ino:24: error: stray '\342' in program
         Serial.println(“water”);
         ^
    analog_soil_moisture_v02.ino:24: error: stray '\200' in program
    analog_soil_moisture_v02.ino:24: error: stray '\234' in program
    analog_soil_moisture_v02.ino:24: error: stray '\342' in program
    analog_soil_moisture_v02.ino:24: error: stray '\200' in program
    analog_soil_moisture_v02.ino:24: error: stray '\235' in program
    /Users/ciastro/Documents/Arduino/analog_soil_moisture_v01/analog_soil_moisture_v02.ino/analog_soil_moisture_v02.ino.ino: In function 'void loop()':
    analog_soil_moisture_v02.ino:16: error: 'analog' was not declared in this scope
       Serial.print(“analog value: “);
                       ^
    analog_soil_moisture_v02.ino:18: error: 'Dry' was not declared in this scope
         Serial.println(“Dry soil”);
                           ^
    analog_soil_moisture_v02.ino:21: error: 'Humid' was not declared in this scope
         Serial.println(“Humid soil”);
                           ^
    analog_soil_moisture_v02.ino:24: error: 'water' was not declared in this scope
         Serial.println(“water”);
                           ^
    exit status 1
    stray '\342' in program

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

title: getting error while trying to compile code for soil moisture sensor

Answers: 2

body:
It is because you declared NONE of your variables (`int`, `float`s) (except `soil_moisture`)

You must declare them. This is not Python where you can simply name a variable without declaring its type. Arduino language is based on C/C++.

body:
The actual error you are seeing is caused by the use of incorrect quotes in your program. You most likely copied and pasted the code from a website which has replaced the proper quotes with typeset-standard quotes:

        Serial.println(“Humid soil”);

should be:

        Serial.println("Humid soil");

Note the subtle difference in the quite shape. The first set are typesetter's open- and close-quote characters. The latter are just plain double-quotes (shift-2 on a UK keyboard).

There are other special characters in your program that need replacing with the standard ASCII equivalent, as well.


body:
I connect my ESP to Arduino to my PC.

If I send AT commands from my serial monitor, I receive full response. I use 115200 and both NL & CR in my serial monitor.

ESP TX is connected to TX Arduino, same for RX.

The problem is when I try to send commands from my Arduino code. I don't receive any response. I use same 115200 both for serial and for ESP8266.

I user this code:

    #include <SoftwareSerial.h>
    SoftwareSerial esp8266(0,1);

    void setup()
    {
        Serial.begin(115200);
        esp8266.begin(115200);
    }

    void loop()
    {
        sendCommand("AT+GMR\r\n");
    }

    String sendCommand(String command, const int timeout, boolean debug)
    {
        String come = "";

        while(esp8266.available())
        {
            char c = esp8266.read(); // read the next character.
            Serial.write(c);
            come += c;
        }
        Serial.println(come);
        return come;
    }

I can't see what is wrong here and why that works with just the Serial Monitor.

title: Arduino & ESP8266

Answers: 2

body:
Make a choice:

1. Are you using pins 0 and 1 for communicating with the PC, or
2. Are you using pins 0 and 1 for communicating with the ESP8266?

**You cannot do both.**

Move the ESP8266 onto some other pins.

body:
When you are using Arduino board just as USB --> RS232 converter then you have to, as you said, connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. [Here][1] I explained that in details.

  [1]: https://arduino.stackexchange.com/questions/30689/arduino-uno-and-esp8266-serial-monitor-issue/31929#31929


body:
I'm currently using an Arduino Uno R3 and an RFID-RC522 with https://github.com/miguelbalboa/rfid .

I wrote the following bytes to the trailer block in order to experiment with it:

    byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA };

I wanted to change the default `MFRC522::MIFARE_Key key.keyByte` so I can read and write to the card using a custom key and leave everything unchanged but I cannot access the sector anymore.

What do I have to do to be able to access the sector again?
[Code](https://pastebin.com/CfZH6nHA):

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

    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN 10
    #define RST_PIN 9
    /*
     * Pin connections for UNO:
     * 9  - RST
     * 10 - SDA
     * 11 - MOSI
     * 12 - MISO
     * 13 - SCK
     */
    MFRC522 mfrc522(SS_PIN, RST_PIN);
    MFRC522::MIFARE_Key key; // will hold card info

    // Every 4th block is a trailer block that contains access and security info, modulo 4.
    const int blockSize = 16;

    int writeBlockNumber = 2; // The block we want to write the data.
    int readBlockNumber = 2;
    byte writeBlockContent[blockSize] = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xFF, 0x7, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA }; // 16 character max
    byte readBlockContent[18] = { 0 };

    // Will write the data to the block.
    int writeBlock(int block, byte data[]) {
      int status;

      if ( (block + 1) % 4 == 0) {
        Serial.println("Warning: Writing on a trailer block!");
        return 0;
      }

      int trailerBlock = block + (4 - block % 4) - 1;
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);
      if ( status != MFRC522::STATUS_OK ) {
        Serial.print("PCD_Authenticate() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return status;
      }

      status = mfrc522.MIFARE_Write(block, data, blockSize);
      if ( status != MFRC522::STATUS_OK ) {
        Serial.print("MIFARE_Write() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return status;
      }
      return MFRC522::STATUS_OK;
    }

    // Will try to dump the whole card info.
    void dumpCard() {
      for(int i = 0; i < blockSize; ++i) {
          Serial.print("Block ");
          Serial.print(i);
          Serial.print(" ");
          if ( readBlock(i, readBlockContent) == MFRC522::STATUS_OK ) {
            printReadBlock();
          }
      }
      mfrc522.PICC_HaltA();
      mfrc522.PCD_StopCrypto1();
    }

    // Will read the block.
    // These functions must be called if you wish to read a new card.
    //    mfrc522.PICC_HaltA();
    //    mfrc522.PCD_StopCrypto1();
    int readBlock(int block, byte data[]) {
      int status;
      byte readSize = blockSize + 2;

      int trailerBlock = block + (4 - block % 4) - 1;
      status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &mfrc522.uid);

      if ( status != MFRC522::STATUS_OK ) {
        Serial.print("PCD_Authenticate() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return status;
      }

      status = mfrc522.MIFARE_Read(block, data, &readSize);
      if ( status != MFRC522::STATUS_OK ) {
        Serial.print("MIFARE_Read() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return status;
      }

      return MFRC522::STATUS_OK;
    }

    // Will print the contents of the readBlockContent.
    void printReadBlock() {
      for (int i = 0; i < blockSize; ++i) {
        Serial.print(readBlockContent[i], HEX);
        Serial.print(" ");
      }
      Serial.print(" -> ");
      for (int i = 0; i < blockSize; ++i) {
        Serial.write(readBlockContent[i]);
      }

      Serial.println();
    }

    // Will print the card id that is stored in mfrc522.uid.uidByte
    void printCardUid() {
      Serial.print("Card ID: ");
      for (int i = 0; i < mfrc522.uid.size; ++i) {
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        Serial.print(" ");
      }
      Serial.println();
    }

    void setup() {
      Serial.begin(9600);
      while (!Serial); // Wait for serial.
      SPI.begin();

      mfrc522.PCD_Init();
      Serial.println("Initialized...");

      // default access key STANDARD KEY 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
      for (int i = 0; i < 6; ++i) {
        key.keyByte[i] = 0xFF;
      }
    }

    void loop() {
      if ( ! mfrc522.PICC_IsNewCardPresent() ) {
          return;  // No card present, continue.
      }
      if ( ! mfrc522.PICC_ReadCardSerial() ) {
          // On success this function will return 1 and set the uid struct mfrc522.uid
          return;
      }

      printCardUid();

      // Write data to block.
    //  writeBlock(15, writeBlockContent);
    //  if ( readBlock(13, readBlockContent) == MFRC522::STATUS_OK )
    //    printReadBlock();

      dumpCard();

      mfrc522.PICC_HaltA();
      mfrc522.PCD_StopCrypto1();
    }

title: RFID-RC522 Can't access sector after writing to trailer block

Answers: 1

body:
And I [quote][1]:

> With each memory access the internal logic verifies the format of the access
conditions. If it detects a format violation the whole sector is irreversibly blocked.

The only thing that can get you locked out of a sector is incorrectly formatted access bits. As long as you didn't touch those, the sector should still be accessible.

It looks like you tried to change key A *and* key B. With the transport config, the contents of the sector trailer can only be altered if you authenticate the sector with Key A. Is that what you did? Lets continue then. Since you left the access bits unchanged (right?), it means only key A has R/W access to all blocks (except the manufacturer's) and key B, since it's still readable, can be used to authenticate but can't be used to access blocks. So, if your key change was successful, then you should be able to access the sector with your new key A i.e. `{0,0,0,0,0,0}`. If it wasn't successful (maybe because authentication failed), then the default key A should still be valid.

  [1]: http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf


body:
I installed the MATLAB support package for arduino in my MATLAB r2013a today.
Now I plugged on my Arduino in my usb port.

And ran the command:
>> a = arduino()

>> Error: Undefined function or variable 'arduino'.

When I get:

>> a = arduino('COM18')

>> Undefined function 'arduino' for input arguments of type 'char'.

I have checked that this package has been installed.
[![The Screenshot][1]][1]

It is grey.
[![enter image description here][2]][2]

Any help will be appreciated.

Thanks very much

Anupam.

  [1]: https://i.stack.imgur.com/QsUrH.png
  [2]: https://i.stack.imgur.com/0ckLu.png

title: Matlab interfacing with arduino ERROR

Answers: 1

body:
Arduino support within MATLAB came with Matlab-2014a onwards, you are using R2013a

Arduino support within SIMULINK came with Matlab-2012a onwards

for your release you can only interact via a simulink model


body:
I have a few questions about the Arduino Micro circuit:

 - If I can provide a steady 5 V source (connected to `+5V`), then I don't need to use the voltage regulator module (including the selector) of the circuit. Correct?
 - If I can provide a steady 5 V source (connected to `+5V`), then I don't need to connect anything to `VIN`. Correct? If that's right, should I connect it (`VIN`) to `GND`, instead of leaving it floating?
 - If I'm not using `+3.3V`, should I connect it to `GND` (instead of leaving it floating)?
 - If I'm powering off of *just* USB, then I can connect `+5V` to `VUSB`. Correct?

Schematic below for reference:

![Arduino Micro Schematic](https://i.stack.imgur.com/o8ZdO.jpg)

title: Arduino Micro Power Questions

Answers: 1

body:
> If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

If you are powering off USB leave everything alone. See the schematic:

[![USB input][1]][1]

The blue line added by me shows what is going on. The VBUS signal from the USB connector goes through a 500 mA resettable fuse (to protect the USB port from overloads). Then it goes to the P-channel MOSFET (FDN340P) which makes a decision about whether to switch on and connect VUSB to +5V signal. It does so if VIN is low, making the MOSFET conduct. If VIN is high (which it would be if you had power into the VIN part of the board) then it disconnects the USB from the +5V line.

---

> If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?

Definitely not. The 3.3V line is an output from the 3V3 voltage regulator. To connect it to ground would heat it up and destroy it.

---

> If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?

No, VIN is already connected to ground via a 10k resistor (see schematic above) and thus it is not floating.

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


body:
Can someone please tell me what I'm doing wrong?

The motor's not turning at all, never mind changing speed.

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

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

title: Gradual change of PWM motor control

Answers: 3

body:
A0 is an analog input. You can't output from it. You can only output on analog input pins by using defining them as 14,15,16...

For the best result, try changing the motor pin to something like pins 9, 10 or 11. They are my favorite PWM pins.

body:
It looks like you are attempting to perform hardware PWM on an Analog Input Pin.

Assuming that you are using an Arduino Uno, try changing your first line of code to use one of the digital output pins which support PWM. You can use any of pins 3, 5, 6, 9, 10, or 11. Then connect that pin to your motor. (Note that you will likely have to use a transistor or driver circuit between the pin and the motor since the motor may well require more current to operate than the Arduino output can directly supply.)

If you are using a different Arduino other than the Uno, look at the documentation to find one of the PWM pins and try using that.

body:
You should copy and paste the text of the code into your question, not a screenshot of it. Then we can copy and paste the problem lines into the answer.

You are varying up and down the variable `motorVoltage` in two loops. However you are not then doing an `analogWrite` with the new value. It should be more like this:

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

    while (motorVoltage <= 255)
      {
      analogWrite (motorPower, motorVoltage);
      motorVoltage++;
      delay (200);
      }


body:
Basically I have created the following code to control my stepper motor:

    int pin_enable_motor_x = 38;
    int pin_motor_step_x = A0;
    int pin_direction_x = A1;
    int endstop_x = 3;

    void setup() {
      pinMode(pin_enable_motor_x, OUTPUT);
      pinMode(pin_motor_step_x, OUTPUT);
      pinMode(pin_direction_x, OUTPUT);
      pinMode(endstop_x, INPUT);

      digitalWrite(pin_enable_motor_x, LOW);

      for (int i = 0; i < 200000; i++) {
        runMotorSingleStepX(100, false); // runMotorSingleStepX(int delay, boolean direction)
        if (digitalRead(endstop_x) == true) {
          break;
        }
      }
    }

    void loop() {

    }

    void runMotorSingleStepX(int wait, boolean value) {
      digitalWrite(pin_direction_x, value);
      digitalWrite(pin_motor_step_x, HIGH);
      delayMicroseconds(wait);
      digitalWrite(pin_motor_step_x, LOW);
      delayMicroseconds(wait);
    }

The idea is that the stepper motor will give many single steps until it reaches my mechanical endstop. But what really happens is that it detects `true` random pulses even when my endstop isn't pressed. So my motor stops before the point it should stop. I'm not sure if it's a common problem and I should be using some tricks to fix this problem.

Does anyone know what could be happening supposing that my electronics circuit is properly settled?

title: Problem stopping a stepper motor with an endstop

Answers: 2

body:
Your `for()` loop is using an `int` type for the iterator. You are asking it to run for up to 200,000 steps but an `int` is a 16 bit signed entity (~+/-32,768) so the `for()` loop will exit well before it reaches your desired count. That may be why you are not reaching the stop while still in the loop.

You may want to use an unsigned long as the type for your loop counter and or use a `while()` construct in which you incorporate the exit condition.

body:
*Answer based on comments originally under the question*

It sounds like the endstop switch may have floating input. Try making the endstop pins `INPUT_PULLUP` rather than `INPUT`.

> It seems to be a little more stable... But it still stops before the point sometimes.

Try a stronger pull-up, like 10k. Over a long wiring run the inbuilt 50k pull-up may not be strong enough to counter noise in nearby wires.

> Thanks, the extra 10K resistor solved the problem :)


body:
I am new to ESP8266. To ease out the task of programming esp8266, I bought this:  [ESP-01 ESP8266 Programmer CH340G Chip USB WiFi Wireless UART GPIO0 Adapter][1].

[![ ESP-01 to USB converter Connected][2]][2]

Configured Arduino Interface to run **AT** commands in the serial monitor.
I flashed ESP8266 with the basic **blink LED** example. It worked fine for some time and later on gave this error.

    warning: espcomm_sync failed

When i tried to flash another program on to ESP8266, I am getting the following error.

    Sketch uses 221,995 bytes (51%) of program storage space. Maximum is 434,160 bytes.
    Global variables use 31,568 bytes (38%) of dynamic memory, leaving 50,352 bytes for local variables. Maximum is 81,920 bytes.
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed
    error: espcomm_upload_mem failed

I could only find [one article][3] regarding this adapter.
There he made a custom bridge soldering GPIO 0 to GND for ESP8266 Flashing.

So should i make a removable bridge for the same, to upload a new program.
Is there any other way to simplify this task?

  [1]: http://www.ebay.in/itm/ESP-01-ESP8266-Programmer-CH340G-Chip-USB-WiFi-Wireless-UART-GPIO0-Adapter-/272370382534?
  [2]: https://i.stack.imgur.com/95PxE.jpg
  [3]: http://www.esp8266.com/wiki/doku.php?id=all-in-one-esp-usb-converter

title: ESP8266 Programming using ESP-01 to USB converter

Answers: 2

body:
Finally I made a breadboard connection joining ESP8266's GPIO 0 and GND to Programmer's GND for flashing the chip

[For more info][1]

[![Connections][2]][2]

Additional Reference:
[Programming ESP8266][3]

  [1]: http://www.arjunsk.com/iot/programming-esp8266-esp-01-using-esp8266-programmer-ch340g-chip-adapter/
  [2]: https://i.stack.imgur.com/zxC3r.jpg
  [3]: http://www.arjunsk.com/tag/esp8266/

body:
Just solder a jumper to the adapter according to this image (bottom side):
[![esp-01 adapter][1]][1]

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

If you want to use programming mode, just switch to connect GND and GPIO0. Switch back to use GPIO0 as IO pin (you may attach your F-F Dupont cable to the floating pin).


body:
I'm new with Arduino (and I'm not very good at English). Recently with Arduino Nano I have tested:

- Control water pump based on soil moisture (using relay) (1)
- Display soil moiture (in percent) on a Nokia 5110 LCD   (2)

Now I'm combining 2 codes to control water pump while always displaying moisture value (in percent) on LCD. However, after I have uploaded the code an Arduino Nano, the LCD showed nothing.

When I touched the sensor (changed moisture value) the first time, the LCD showed up, but when I touched the sensor the second time (changed moisture value again), the LCD went blank. The relay and pump still work fine, so I think the problem comes from LCD's code.

Here's my code (1):

    const int VAL_PROBE = 0;
    int RELAY1 = A1;
    const int MOISTURE_LEVEL = 250;

    void setup()
    {
      Serial.begin(9600);
      pinMode (2, INPUT);
      pinMode(A0, INPUT);
      pinMode(RELAY1, OUTPUT);
    }

    void loop()
    {
      int moisture = analogRead(VAL_PROBE);
      Serial.print("Moisture = ");
      Serial.println(moisture);

      if(moisture < MOISTURE_LEVEL)
      {
        digitalWrite(RELAY1,0);           // turn on relay
        Serial.println("Light ON");
      }
      else
      {
        digitalWrite(RELAY1,1);          // turn off relay
        Serial.println("Light OFF");
      }
    }

The code (2)(got it from the Internet):

        //////////////////////////////////////////////
       //        Arduino Soil Moisture Sensor      //
      //            with NOKIA 5110 LCD           //
     //           http://www.educ8s.tv           //
    //////////////////////////////////////////////

    #include <LCD5110_Graph.h> // THE LIBRARY I AM USING IS THIS:  http://www.rinkydinkelectronics.com/library.php?id=47

    LCD5110 lcd(8,9,10,12,11);

    extern unsigned char BigNumbers[];
    extern uint8_t ui[];

    int sensorPin = A0;
    int sensorValue = 0;
    int percent = 0;
    String percentString ="0";
    int stringLength = 0;

    void setup() {
      lcd.InitLCD();
      lcd.setFont(BigNumbers);
      delay(1000);
    }

    void loop() {
      lcd.clrScr();
      lcd.drawBitmap(0, 0, ui, 84, 48);
      sensorValue = analogRead(sensorPin);
      percent = convertToPercent(sensorValue);
      percentString = String(percent);
      stringLength = percentString.length();
      displayPercent(stringLength);

      lcd.update();
      delay(1000);
    }

    int convertToPercent(int value)
    {
      int percentValue = 0;
      percentValue = map(value, 1023, 350, 0, 100);
      if(percentValue>100)
        percentValue = 100;
      return percentValue;
    }

    void displayPercent(int length)
    {
      switch(length)
      {
        case 1:  lcd.print(percentString,38,19); break;
        case 2:  lcd.print(percentString,24,19); break;
        case 3:  lcd.print(percentString,10,19); break;
        default:  lcd.print(percentString,0,19); break;
      }
    }

And my combined code:

    const int VAL_PROBE = 0;
    int RELAY1 = A1;
    const int MOISTURE_LEVEL = 250; // Mức độ ẩm cố định là 250
    #include <LCD5110_Graph.h>

    LCD5110 lcd(8,9,10,12,11);

    extern unsigned char BigNumbers[];
    extern uint8_t ui[];

    int sensorPin = A0;
    int MoistureValue = 0;
    int percent = 0;
    String percentString ="0";
    int stringLength = 0;

    void setup()
    {
      Serial.begin(9600);//Mở cổng Serial ở mức 9600
      pinMode (2, INPUT);
      pinMode(A0, INPUT);
      pinMode (12, OUTPUT);
      pinMode(RELAY1, OUTPUT);
      lcd.InitLCD();
      lcd.setFont(BigNumbers);
      delay(1000);
    }

    void loop()
    {
      lcd.clrScr();
      lcd.drawBitmap(0, 0, ui, 84, 48); // hiển thị giao diện màn hình
      MoistureValue = analogRead(sensorPin); // đọc giá trị từ cảm biến

      percent = convertToPercent(MoistureValue);
      percentString = String(percent);
      stringLength = percentString.length();
      displayPercent(stringLength);

      lcd.update(); // cập nhật màn hình
      delay(1000); // mỗi 1 giây

      int moisture = analogRead(VAL_PROBE);
      Serial.print("Moisture = ");
      Serial.println(moisture);

      if(moisture < MOISTURE_LEVEL)
      {
        digitalWrite(12,HIGH);
        digitalWrite(RELAY1,0);           // bật relay
        Serial.println("Light ON");
      }
      else
      {
        digitalWrite(12,LOW);
        digitalWrite(RELAY1,1);          // tắt relay
        Serial.println("Light OFF");
      }
    }

    int convertToPercent(int value) // đổi giá trị cảm biến sang phần trăm
    {
      int percentValue = 0;
      percentValue = map(value, 1023, 350, 0, 100);
      if(percentValue>100)
        percentValue = 100;
      return percentValue;
    }

    void displayPercent(int length) // hiển thị phần trăm ra màn hình
    {
      switch(length)
      {
        case 1:  lcd.print(percentString,38,19); break;
        case 2:  lcd.print(percentString,24,19); break;
        case 3:  lcd.print(percentString,10,19); break;
        default:  lcd.print(percentString,0,19); break;
      }
    }

Any advice?

title: Controling pump while displaying moisture value on a LCD at the same time with soil moisture sensor?

Answers: 2

body:
I think the problem is with

    digitalWrite(12,HIGH);

and

    digitalWrite(12,LOW);

Pin 12 is used by the LCD. Changing it's output will reset the LCD. I'm not sure why you put it there to begin with, as it wasn't part of any of the two sketches.

body:
in cases like this where you are combining multiple pieces of code together, a simpler approach would be to rename that:

    //set up 1
    void setup1(void) {
    ...
    }

    //loop 1
    void loop1(void) {
    ...
    }

    //set up 2
    void setup2(void) {
    ...
    }

    //loop 2
    void loop2(void) {
    ...
    }

    ...

    //combined setup
    void setup(void) {
      setup1();
      setup2();
      ...
    }

    //combined loop
    void loop(void) {
      loop1();
      loop2();
      ...
    }

that's much easier to track than to manually copy-and-paste them.


body:
I'm trying to communicate with my Arduiono UNO via USB serial port, more precisely I'm trying to read a string like 125,0, I know it's full of article out there about this, but belive me I've tryied more or less everything, now I got a NODEJS server on a Raspberry Pi that looks like:

    var express = require('express');
    app = express();
    server = require('http').createServer(app);
    io = require('socket.io').listen(server);

    var SerialPort = require("serialport")
    var serialPort = new SerialPort("/dev/ttyACM1", { baudrate: 115200 });

    server.listen(8080);
    app.use(express.static('public'));

    var brightness1 = 0;
    var brightness2 = 0;
    var string;

    io.sockets.on('connection', function (socket) {
     socket.on('led', function (data) {
       brightness1 = data.value1;
      brightness2 = data.value2;
      string = brightness1 +","+brightness2;
      var buf = new Buffer(1);
      buf.write(string);
      serialPort.write(buf);
      console.log(buf);
            console.log(string);
         io.sockets.emit('led', {value1: brightness1, value2: brightness2});

     });

So based on that, I'm sending a string over the serial and the console log showed above gives me that:

    <Buffer 32>    //console.log(buf);
    23,0           //console.log(string);

Wich I think it should be ok because I'm sending what I need a 32 and a 0, also if i don't know what it means the <Buffer 32>

Arduino side I used the sketch provided [here][1] and retouch it a bit based on my needs:

    void setup()
    {
      Serial.begin(115200);
    }
    void loop()
    {
      while(!Serial.available()); //wait until a byte was received
          Serial.println(Serial.read());
          int a = Serial.parseInt();
          int b = Serial.parseInt();
          Serial.println(a);
          Serial.println(b);
          //analogWrite(3, a);
    }

but the result of my Serial.print() are really incongruents, something like:
5--2224, which is totally nosense, my question so is WHY? Where I'm getting wrong? I read a lot around, am I missing something?

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

title: How to correctly read a string from Arduino serial port?

Answers: 3

body:
This is a common (and my favorite) approach:

* Choose an “end of message” character. CR or LF can be good choices,
  especially if you want to test your program with a terminal emulator.
* On the Arduino, buffer all the received bytes until you see the end of
  message.
* When you see the end of message, handle the buffer to a function that
  will parse and process it.

I would avoid `parseInt()` for anything but the simplest tests, because
it is both blocking and sensitive to the timing of the input.

For an example, you can take a look at this
[Simple Arduino command line
interpreter](https://gist.github.com/edgar-bonet/607b387260388be77e96)
(look at `loop()`). It's non blocking, so you can add background
processing to perform while waiting for input characters.

body:
I fully agree here with edgar Bonet.
I only want to add a link to a library I have written that does a line by line (based on end message CR and/or LF)
[SerialStringReader][1]
This library contains examples.
Note that for many reasons the library uses null terminated strinsg (also known as char arrays) and not the Arduino String class

  [1]: https://github.com/jantje/ArduinoLibraries/tree/master/SerialStringReader

body:
>How to correctly read a string from Arduino serial port?

You can use the function `Serial.readString()`. It will return a string that you typed from the serial monitor.


body:
I am learning about pointers.

I was wondering how the memory address is defined in programming. I get different outputs depending on the format I choose for memory address. So I was wondering if it is correct to assume that the format of the memory address is defined by the programmer. I get different results for memory address when I use `Serial.print( (long) &ptr1, DEC);` and `Serial.print( (long) &ptr1, HEX);`

     #include <stdio.h>
     int counter = 0;
       void setup() {
        Serial.begin(9600);
       int test1 = 10;
       float test2 = 3.14159;
       char test3[ ] = "This is a character array";
       int *ptr1;
       float *ptr2;
     char *ptr3;
      ptr1 = &test1;
    Serial.print("The integer value is stored at ");
    Serial.print( (long) &ptr1, DEC);

     Serial.print("The integer value is stored at ");
      Serial.print( (long) &ptr1, HEX);

      }
     void loop() {

        }

My output is:

The integer value is stored in  2296

The integer value is stored in  8f8

title: Using pointers with Arduino

Answers: 1

body:
You're printing the address of the pointer, not the contents of the pointer.

Say you have the memory map of:

    100 20       test1 low byte
    101 0        test1 high byte
    102 100      ptr1 low byte
    103 0        ptr1 high byte

`test` is located at address 100 and takes two bytes. `ptr1` is located at 102 and takes two bytes. `ptr1` contains the address of `test` (100) and `test1` contains the value `20`.

The different possible combinations of prints are:

    Serial.println(test1);  => 20 (contents of test1)
    Serial.println(&test1); => 100 (address of test1)
    Serial.println(ptr1);   => 100 (contents of ptr1 = address of test1)
    Serial.println(&ptr1);  => 102 (address of ptr1)
    Serial.println(*ptr1);  => 20 (contents of address pointed to by ptr1).

(note: some of those will require a *cast* in order for the C++ to select the correct `println()` overload function.)


body:
I have written some Arduino code (with help from the post *[Serial Input Basics][1]*). On serial I send some data and, based on certain values sent, certain LEDs will be lit. Here is the Arduino code:

    const byte numChars = 32;
    char receivedChars[numChars];
    char tempChars[numChars];        // Temporary array for use when parsing

    // Variables to hold the parsed data
    //char messageFromPC[numChars] = {0};
    int cmd = 0;
    int pitch = 0;
    int velocity = 0;
    int integerFromPC = 0;
    int int2FromPC = 0;
    boolean newData = false;

    void setup() {

        // Put your setup code here, to run once:
        Serial.begin(9600);//set baud rate

        //Configure pins 2:5 as OUTPUT
        pinMode(2,OUTPUT);
        pinMode(3,OUTPUT);
        pinMode(4,OUTPUT);
        pinMode(5,OUTPUT);
        pinMode(13,OUTPUT);
    }

    void loop() {
        recvWithStartEndMarkers();
        if (newData == true) {
            strcpy(tempChars, receivedChars);
            // This temporary copy is necessary to protect the original data
            // because strtok() used in parseData() replaces the commas with \0.

            parseData();
            showParsedData();
            if(cmd==144 && velocity!=0){
                switch(pitch){
                    case 30:
                        digitalWrite(2, HIGH);
                        break;

                    case 31:
                         digitalWrite(3, HIGH);
                         break;

                    case 32:
                        digitalWrite(4, HIGH);
                        break;

                    case 33:
                        digitalWrite(5, HIGH);
                        break;

                    default:
                        break;
                }
            }
            if(cmd==144 && velocity==0){
                switch(pitch){

                    case 30:
                        digitalWrite(2, LOW);
                        break;

                    case 31:
                        digitalWrite(3, LOW);
                        break;

                    case 32:
                        digitalWrite(4, LOW);
                        break;

                    case 33:
                        digitalWrite(5, LOW);
                        break;

                    default:
                        break;
                }
            }
            newData = false;
        }
    }

    void recvWithStartEndMarkers() {

        static boolean recvInProgress = false;
        static byte ndx = 0;
        char startMarker = '<';
        char endMarker = '>';
        char rc;

        while (Serial.available() > 0 && newData == false) {
            rc = Serial.read();

            if (recvInProgress == true) {
                if (rc != endMarker) {
                    receivedChars[ndx] = rc;
                    ndx++;
                    if (ndx >= numChars) {
                        ndx = numChars - 1;
                    }
                }
                else {
                    receivedChars[ndx] = '\0'; // Terminate the string
                    recvInProgress = false;
                    ndx = 0;
                    newData = true;
                }
            }

            else if (rc == startMarker) {
                recvInProgress = true;
            }
        }
    }

    void parseData() {      // Split the data into its parts

        char * strtokIndx;  // This is used by strtok() as an index

        strtokIndx = strtok(tempChars, " "); // Get the first part - the string
        //strcpy(messageFromPC, strtokIndx); // Copy it to messageFromPC
        cmd = atoi(strtokIndx);

        strtokIndx = strtok(NULL, " ");      // This continues where the previous call left off
        //integerFromPC = atoi(strtokIndx);  // Convert this part to an integer
        pitch = atoi(strtokIndx);

        strtokIndx = strtok(NULL, " ");
        velocity = atoi(strtokIndx);         // Convert this part to a float
    }

    void showParsedData() {
        Serial.print("Comm ");
        Serial.println(cmd);
        Serial.print("Ptch ");
        Serial.println(pitch);
        Serial.print("Velo ");
        Serial.println(velocity);
        Serial.println("\n");
    }

Now this works perfectly with sending data from the Arduino's serial monitor, so for example if I type the following on serial monitor:

    <144 30 45>

Then the LED I expect to get lit does, and I can turn it off by:

    <144 30 0>

Now, I want to send this data from a Python (2.7) program which I am reproducing here:

    #!/usr/bin/env python
    import time
    import serial
    ser = serial.Serial('/dev/cu.usbmodem1421', 9600)
    noteOn = 144
    veloMid = 75
    veloSilent = 0
    def sendData(cmd, pitch, velocity):
        global ser
        cmd = bytes(cmd)
        pitch = bytes(pitch)
        velocity = bytes(velocity)
        ser.write("<")
        ser.write(cmd)
        ser.write(pitch)
        ser.write(velocity)
        ser.write(">")

    while 1:
        notes = range(30, 34)
        for note in notes:
            sendData(noteOn, note, veloMid)
            time.sleep(2)
            sendData(noteOn, note, veloSilent)

The idea was to do the same thing I was doing manually in serial monitor, except using a Python script. But this produces no result. I see the RX and TX pins on the Arduino toggling, so it looks like the program is indeed communicating with the Arduino. In the Python IDE I wrote a few lines as follows to read the data from Arduino:

    import serial
    ser = serial.Serial('/dev/cu.usbmodem1421', 9600, timeout=5)
    while True:
        data_raw = ser.read()
        print data_raw

With above code I receive the following characters in the Python IDE:

    C
    o
    m
    m

    P
    t
    c
    h

    V
    e
    l
    o

I have a feeling there is some mismatch between the data types of the data I am sending between the Python script and the Arduino, but I am not sure exactly what this mismatch might be.

- Why am I not seeing the values of cmd, pitch and veocity being printed out from the serial.read() although the other strings "Comm   Ptch   Velo" are printed?

- What dataype is serial.write passing on that might than be causing mismatch with my Arduino code?

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

title: Why is communication between a Python program and Arduino not producing the expected result?

Answers: 1

body:
In your test with the serial monitor you are putting spaces between each number. Using my logic analyzer I got this being sent from your Python code to the Arduino:

[![Logic analyzer image][1]][1]

No spaces, right? So the Arduino is receiving:

    <1443175>

And since you are using a space as a numeric delimiter your decoding isn't working.

---

Something like this is probably warranted:

<!-- language: lang-python -->

        ser.write("<")
        ser.write(cmd)
        ser.write(" ")
        ser.write(pitch)
        ser.write(" ")
        ser.write(velocity)
        ser.write(">")

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


body:
Please, someone.

I want to use a temperature sensor (DS18B20) in an I2C only shield ([Tentacle Mini](https://www.whiteboxes.ch/tentacle/tentacle-mini-quickstart)), but this sensor is One Wire only. Can I write an I2C code to change the 1-Wire to I2C for this sensor? I think to use the ([DS2482-800](https://www.maximintegrated.com/en/products/interface/controllers-expanders/DS2482-800.html)) bridge, but I don't know how to do...

Thanks!

title: Help with 1-Wire to I2C translate

Answers: 1

body:
As you said, the DS18B20 uses One-Wire interface. I2C is a Two-Wire interface. Pratically, you can't use the Arduino to translate that, BUT I found the  [DS28E17][1], a module that could translate the the 2 methods of communication. It should work but I havent tested it.

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

The DS28E17 is a 1-Wire slave to I2C master bridge device that interfaces directly to I2C slaves at standard (100kHz max) or fast (400kHz max). Data transfers serially by means of the 1-Wire® protocol, which requires only a single data lead and a ground return. Every DS28E17 is guaranteed to have a unique 64-bit ROM registration number that serves as a node address in the 1-Wire network. Multiple DS28E17 devices can coexist with other devices in the 1-Wire network and be accessed individually without affecting other devices. The DS28E17 allows using complex I2C devices such as display controllers, ADCs, DACs, I2C sensors, etc. in a 1-Wire environment. Each self-timed DS28E17 provides 1-Wire access for a single I2C interface.

Hope I helped you.

  [1]: https://www.maximintegrated.com/en/products/interface/controllers-expanders/DS28E17.html
  [2]: https://i.stack.imgur.com/llicG.png


body:
I have an interrupt signal attached to the A12 pin of an Arduino Mega 2560.

Would the following source line activate the interrupt processing?  I am calling the `digitalPinToInterrupt` function on an Analog pin.  It compiles fine.

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

    attachInterrupt(digitalPinToInterrupt(A12), MessageFromIOBInt, FALLING);

where my interrupt code is

    void MessageFromIOBInt(void) {
     ++gNumInterrupts;
    }

title: Does 'digitalPinToInterrupt' work with analog pins

Answers: 2

body:
Interrupts only work on interrupt pins. Trying to translate a pin number into an interrupt number for a pin that isn't an interrupt pin will never work.

> External Interrupts: 2 (interrupt 0), 3 (interrupt 1), 18 (interrupt 5), 19 (interrupt 4), 20 (interrupt 3), and 21 (interrupt 2). These pins can be configured to trigger an interrupt on a low level, a rising or falling edge, or a change in level.

Many pins (including the analog pins) can use the *pin change* interrupt. This requires an [external library](http://playground.arduino.cc/Main/PinChangeInt) which has its own way of interfacing with them (see the examples).

body:
> Does 'digitalPinToInterrupt' work with analog pins?

It works in the sense that it compiles. When executed, for a pin that is not one of the interrupt pins it will return the value `NOT_AN_INTERRUPT`.

Thus a sensible test would be to check whether or not you get `NOT_AN_INTERRUPT` returned from `digitalPinToInterrupt(A12)`.

A quick test confirms this:

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

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();
      Serial.println (digitalPinToInterrupt(A12));
    }  // end of setup

    void loop () { }

Output:

    -1

---

In Arduino.h is this define:

    #define NOT_AN_INTERRUPT -1

I have [a page about interrupts](http://www.gammon.com.au/interrupts). On that page, amongst other things, is a list of external interrupt pins for various Arduinos:

[![Interrupt pins][1]][1]

You can see that the pins on the board labelled D2, D3, D18, D19, D20, D21 are the only ones which support these sorts of interrupts (external interrupts). Various other pins support pin-change interrupts.

On the Mega2560 in particular these pins are supported for pin-change interrupts:

>   10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69)

---

As Majenko mentioned, you use pin-change interrupts in a different way, possibly using the [PinChangeInt](http://playground.arduino.cc/Main/PinChangeInt) library, or just accessing the registers yourself as described on the page I mentioned above.

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


body:
I use [this][1] Library to measure my free RAM on a Mega in runtime. But this Library does not work on the Due.

  [1]: https://github.com/McNeight/MemoryFree

title: How to measure free RAM on an Arduino Due in Runtime?

Answers: 2

body:
Try to use this method:

    int freeRAM() {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

body:
As mentioned by Mikael Patel in a comment, the library from [Arduino-MemoryFree
](https://github.com/mpflaga/Arduino-MemoryFree) should do it. A minimal sketch that seems to work on the Due:

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

    extern "C" char* sbrk(int incr);

    int freeMemory() {
      char top;
      return &top - reinterpret_cast<char*>(sbrk(0));
    }

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ();
      Serial.print ("Free memory is: ");
      Serial.println (freeMemory ());
    }  // end of setup

    void loop () { }

I'm not totally convinced that this gives the correct figure. The figure returned by the library above for my Uno was too high (2297 bytes).


body:
Hey all I am wondering if it's possible to modify the WString.cpp file to only include the commands that I need for my project since that file is so large.

I am using a Digispark arduino that is Attiny85 which only has about **6k flash memory after bootloader**.

Needless to say I am almost out of flash memory and I still need to do a few things.

I am reading from a serial port (in this case, using [DigiCDC][1] for a virtual serial port).

How can I overwrite the default Strings class that looks like its built in to the IDE with my own modified String class so I can get a smaller footprint?

Thanks!

  [1]: https://digistump.com/wiki/digispark/tutorials/digicdc

title: Replacing stock String.cpp with smaller version

Answers: 1

body:
You can make a copy of WString.cpp, edit it, and add it to your project.
Note however that:

1. You will have to define _every method_ that you use. Otherwise the
   linker will pull WString.o from the Arduino core library in order to
   resolve the missing methods, and then it will complain that some
   methods have been defined twice.
2. Just pruning WString.cpp from unused methods will not help: the
   linker is already doing that for you.
3. To know which functions/methods of your program are taking too much
   flash, you can use the command
   [`avr-nm --size-sort -Crtd program.elf`](https://arduino.stackexchange.com/a/12684).
4. I second Majenko in recommending against String objects if possible.


body:
I am currently working on a python-based Bluetooth Low Energy client for OS X and I got stuck while trying to write a remote float characteristic value.

First of all: my setup is an Arduino 101 with integrated BLE module and a Macbook. On the Arduino side the code is working well, I can read and write BLE characteristic's from a BLE explorer app on my phone.

Also I did achieve to read out the characteristics float values in my python script on the Macbook. Yet I did not fully understand what exactly I am doing. After requesting the characteristic's value from the peripheral, the peripheral answers and I get what I think is binary data? I could manage to unpack the data to a float by using.

         def characteristic_to_float(data):
            float_value = struct.unpack('f', data)[0]
            return float_value

The received floats are correct. But I couldn't get my python code to properly write a float value to the peripheral. I tried this:

        a_number = 5.3

        def float_to_characteristic(float_value):
            val = struct.pack('<f', float_value)[0]
            return val

        characteristic_1.write_value(float_to_characteristic(a_number))

The python code itself will run through without an error, but the Arduino doesn't receive the data. I am sure of that, because I implemented a function on it that sends out a Serial print when a characteristic has been written.

Remember the characteristics are read & write and I could verify this by using my phone. I think I got something wrong with the struct.pack thing, since I can't find any information about what data format is needed...

Does someone know how I can pack or convert the float to the right data format? Unfortunately the lib I use (Adafruit BluefruitLE) does not have a documentation.

Thanks!

title: Writing a float to a BLE characteristic. What data format?

Answers: 3

body:
Two solutions came to my mind if am gonna do your thing,
1) convert the number to a string char by char and send it as it is then unpack it as char by char , for example 5.3 -- > "5.3" it will be received then you have to decompose it 5 and . and 3 (inefficient solution because of conversion of types will be alot)

2) calculate the number of decimal digits and send it with the number something like:
5.3 ---> 53 and one decimal point, you would send it as
53:1 and then unpack it and reconstruct it

the second solution would be better for me since i have to send it as 2 things
number: decimal point
and then reconstruct it, this library will ease the reconstruction of decimal point sent by 53:1 (if you want to send floats in two directions)
[SimpleSerialExtractor][1]

  [1]: https://github.com/Mohamad1994HD/SimpleSerialExtractor.git

body:
I could solve the issue by taking another look in the documentation of the struct lib in python. I tested different pack and unpack methods and wondered where the [0] in my code came from (I did copy it from somewhere). So what I found working for my setup simply is:

    def float_to_characteristic(float_value):
           val=struct.pack('<f',float_value)
           return val

When I send this packed value through BLE the Arduino will accept it.

body:
I used this way:
define a BLE format descriptor (0x2904)
Attach the descriptor to the characteristic
```
struct BLE2904_Data {
  uint8_t m_format;
  int8_t m_exponent;
  uint16_t m_unit;
  uint8_t m_namespace;
  uint16_t m_description;
} __attribute__((packed));

struct BLE2904_Data desc1;   // must remain valid memory for ArduinoBLE

  desc1.m_format = 0x14;  // float
  desc1.m_exponent = 0x0;
  desc1.m_unit = 0x2728;  // voltage
  desc1.m_namespace = 1;
  desc1.m_description = 0x10f;

  BLEDescriptor voltageLabelDescriptor("2904", (uint8_t*)&desc1, sizeof(desc1));
  batteryLevelCharacteristic.addDescriptor(voltageLabelDescriptor);
```
The 2904 descriptor sets the data type see [here][1] for more details:

  [1]: https://btprodspecificationrefs.blob.core.windows.net/assigned-numbers/Assigned Number Types/Assigned_Numbers.pdf