body:
I tried the code below and it worked for me, don't miss the `delay()` part:

**Sender Code:**

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

    void loop() {
        float yaw = 10.5;
        float pitch = 20.15;
        float roll = 100.10;
        float ypr[3];
        ypr[0] = yaw;
        ypr[1] = pitch;
        ypr[2] = roll;
        Serial.write((byte*) ypr, 12);  // No new-line
        delay(1000);

    }

**Receiver Code:**

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

    void loop() {

    }

    void serialEvent() {
        if (Serial.available() == 12){
          byte yawData[4];
          yawData[0] = Serial.read();
          yawData[1] = Serial.read();
          yawData[2] = Serial.read();
          yawData[3] = Serial.read();
          float yawAngle = *((float*)(yawData));
          Serial.println(yawAngle);

          yawData[0] = Serial.read();
          yawData[1] = Serial.read();
          yawData[2] = Serial.read();
          yawData[3] = Serial.read();
          float yawPitch = *((float*)(yawData));
          Serial.println(yawPitch);

          yawData[0] = Serial.read();
          yawData[1] = Serial.read();
          yawData[2] = Serial.read();
          yawData[3] = Serial.read();
          float yawRoll = *((float*)(yawData));
          Serial.println(yawRoll);
        }
    }

**Results:**

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

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


sender: user

message:
Assemble or typecast byte array to float

The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays

`0.00`

`0.00`

`0.00` etc.

Here is the code:

    void serialEvent2() {
      if (Serial2.available() > 11) {
        byte yawData[3];
        yawData[0] = Serial2.read();
        yawData[1] = Serial2.read();
        yawData[2] = Serial2.read();
        yawData[3] = Serial2.read();
        float yawAngle = *((float*)(yawData));
        Serial.println(yawAngle);

        byte pitchData[3];
        pitchData[0] = Serial2.read();
        pitchData[1] = Serial2.read();
        pitchData[2] = Serial2.read();
        pitchData[3] = Serial2.read();
        float pitchAngle = *((float*)(pitchData));

        byte rollData[3];
        rollData[0] = Serial2.read();
        rollData[1] = Serial2.read();
        rollData[2] = Serial2.read();
        rollData[3] = Serial2.read();
        float rollAngle = *((float*)(rollData));
      }
    }

I made sure the data coming to Serial2 is not `0`.

**UPDATE:** The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.

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

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

sender: assistant

body:
What if you write

    yawData[3] = Serial2.read();
    yawData[2] = Serial2.read();
    yawData[1] = Serial2.read();
    yawData[0] = Serial2.read();

i.e. you change the endianness of the representation


message:
How to destroy my Arduino with I/O pins?

What are the most common ways of destroying a Arduino using the I/O pins?

Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

body:
> What are the most common ways of destroying a Arduno using the I/O pins?

Over-voltage and over-current.

Over-voltage involves putting too high (or too low) a voltage onto an IO pin.  Over-current involves trying to source (or sink) too much current through an IO pin.  Both can be fatal.

> Also, in what situation would it be acceptable to attach the positive or negative end of a power supply to an I/O pin?

**"Positive":** When that power supply is no more than 5V and shares ground with the Arduino and you want to know if it's on or not, or measure the voltage (Analog Input).  Anything more than 5V will require a voltage divider to bring the voltage down to 5V.

**"Negative":** If by that you mean the ground terminal, and that ground terminal is shared with the Arduino ground, then you can do it any time - but why would you, since you'd just be connecting to the Arduino ground since they are one and the same. If it's not the ground terminal but a potential *below* ground, then never unless you use some circuitry to raise that potential above ground for measuring it.


body:
There are many ways to destroy an Arduino, check out this article, [10 Ways to Destroy An Arduino][1].

>  1. Shorting I/O Pins to Ground
>  2. Shorting I/O Pins to Each Other
>  3. Apply Overvoltage to I/O Pins
>  4. Apply External Vin Power Backwards
>  5. Apply >5V to the 5V Connector Pin
>  6. Apply >3.3V to the 3.3V Connector Pin
>  7. Short Vin to GND
>  8. Apply 5V External Power with Vin Load
>  9. Apply >13V to the Reset Pin
>  10. Exceed Total Microcontroller Current

  [1]: http://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


message:
Giving the impression of a dying device - making a vibrating motor slow down and stop

I'm trying to make a gag gift for a friend. The effect I'm trying to imitate is of a device that starts up for a moment and then putters out like something is wrong.

So I need it to:
1. Vibrate a motor for a second or two.
2. Make the vibration sputter out.
3. Light up an LED behind an error message on a paper screen.

I have very little hands on experience with anything electronic, but I have some programming and I took enough physics to know what a capacitor, etc is.

My questions are whether an Arduino is a good and cost effective way to accomplish this and is there any beginner friendly advice anyone can give me to get this accomplish

body:
You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led.
This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: <https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview>

Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: <https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d> )


message:
How to send volume +/- on Mac/OSX from Leonardo

I saw [this answer](https://arduino.stackexchange.com/questions/8934/send-keyboard-media-keys-with-keyboard-library) but I can't find the analog for Mac.

I've tried cycling thru keycodes from 0x01 thru maybe 0x500, and I went thru ascii a few times, also found brightness up/down, and `F11`, `F12`, but they get pressed **with fn key by default** which makes them do operations other than vol +/-.

body:
Unfortunately, `Fn` is hardware and it is handled internally by the keyboard to do something hardware-based without sending any code. So the short answer is: you can't simulate Fn key with arduino.

What I think of as a solution is:

* Create a program on your Mac that can listen for keyboard scan codes to do vol +/- or any other function.
* Send a custom scan code from Arduino to your Mac ( a scan code that isn't part of the standard scan codes ).
* When your listening program receives that code, it should do Vol +/- (or anything else )...


body:
Could you just untick the "Use all F1, F2, …" in System Preferences -> Keyboard?

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

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

Just wondering if that would be an option and if doing so would create the desired outcome.


message:
Is it possible for Arduino to send a message to the internet without using a GSM shield?

I need an Arduino to send a message, to be displayed on the web, after pressing a push button, which is connected to an Arduino [or shield], without using a GSM shield.

I need to send a message just by using HTML/PHP code included in the Arduino IDE. This displayed message should contain two buttons. One button is used to turn a LED ON/OFF and the other to open a streaming video.

Can anyone help me with the Arduino code and explain how I should do that? Is there any third party device, apart from a GSM shield, that can help me to send that message?

body:
Use this example to open a webpage using a push button, you need `Python` installed on your Windows.

**Step 01:**

Upload this sketch to your arduino:

    const int buttonPin = 2; // the number of the pushbutton pin
    int buttonState = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(buttonPin, INPUT);
    }

    void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH) {
      Serial.println("OpenWebPage");
      }
    }

**The Circuit:**

 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

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

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

**Step 02:**

Open a text editor and paste this code to a new file:

    import serial
    from subprocess import call

    ser = serial.Serial(
        port='COM5', # Change this to your COM port number
        baudrate=9600,
        parity=serial.PARITY_ODD,
        stopbits=serial.STOPBITS_TWO,
        bytesize=serial.SEVENBITS
    )

    if (ser.isOpen()):
     print "Serial Port is Open..."
     print "Waiting for a command ..."
     while 1:
      cmd = ser.readline()
      if cmd.strip() == "OpenWebPage":
       print "Received command from Arduino..."
       print "Opening webpage..."
       call(["explorer", "http://www.google.com"]) #change it the address you want

Save the file to your desktop, name it : `SerialListener.py`

**Step 03**

* Now open a Command Prompt window.
* Navigate to your desktop folder and execute this command: `python SerialListener.py`.
* You should see **Serial Port is Open... Waiting for a command ...**
* Press the push button, and a webpage should open in your default browser.


message:
ISR not working as it is supposed to

For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle).

I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small test program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs.  My code looks like following:

<!-- language: c -->

        #include <PinChangeInt.h>
        #define pw 3
        int pwm;

        void setup() {
          // put your setup code here, to run once:
          pinMode(pw, OUTPUT) ;
          pwm_setup();             // Set PWM to a frequency of 62.5kHz

          PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
          PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

          Serial.begin(9600);
        }

        void loop() {
          // put your main code here, to run repeatedly:
          pwm = 127;                                                // 50% duty cycle
          pwm_on(pwm);

        }
        void pwm_setup()
        {

          TCCR2A = 0x23 ;
          TCCR2B = 0x09 ; // mode 7, clock prescale by 1
          OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
          OCR2B =0 ;
          TCNT2 =0 ;

        }
        void pwm_on(double)
         {
            OCR2B = pwm ;
         }

        void rise()
        {
          Serial.println("RISE");
        }

    void fall()
    {
      Serial.println("fall");
    }

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.

Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can anyone point it out please ?

Your helpful comments and suggestions would be appreciated.
Thankyou!

body:
Here are a few items to consider.

1. From `#define pw 3` you are working with PD3, INT1.  As one of the Atmega328 Uno's two external interrupts, INT1 supports RISING and FALLING events separately.  Pin change interrupts (PCIs) on pins other than 2 or 3 of the Uno won't separate them and in the interrupt routine (one interrupt routine in that case, not two) you will need to test which occurs by reading the pin.

2. Serial communication depends on interrupts and won't work in an interrupt handler.  Instead, set a flag (via a volatile byte variable) to test in your `loop()`.

3.  For testing, put `pwm_on(pwm)` in `setup()` instead of `loop()`.

4. In `loop()`, compute `seconds = milli()/1000` and if `seconds != prevsec`, set prevsec=seconds, enable your PCI or external interrupt, then enter a loop that waits for a flag and takes a reading.  Or, in the interrupt handler, both set a flag and take a reading into a volatile variable.

5.  If you only need to measure the quantities a few times per second, or a few times per minute, you could just busy-wait for the condition, then trigger a sample-and-hold, then convert analog to digital via `analogRead()`.

Regarding sample-and-hold: Unless you change the ADC sampling rate, `analogRead()` will take up to 100 microseconds per reading.  If your input waveform is 62.5 KHz, it will toggle about about six times while being measured, which if measured directly is likely to give a random result.  However, if you use a sample-and-hold circuit, you can hold the ADC input constant until your measurement completes.

An alternative to using a sample-and-hold is changing the ADC sampling speed. See post #5 in thread [Faster Analog Read?](http://forum.arduino.cc/index.php?topic=6549.0) on forum.arduino.cc.  If you get the sample time down to 8 to 12 microseconds you can do ok with a busy-wait method.  Ie, when your code wants a reading, it has a loop that measures the PWM line over and over, and starts an ADC conversion shortly after the PWM gets to the state desired for the measurement.


message:
Modbus Communication protocol for Arduino as Slave

I have an Arduino Uno board, with these components:

* [rs-485 Modbus module shield][1]
* [Multiprotocol radio shield board for Arduino][2]

In addition I have a level sensor which reads either 1 when it is above water, and 0 when it is below.

I need to be able to give the value of this sensor to a modbus master over rs485.

[Cooking Hacks Tutorial][3]

This page has a description of how to use the ModbusMaster485 library, but I can not find any information about the slave library.

I can not find any documentation for this library, and would really appreciate any pointers.

  [1]: https://www.cooking-hacks.com/rs-485-modbus-module-shield-board-for-arduino-raspberry-pi-intel-galileo "rs-485 Modbus module shield"
  [2]: https://www.cooking-hacks.com/multiprotocol-radio-shield-board-for-arduino-rpi-intel-galileo "Multiprotocol radio shield board for Arduino"
  [3]: https://www.cooking-hacks.com/documentation/tutorials/modbus-module-shield-tutorial-for-arduino-raspberry-pi-intel-galileo/ "Cooking Hacks Tutorial"

body:
It's not very well documented for the slave but maybe that is because it only has two methods...

It looks like the slave library is contained in the same library as the master but with name `ModbusSlave485.h`

You can see in the .h it only has two public methods. One is `connfigure()` and the other is `update()`. see below an extract from the .h which explains what each method does.

    #include "ModbusSlave485.h"

    mySlave = ModbusSlave485();

    void setup()
    {
      mySlave.configure(slave, baud, parity, txenpin);
    }

    void loop()
    {
      //check for update from master
      mySlave.update(regs, regs_size)
    }

extract from .h

    /*
     * configure(slave, baud, parity, txenpin)
     *
     * sets the communication parameters for of the serial line.
     *
     * slave: identification number of the slave in the Modbus network (1 to 127)
     * baud: baudrate in bps (typical values 9600, 19200... 115200)
     * parity: a single character sets the parity mode (character frame format):
     *         'n' no parity (8N1); 'e' even parity (8E1), 'o' for odd parity (8O1).
     * txenpin: arduino pin number that controls transmision/reception
     *        of an external half-duplex device (e.g. a RS485 interface chip).
     *        0 or 1 disables this function (for a two-device network)
     *        >2 for point-to-multipoint topology (e.g. several arduinos)
     */
      void configure(unsigned char slave, long baud);

    /*
     * update(regs, regs_size)
     *
     * checks if there is any valid request from the modbus master. If there is,
     * performs the requested action
     *
     * regs: an array with the holding registers. They start at address 1 (master point of view)
     * regs_size: total number of holding registers, i.e. the size of the array regs.
     * returns: 0 if no request from master,
     *  NO_REPLY (-1) if no reply is sent to the master
     *  an exception code (1 to 4) in case of a modbus exceptions
     *  the number of bytes sent as reply ( > 4) if OK.
     */
      int update(int *regs, unsigned int regs_size);

      // constructor
      ModbusSlave485()
      {
     myDevice = RS485();
      }


message:
Python script to toggle LED's

I have 8 LED's connected to a shift register on my arduino uno r3. I am trying to write a Python3 script that will prompt a user to select one of the LED's and then prompt to toggle on or off.

Should be pretty basic but I cant seem to get this working.

I have already botched my code trying to get this running:

the jist of my python script is

    import serial
    import os
    import time

    os.system('clear')

    ser = serial.Serial('/dev/cu.usbmodem1431', 9600)

    while True:
        led = input("Which LED do you wish to operate? (press x to quit): ")

        if led >= '0' and led <= '7':
            print("Operating LED # %s" % led)
            ser.write(str.encode(led)) # sends the choice of led to arduino'
            on_or_off = input("Do you want to turn it on or off (press 0 for off and 1 for on): ")

            if on_or_off == '0':
                #send command to arduino to turn off the selected LED
                print("Command sent to arduino to turn OFF LED %s" % led)
                ser.write(str.encode(on_or_off))
            elif on_or_off == '1':
                #send command to arduino to turn on the selected LED
                print("Command sent to arduino to turn ON LED %s" % led)
                ser.write(str.encode(on_or_off))
            else:
                print("Please enter 0 or 1 to operate the LED. ")

        elif led == 'x':
            ser.close()
            break
        else:
            continue

For some reason Arduino is only dealing with the first input...

HEre is my loop code on the arduino

    void loop() {
      if(Serial.available() > 0){
        led = Serial.read(); // from python script the led to operate
        led = led - '0';
        if(led >= '0' && led <= '7'){
          if(Serial.available() > 0){
            ledState = Serial.read(); // expects the led state next
            ledState = ledState - '0';
            if(ledState == '0'){
              shiftWrite(led,LOW);
            }else if(ledState == '1'){
              shiftWrite(led,HIGH);
            }
          }
        }
      }
    }

shiftWrite is a function I wrote because there are 8 LEDS hooked to a shiftRegister

***update:***

I tried the state machine suggestion and it didnt work...

      void loop() {
      while(Serial.available()){
        led = Serial.read();
        led = led - '0';
        if(led>= 0 && led <= 7){
          state = 1; //We've received the LED # go to state 1
          Serial.println(led);
          Serial.println(state);
          Serial.println(ledState);
          continue;
        }
        if(state == 1){
          ledState = Serial.read();
          ledState = ledState - '0';
          if(ledState == '0'){
            shiftWrite(led,LOW);
          }else if(ledState == '1'){
            shiftWrite(led,HIGH);
          }
          state = 0; //Ended the operation return to state 0
        }
      }
    }

With the serial monitor in the arduino IDE open (not running the python script) I tried this input: 4,1

This is my output on the serial monitor:

    4
    1
    0
    1
    1
    0

Any ideas? Basically the same problem as before...I actually thought the state machine idea would work...

body:
You're assuming that the microcontroller is going to wait until you choose LED state, which is wrong. Try this:

    int state = 0;
    int led;
    int ledState;

    void loop() {
      while (Serial.available())
      {
        if (state == 0)
        {
          led = Serial.read() - '0';
          if(led >= 0 && led <= 7)
          {
            state = 1; // Here we have got the LED number, go to state 1
            continue;
          }
        }
        if (state == 1)
        {
            ledState = Serial.read() - '0';
            if(ledState == 0)
            {
              shiftWrite(led,LOW);
            }
            else if(ledState == 1)
            {
              shiftWrite(led,HIGH);
            }
            state = 0; // Here we ended the operation, return back to state 0
        }
      }

    }

You need what we call a state machine, here I use `state=0` for the state corresponding to choosing LED number, `state=1` is for the state that waits for the operation ON/OFF.


body:
Try this code, it is working as intended:

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

    int state = 0;
    int led;
    int ledState;

    void loop() {

      while (Serial.available())
      {
        if (state == 0)
        {

          led = Serial.read() - '0';
          if(led >= 0 && led <= 7)
          {
            state = 1;
            Serial.println("Got LED number: " + String(led));
            break;
          }
        }
        if (state == 1)
        {
            ledState = Serial.read() - '0';
            if(ledState == 0)
            {
              Serial.println("LED n " + String(led) + " is now OFF");
            }
            else if(ledState == 1)
            {
              Serial.println("LED n " + String(led) + " is now ON");
            }
            state = 0;
        }
      }

    }


message:
How to change SIM908 GPS location coordinates format?

I am using the SIM908 module to get GPS position.

The SIM908 sends the latitude and longitude in the `ddmm.mmmm` format, but major online services for GPS location (for example, Google Earth) use the `dd.dddd` format.

So, how can I modify my code to convert coordinates from the SIM908 to `dd.dddd` format?

This is the SIM908 GSM Library Code that I am using:

    #include "gps.h"
    char GPSGSM::getBattInf(char *str_perc, char *str_vol)
    {
         char ret_val=0;
         char *p_char;
         char *p_char1;

         gsm.SimpleWriteln("AT+CBC");
         gsm.WaitResp(5000, 100, "OK");
         if(gsm.IsStringReceived("+CBC"))
              ret_val=1;

         //BCL
         p_char = strchr((char *)(gsm.comm_buf),',');
         p_char1 = p_char+1;  //we are on the first char of BCS
         p_char = strchr((char *)(p_char1), ',');
         if (p_char != NULL) {
              *p_char = 0;
         }
         strcpy(str_perc, (char *)(p_char1));

         //Voltage
         p_char++;
         p_char1 = strchr((char *)(p_char), '\r');
         if (p_char1 != NULL) {
              *p_char1 = 0;
         }
         strcpy(str_vol, (char *)(p_char));
         return ret_val;
    }

    char GPSGSM::getBattTVol(char *str_vol)
    {
         char *p_char;
         char *p_char1;
         char ret_val=0;

         gsm.SimpleWriteln("AT+CBTE?");
         gsm.WaitResp(5000, 100, "OK");
         if(gsm.IsStringReceived("+CBTE"))
              ret_val=1;

         //BCL
         p_char = strchr((char *)(gsm.comm_buf),':');
         p_char1 = p_char+2;  //we are on the first char of BCS
         p_char = strchr((char *)(p_char1), '\r');
         if (p_char != NULL) {
              *p_char = 0;
         }
         strcpy(str_vol, (char *)(p_char1));
         return ret_val;
    }

    char GPSGSM::attachGPS()
    {
         if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=1", 500, 100, "OK", 5))
              return 0;
         if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSRST=1", 500, 100, "OK", 5))
              return 0;
         return 1;
    }

    char GPSGSM::deattachGPS()
    {
         if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=0", 500, 100, "OK", 5))
              return 0;
         return 1;
    }

    char GPSGSM::getStat()
    {
         char ret_val=-1;
         gsm.SimpleWriteln("AT+CGPSSTATUS?");
         gsm.WaitResp(5000, 100, "OK");
         if(gsm.IsStringReceived("Unknown")||gsm.IsStringReceived("unknown"))
              ret_val=0;
         else if(gsm.IsStringReceived("Not"))
              ret_val=1;
         else if(gsm.IsStringReceived("2D")||gsm.IsStringReceived("2d"))
              ret_val=2;
         else if(gsm.IsStringReceived("3D")||gsm.IsStringReceived("3d"))
              ret_val=3;
         return ret_val;
    }

    char GPSGSM::getPar(char *str_long, char *str_lat, char *str_alt, char *str_time, char *str_speed )
    {
         char ret_val=0;
         char *p_char;
         char *p_char1;
         gsm.SimpleWriteln("AT+CGPSINF=0");
         gsm.WaitResp(5000, 100, "OK");
         if(gsm.IsStringReceived("OK"))
              ret_val=1;

         //longitude
         p_char = strchr((char *)(gsm.comm_buf),',');
         p_char1 = p_char+1;  //we are on the first char of longitude
         p_char = strchr((char *)(p_char1), ',');
         if (p_char != NULL) {
              *p_char = 0;
         }
         strcpy(str_long, (char *)(p_char1));

         // latitude
         p_char++;
         p_char1 = strchr((char *)(p_char), ',');
         if (p_char1 != NULL) {
              *p_char1 = 0;
         }
         strcpy(str_lat, (char *)(p_char));

         // altitude
         p_char1++;
         p_char = strchr((char *)(p_char1), ',');
         if (p_char != NULL) {
              *p_char = 0;
         }
         strcpy(str_alt, (char *)(p_char1));

         // UTC time
         p_char++;
         p_char1 = strchr((char *)(p_char), ',');
         if (p_char1 != NULL) {
              *p_char1 = 0;
         }
         strcpy(str_time, (char *)(p_char));

         // TTFF
         p_char1++;
         p_char = strchr((char *)(p_char1), ',');
         if (p_char != NULL) {
              *p_char = 0;
         }

         // num
         p_char++;
         p_char1 = strchr((char *)(p_char), ',');
         if (p_char1 != NULL) {
              *p_char1 = 0;
         }

         // speed
         p_char1++;
         p_char = strchr((char *)(p_char1), ',');
         if (p_char != NULL) {
              *p_char = 0;
         }
         strcpy(str_speed, (char *)(p_char1));

         return ret_val;
    }

    void parseTime(char *field, int *time)
    {
         ////////////////Time////////////
         char tmp[4];
         tmp[2]=0; // Init tmp and null terminate
         tmp[0] = field[8];
         tmp[1] = field[9];
         time[0] = atoi(tmp); // Hours
         tmp[0] = field[10];
         tmp[1] = field[11];
         time[1] = atoi(tmp); // Minutes
         tmp[0] = field[12];
         tmp[1] = field[13];
         time[2] = atoi(tmp); // Seconds
         /////////////Date///////////////
         tmp[0] = field[0];
         tmp[1] = field[1];
         tmp[2] = field[2];
         tmp[3] = field[3];
         tmp[4]=0; // Init tmp and null terminate
         time[3] = atoi(tmp); // year
         tmp[0] = field[4];
         tmp[1] = field[5];
         tmp[2]=0; // Init tmp and null terminate
         time[4] = atoi(tmp); // month
         tmp[0] = field[6];
         tmp[1] = field[7];
         tmp[2]=0; // Init tmp and null terminate
         time[5] = atoi(tmp); // day
    }

    // Read the latitude in decimal format from a GGA string
    double convertLat(char* latString)
    {
         double latitude = atof(latString);                                    // convert to a double (precise)
         int deg = (int) latitude / 100;                               // extract the number of degrees
         double min = latitude - (100 * deg);                  // work out the number of minutes
         latitude = deg + (double) min/60.0;                   // convert to decimal format
         return latitude;
    }

    // Read the longitude in decimal format from a GGA string
    double convertLong(char* longString)
    {
         double longitude = atof(longString);                                  // convert to a double
         int deg = (int) longitude / 100;                              // extract the number of degrees
         double min = longitude - (100 * deg);                 // work out the number of minutes
         longitude = deg + (double) min/60.00;                 // convert to decimal format
         return longitude;
    }

body:
This could be a general programming question. The only thing specific to
Arduino here is that you may want a solution that minimizes the use of
memory and avoids floating point operations.

Here is a memory-friendly solution that reformats the string _in place_,
i.e. it overwrites the original string. In many cases this is
appropriate, as it is unlikely that you need the original string later,
but you have to make sure it fits your application. It works by first
moving a few characters around in order to have the format "dd.mmmmm",
then parsing the minutes and converting to fractional degrees, then
writing that in ASCII.

It should be noted that the only reason for dropping the last digit in
the minutes field is to avoid 32-bit operations. I compiled for an Uno
and checked the generated assembly: it uses only four bytes of RAM, in
the stack.

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

    // Convert the format of a latitude from "ddmm.mmmm" to "dd.dddd".
    // The string is converted in place.
    void convertLat(char* s)
    {
        // Convert ddmm.mmmm to dd.mmmmm
        s[4] = s[3];  // move minutes
        s[3] = s[2];  // move tens of minutes
        s[2] = '.';   // put decimal point
        s[8] = '\0';  // drop last digit

        // Compute fractional degrees.
        uint16_t fraction = atoi(s + 3);  // unit = 1e-3 arcmin
        fraction /= 6;                    // unit = 1e-4 deg

        // Write in ASCII, right to left.
        s[7] = '\0';
        for (int i = 6; i > 2; i--) {
            s[i] = fraction % 10 + '0';
            fraction /= 10;
        }
    }

You can use this same function to convert a longitude from "dddmm.mmmm"
to "ddd.dddd" by just skipping the first character:

    static inline void convertLon(char* s)
    {
        convertLat(s + 1);
    }

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

**Addendum**: To answer Lipsyor comment, it is possible to have the
latitude in units of 1e-6 deg by using 32-bit arithmetic:

    // Convert the format of a latitude from "ddmm.mmmm" to "dd.dddddd".
    // The string is converted in place.
    void convertLat(char* s)
    {
        // Convert ddmm.mmmm to dd.mmmmmm
        s[4] = s[3];  // move minutes
        s[3] = s[2];  // move tens of minutes
        s[2] = '.';   // put decimal point

        // Compute fractional degrees.
        uint32_t fraction = atol(s + 3);     // unit = 1e-4 arcmin
        fraction = (fraction * 10 + 3) / 6;  // unit = 1e-6 deg

        // Write in ASCII, right to left.
        for (int i = 8; i > 2; i--) {
            s[i] = fraction % 10 + '0';
            fraction /= 10;
        }
    }

The `+ 3` in the computation is only to round to nearest. Dropping this
term should not make any significant difference.


message:
LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch

I've been playing with an Arduino Uno, trying to get a 16x2 LCD screen to work with an I2C controller. I've got [this][1] LCD screen and [this][2] controller. And I've been trying to get the sketch below to work.

    #include <Wire.h>
    #include <LCD.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);//, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    void setup()
    {
        lcd.begin(16,2);
        lcd.backlight();
        lcd.setCursor(0, 0);
        lcd.print("Hello world!");
        lcd.setCursor(0, 1);
        lcd.print("Row number: ");
        lcd.setCursor(12, 1);
        lcd.print("2");
    }
    void loop()
    {

    }

I've used an address scanner to verify that the address is correct (39 [0x27]), but it still won't display anything. It lights up, and I've tried adjusting the contrast, but it just won't display any characters.

I'm wondering if the definition of which pins are which is correct, but I can't seem to find anything detailing how the numbers used in the sketch correlate to the pins on the controller, which then correlate to the pins on the LCD screen. If any body can give me some insight I'd appreciate it.

  [1]: http://www.amazon.com/gp/product/B00HICXURS?psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00
  [2]: http://www.amazon.com/gp/product/B00FIVUVBY?psc=1&redirect=true&ref_=oh_aui_detailpage_o01_s00
  [3]: https://github.com/futureshocked/arduino_sbs/blob/master/LCD Single Wire/LCD_Single_wire_Demo_1/LCD_Single_wire_Demo_1.ino

body:
Yes, the pins can be different depending on the LCD and the controller. My favorite solution to this is to run a simple "i2c guesser" sketch that can be downloaded from the following forum thread (download link is at the bottom of the first post):
http://forum.arduino.cc/index.php?topic=260510.0

With that sketch it usually only takes me a couple minutes to find the correct pin numbers.


message:
Arduino Part Needs Identified

[![I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help! ][1]][1]

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

I do not know what part this is. I ordered an Arduino beginners kit and this part was not labeled. Please help!

body:
It seems that it is an MPU6050 Module 3 Axis Accelerometer Gyroscope Module for Arduino.

Learn more: http://playground.arduino.cc/Main/MPU-6050

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

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


message:
How to connect MCP4141 digipot and a data logger shield to the same Arduino board

The main problem here is that they both need to communicate via the Arduino's SPI bus, and I know that each of the two devices will need its own CS pin (The data logger is hard wired to 10, so the digital potentiometer will need a different one)

This would be fine, except that the digital potentiometer has one pin for both SPI and SDO.
I read that to connect this to the Arduino, the shared pin on the digipot needs to be connected to the MISI pin on the Arduino (pin 12) and then to bridge the MISO pin to the MOSI pin with a resistor.

Would anyone be able to tell if this will work. I do not want to try connecting the two devices like this just in case it breaks something in the board.

Thanks

body:
I have done the same thing in the past for a DS1302 RTC that uses the same communication system.  Yes, it works.  Will it interfere with the other communication though? Quite possibly.  It works fine for *half duplex* communication, but could cause interference with something else on the bus that is *full duplex*.

If in doubt, and you're not worried about high speed or high efficiency (you're not changing the potentiometer's value often) then use three other pins and bit-bang your own half duplex serial interface - it's not hard.


message:
Diode lights generate false interruptions

I have spent quite a considerable time debugging my code that was triggering false interruptions. I have found out that the source of the error were the diode lights (on the picture). I would like to ask if anyone can point me to the possible source of such behaviour.

I will try to explain really briefly what the issue was providing only needed (from my point of view) details. If you would require more - tell me.

So, I have a board that looks like this:
[![circuit][1]][1]

You can see two reed switches (close circuit in the presence of a magnet) which leads the `INT0` (pin 2) and `INT1` (pin 3) on arduino to trigger an interruption on their `RISING` behaviour. The pull down resistors are 1kOhm. This cirquit works perfectly.

The original version of this circuit had lights in positions `D5-D10` and `D19-D24` (between the reed switches and the connections to the interruptor pins). The lights are these:
[![diod lights][2]][2]

The part of the circuit with the red light (connected to `INT1`) worked flawlessly, while the circuit with the green light (connected to `INT0`) every once in a while triggered a false interruption in `INT1`. The lights, however were always blinking correctly.

I have nearly no experience with circuits and hardware, so a pointer on where to start reading to understand the issue is also welcome. Hope to hear from someone who knows what the cause could have been. I would still like to use the lights somehow, because they give a nice feedback on what is happening to the system.

Thanks!

PS. I do not think the code is necessary here, but I will post it too if you like. I am however quite confident that the bug is not on the software side.

  [1]: https://i.stack.imgur.com/SSv38.png
  [2]: https://i.stack.imgur.com/mhMrqm.jpg

body:
Aaaaah, ok, now I see...

You put

> +5V - Reed - LED - input pin - 1k resistor - ground

right?

If so the problem is that a red led has (usually) a voltage drop of about 1.5V, while the green one has a voltage drop of 1.8V-2.0V. The Atmega 328P has a Vih (i.e. the minimum voltage needed for a reliable high) of 0.6*Vcc, so for a 5V supply this value is 3V.

Consequently with a green LED you will have a value TOO CLOSE to the minimum acceptable value for the input pin. Note that the 2.0V value is an usual one, but different leds have different voltages.

Moreover the so-called high-brightness leds (the ones with a transparent case) have a more-than-3V voltage drop, so if you put for instance a blue led you will never receive a signal.

To solve the problem, you have three solutions:

1) use a (low brightness) red led also for the green path
2) remove the led from that path and drive it directly with the arduino (you will have also the notification that arduino has understood the command)
3) change the path to

> +5V - Reed - input pin - LED - 1k resistor - ground

(i.e. take the voltage BEFORE the led, not after)

I think it'll work then :)

EDIT: according to the data I found on the internet the red led is usually 1.8V, while the green one is usually 2.1V. This does not change my answer, anyway.

And... You won't "fry" your pins with the 5V you are prividing to the circuit....


message:
Problem with for loop

I'm having trouble with the syntax of code. I want to have the motor turn when the next average the program measures is 100 or more greater than the previous average it measured. I don't know how to write the if statement:

    if(average == (average>=100)) {
    for(pos = 0; pos <= 120; pos += 1) {
      sServo.write(pos);
      delay(50);
    }
    for(pos = 120; pos >= 0; pos -= 1) {
      sServo.write(pos);
      delay(50);
    }
    }

body:
The motor should

> turn when the next average the program measures is 100 or more greater than the previous average it measured

So simply write it:

    // Old average is called "average"
    // Compute the new average and put it in next_average
    if ((next_average - average) >= 100)
    {
      // Turn the motor
    }
    average = next_average;


message:
A question about Continuous Rotation Servo and Arduino

We have this project that uses a Continuous Rotation Servo and we have a slight problem controlling it. We're planning to attach a Rack Gear to the Servo to slide a stainless steel to the right, and vice versa.

**The Question:** Is it possible to stop the continuous rotation servo when the stainless steel hits a bump or it already made its proper position accurately?

This idea is like the Power Windows of cars.

body:
You can track the servo rotation with an encoder and after reaching a specific position, you can send different instructions to execute other actions.

Other alternative is maybe you can place a limit switch at the position where you want it to stop.


body:
The way that power windows detect fully open or closed is typically by measuring the motor current:  When a motor is stalled it's current increases because there is no longer any back-emf as there is when the magnetic fields are rotating.  You can measure this current and then stop when you see it increase over the running current.

This is especially useful in the context of the window example as limit switches would have to be set EXACTLY at the closed position which is hard to do and if they fail or get out of alignment can lead to burned out motors if the limit switch is set beyond the physical travel limit.  Furthermore, an obstruction will result in a burned out motor even if the limit switch is correctly set as the window could never reach its limit position.  In these two cases, a timeout would need to be included as a backup (A timeout is not a bad idea in any case!).


message:
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

So I try to compile and upload a simple code such as the Basic Blink.
I have not connected it to pin 0 or pin 1.

There is an LED with the "L" label on the card that works. So I guess not the chip is damaged?

I have selected the correct model which is Arduino Uno / Genuino. I've checked the drivers several times now, even reinstalled Arduino Software twice and tried on 2 different computers.

5V works with ground, I can get the LED to light up. But I cannot compile / upload code.

    Error MSG: avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    (this message repeats 10 times with attempts)

I read something about bootloader, but I have no idea how to do this / what it is. I do not have the right components for bootloading I guess.

Also the COM is correct. I've tried using all the listed COMs without any result. Is this a hardware issue? Is my chip grilled or something?

body:
You should re-burn the bootloader. If you have another uno, you can burn bootloader [here][1]

  [1]: https://tutorial.cytron.io/2015/02/04/using-isp-burn-bootloader-arduino/


message:
433MHz sending not receiving

I'm trying to send data using [these][1] cheap parts.
When I check the voltage on the data port of the transmitter, I see what I expect, 1.2 and 0.6 fluctuating while sending.
But when I check the receiver I get 0. I've got 3 of the sets and tried them all. Also tried it with running the transmitter on 11V for some extra power. I've added a LED to the transmitter to see when it transmits and I've added a not-so-good antenna to both while they are only 5cm apart during my tests.

Any advice would be appreciated.

**Receiver**
FS1000A with a LR433A

    #include <VirtualWire.h>

    const int led_pin = 6;
    //const int transmit_pin = 12;
    const int receive_pin = 11;
    //const int transmit_en_pin = 3;

    void setup()
    {
        delay(1000);
        Serial.begin(9600);  // Debugging only
        Serial.println("setup");

        // Initialise the IO and ISR
        //vw_set_tx_pin(transmit_pin);
        vw_set_rx_pin(receive_pin);
        //vw_set_ptt_pin(transmit_en_pin);
        //vw_set_ptt_inverted(true); // Required for DR3100
        vw_setup(1000);  // Bits per sec

        vw_rx_start();       // Start the receiver PLL running
    }

    void loop()
    {
        uint8_t buf[VW_MAX_MESSAGE_LEN];
        uint8_t buflen = VW_MAX_MESSAGE_LEN;

        if (vw_get_message(buf, &buflen)) // Non-blocking
        {
      int i;

            digitalWrite(led_pin, HIGH); // Flash a light to show received good message
      // Message with a good checksum received, print it.
      Serial.print("Got: ");

      for (i = 0; i < buflen; i++)
      {
          Serial.print(buf[i], HEX);
          Serial.print(' ');
      }
      Serial.println();
            digitalWrite(led_pin, LOW);
        }
    }

**Transmitter**

    #include <VirtualWire.h>

    const int led_pin = 11;
    const int transmit_pin = 12;
    const int receive_pin = 2;
    const int transmit_en_pin = 3;

    void setup()
    {
      // Initialise the IO and ISR
      vw_set_tx_pin(transmit_pin);
      vw_set_rx_pin(receive_pin);
      vw_set_ptt_pin(transmit_en_pin);
      vw_set_ptt_inverted(true); // Required for DR3100
      vw_setup(1000);   // Bits per sec
    }

    byte count = 1;

    void loop()
    {
      char msg[7] = {'h','e','l','l','o',' ','#'};
      Serial.println("sending");
      msg[6] = count;
      digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
      vw_send((uint8_t *)msg, 7);
      vw_wait_tx(); // Wait until the whole message is gone
      digitalWrite(led_pin, LOW);
      delay(1000);
      count = count + 1;
    }

[![transmitter][2]][2]
[![receiver][3]][3]

  [1]: http://www.ebay.com/itm/221524421949
  [2]: https://i.stack.imgur.com/ZLAIw.jpg
  [3]: https://i.stack.imgur.com/xQiju.jpg

body:
If you are not getting anything on the receiver, then the receiver is definitely the problem. These units will boost the gain until it get some signal, any signal.

You should be able to power the receiver + and GND (I have one, which ran on 5v, I can't see if these are the same), and put a multimeter from GND to Data, and you should get about half of Vcc, probably fluctuating a bit. If you look at the same with an oscilloscope, it should fluctuating wildly between 0 and Vcc volts. All of this should work without a transmitter, and without an Arduino (you will need a power supply for the receiver).

Note: this is from memory, I don't have mine here to test.

Once you are getting "random data" (background noise), you can progress to sending a signal.

Note that you should keep your "1"s and "0"s balanced to get a clear signal - check out Manchester encoding (this encodes a "1" as "1,0", and a 0 as "0,1", so there will be a perfect balance). You might also want to send a 1010101010 at the start - this gives the receiver a chance to adjust the gain to the correct level. Or, you can use some width-based encoding (e.g. "slow 1, slow 0" for a "1", and "fast 0, fast 1" for a "0").


body:
What I thought was the receiver turned out to be the transmitter. I've earned my noob medal now :)
The chip with the LR433A on it is the sending unit.

The code above and the wiring is all good!


message:
Can I safely integrate 3,3v sensor with 5v Arduino UNO? How?

I plan to use [Adafruit's RGB sensor][1] with Arduino working as a RGB controller running on 5V. In my location, [the 5V-compatible version of the sensor][2] is not available.

There is a 3,3V pin on my Arduino board. Can I use it to power the sensor, or will the data pins (which are rated 5V) still burn it?

The TCS34725 chip uses I2C communication, which arguably would still be compatible with the 5V (http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter)

I am still very new to the electronics, and I don't feel confident enough to build my own level converter, and sadly, no converters advertised on [arduino.cc][3] are available in my country (Poland).

  [1]: https://www.adafruit.com/products/1356
  [2]: https://www.adafruit.com/products/1334
  [3]: http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter

body: You can use "logic level converter bidirectional," to connect modules with different voltage requirements. They are pretty cheap.


body:
If you need I2C the best solution is go for a logic level converter based on BSS138 mosfet or similar. I've used a few and they never let me down. Examples: Sparkfun have this https://www.sparkfun.com/products/12009 and Adafruit http://www.adafruit.com/products/757

![](https://cdn.sparkfun.com//assets/parts/8/5/2/2/12009-07.jpg)

if you have also a few transistors available, you can make your own homemade solution till you get something more robust, according to arduino page: https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter

[![][1]][1]
<sub>(source: [arduino.cc](https://playground.arduino.cc/uploads/Main/i2c-level-shifter-transistors.png))</sub>

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


message:
sending ctrl-z in a struct?

I have a set of buttons wired to an arduino leonardo that are meant to send either single keystrokes to a computer "a, b, c..." etc, or a key sequence like ctrl+z (to perform an undo command.) Effectively this is a little usb keyboard with pre defined buttons. The way the struct is now, I can only manage to send one keystroke, never a modifier key+letter like I need.

The full code is listed here under "working code": https://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin

It just debounces the buttons and sends back actions (just single letters right now) using the ones defined in the struct. (thanks very much jwpat7)

The part in question is this

    struct ButtonStruct buttons[nSwitches] = {
      {0, sw0, 'A'},
      {0, sw1, 'B'},
      {0, sw2, 'C'},
      {0, sw3, 'D'},
      {0, sw4, 'E'},
      {0, sw5, 'F'},
      {0, sw6, 'G'},
      {0, sw7, 'H'}};

I effectively want to replace the 'A' in {0, sw0, 'A'} to something that sends ctrl+z keystroke/keysequence instead of the letter 'A'.

I've tried KEY_LEFT_CTRL, setting a variable like char ctrlKey = KEY_LEFT_CTRL; and trying {0, sw0, ctrlKey, 'z'}, the "substitution" hex here: http://www.nthelp.com/ascii.htm and a number of other things.

I've read through a lot and I can't seem to find anything relevant. I've been told it's possible to use pointers to create a key-sequence but a -> operand in there just throws errors. I'm new and I realize I might have a core principal wrong, but isn't there some simple syntax to send a ctrl+z command (and then releasing it obviously) using that space? When I put {0, sw0, KEY_LEFT_CTRL, 'z'} it just reports "Lz", using the last letter in KEY_LEFT_CTRL instead of treating it as a modifier.  I'm so confused

(Also right now one press = one character and doesn't continually report like holding down a key on a regular keyboard.  I'd like to fix that too but I'd settle for just a bloody ctrl+z at this point.)

**EDIT**: Current Code (compiled!)

        enum { sw0=2, sw1=3, sw2=4, sw3=5, sw4=6, sw5=7, sw6=8, sw7=9}; // Switchbutton lines
    enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
    struct ButtonStruct {
      unsigned long int bounceEnd;  // Debouncing-flag and end-time
      // Switch number, press-action, release-action, and prev reading
      byte swiNum, swiActP, charMod, swiActR, swiPrev;
    };

    struct ButtonStruct buttons[nSwitches] = {
      {0, sw0, 'z',  KEY_LEFT_CTRL},
      {0, sw1, 'B'},
      {0, sw2, 'C'},
      {0, sw3, 'D'},
      {0, sw4, 'E'},
      {0, sw5, 'F'},
      {0, sw6, 'G'},
      {0, sw7, 'H'}};
    //--------------------------------------------------------
    void setup() {
      for (int i=0; i<nSwitches; ++i)
        pinMode(buttons[i].swiNum, INPUT_PULLUP);
    Keyboard.begin();
    }
    //--------------------------------------------------------
    byte readSwitch (byte swiNum) {
      // Following inverts the pin reading (assumes pulldown = pressed)
      return 1 - digitalRead(swiNum);
    }
    //--------------------------------------------------------
    void doAction(byte swin, char code, char tosend, char chmodi) {

    if (chmodi) {    // See if modifier needed
       Keyboard.press(chmodi);
       Keyboard.press(tosend);
       delay(100);
       Keyboard.releaseAll();
    } else {
       Keyboard.write(tosend);
    }
    }
    //--------------------------------------------------------
    void doButton(byte bn) {
      struct ButtonStruct *b = buttons + bn;
      if (b->bounceEnd) { // Was button changing?
        // It was changing, see if debounce time is done.
          if (b->bounceEnd < millis()) {
        b->bounceEnd = 0;    // Debounce time is done, so clear flag
        // See if the change was real, or a glitch
        if (readSwitch(b->swiNum) == b->swiPrev) {
          // Current reading is same as trigger reading, so do it
          if (b->swiPrev) {
            doAction(b->swiNum, 'P', b->swiActP, b->charMod);
          }
        }
          }
      } else {  // It wasn't changing; but see if it's changing now
        if (b->swiPrev != readSwitch(b->swiNum)) {
          b->swiPrev = readSwitch(b->swiNum);
          b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
        }
      }
    }
    //--------------------------------------------------------
    long int seconds, prevSec=0;
    void loop() {
      for (int i=0; i<nSwitches; ++i)
        doButton(i);
    }

body:
<strike>First off, consider trying '\032' or '\x1A' for the ctrl-z.  (See, eg, *[How to send ctrl+z in C](https://stackoverflow.com/q/16132971)* on stackoverflow.)</strike>

To send a ctrl-z, use something like:

    Keyboard.press(ctrlKey);
    Keyboard.press('z');
    delay(100);
    Keyboard.releaseAll();

For more examples of using modifier keys, see the [KeyboardPress](https://www.arduino.cc/en/Reference/KeyboardPress) page at arduino.cc, and the example program `KeyboardLogout.ino`.  [To coordinate this with the `struct` data structure approach, you could use code somewhat like

    tosend = b->actionChar1;
    if (tosend < ' ') {    // See if modifier needed
       Keyboard.press(ctrlKey);
       Keyboard.press(tosend+96); // or is it 64?
       delay(100);
       Keyboard.releaseAll();
    } else {
       Keyboard.write(tosend);
    }

[You'll need to test which offset, 96 or 64, works in the above code; I don't have a Leonardo or similar to run this on, and haven't looked at the Keyboard library source to see how it treats this.]  Another way is to add a modifier-byte field in the `struct`, and issue it if its non-zero.]

Second, suppose the current form of `ButtonStruct` is analogous to

    struct ButtonStruct {
      unsigned long int bounceEnd;  // Debouncing-flag and end-time
      // Switch number, press-action and prev reading
      byte swiNum, actionChar1, swiPrev;
    };

where `actionChar1` is the action character in use now.  You could add another byte to the `struct`, say `actionChar2`, and after a statement like `Keyboard.write(b->actionChar1);` add the following:

    if (b->actionChar2)
      Keyboard.write(b->actionChar2);

which says to write out `actionChar2` if it is non-zero.

In some of the questions linked to the previous question, you may see advice that `Keyboard.write` won't send non-printing characters.  I don't know if that's so, but in any case, there are mods available for `Keyboard` (ie, changes to the library) that allow non-printing characters and special characters to be sent.

Also note, if your program gets close to using all the RAM memory, you may want to keep `buttons[]` in ProgMem and access it from there so it doesn't need to be copied into RAM.  (See the three ProgMem questions that are linked in the top right sidebar [.](https://arduino.stackexchange.com/q/13545)  [.](https://arduino.stackexchange.com/q/14250) [.](https://arduino.stackexchange.com/q/16012))   If you change the struct to use strings instead of single chars for its actions, using less RAM will increase in importance.

*Edit* re:  “what I don't know how to change ---> {0, sw0, 'A'}”:

`{0, sw0, 'A'}` initializes an element of `buttons[]`.
In `buttons[]`, each element is a `ButtonStruct`, because `buttons[]` is an array of `ButtonStruct`s.  (For more about structs, see syntax and examples in eg [Struct (C programming language)](https://en.wikipedia.org/wiki/Struct_(C_programming_language)#Declaration) in wikipedia.)

You control what information can be in each element of `buttons[]` by modifying the definition of `ButtonStruct`.  If you need more data items in each `buttons[]` entry, then add more data items in the definition of `ButtonStruct`.  Likewise for fewer.

After you decide what information you need to have available to process a button press, modify `ButtonStruct` to contain exactly that information.  It may be that some information will apply in some cases but not in all.  If so, when you initialize `buttons[]`, have some value (say 0) that stands for not-used, and fill in not-used spots with that value.

For example, if you need key modifiers (shift, ctrl, alt) add a modifier item to `ButtonStruct`.

Whenever you change `ButtonStruct`, you need to change `buttons[]` initialization to match.  For example, if `ButtonStruct` were to include [Keyboard Modifiers](https://www.arduino.cc/en/Reference/KeyboardModifiers) and looked like

    struct ButtonStruct {
      // Switch number, press-actions and prev reading
      byte swiNum, actionChar, charMod, swiPrev;
      unsigned long int bounceEnd;  // Debouncing-flag and end-time
    };

[with some items in a different order than before!] your initializer elements in the `buttons[]` declaration could look like

      { sw29, 'Q' },

where `charMod`, `swiPrev`, and `bounceEnd` are left to default to zero, or like

      { sw37, 'R',  KEY_LEFT_CTRL},

where `swiPrev` and `bounceEnd` default to zero.

Then, in your button-action code you could say:

    tosend = b->actionChar;
    chmodi = b->charMod;
    if (chmodi) {    // See if modifier needed
       Keyboard.press(chmodi);
       Keyboard.press(tosend);
       delay(100);
       Keyboard.releaseAll();
    } else {
       Keyboard.write(tosend);
    }

For those elements of `buttons[]` where you specified a modifier, the `if`'s first branch executes, and for those where you didn't, ie, for plain unmodified characters, the second one does.

There are all sorts of variants on these methods.  For example, instead of specifying action characters and modifiers in the `buttons[]` array, you could change it so that you specify function names, or could have several classes of actions.  If 80% of the actions were to issue one simple character, make that class 0, so the action class can usually default to 0.


message:
Mpr121 multiple using breakout

I try more solution but there are not working. i use adafruit mpr121 lib, sparkfuns solution but there are not working. Some solutions say, cut the addr socket but i am not understand. maybe you show this solutions breakout, i try my code.

body:
Unfortunately the wording of your question is very poor, however I think you are asking how to use multiple MPR121 devices on an Arduino?

According to the Sparkfun website you can change the I2C address from the default of 0x5A to one of four other addresses by cutting the jumpers on the back and connecting it to one of the other pins:

- ADDR > GND  = 0x5A (default)
- ADDR > 3.3V = 0x5B
- ADDR > SDA  = 0x5C
- ADDR > SCL  = 0x5D

I would also recommend using the [Bare Conductive][1] libraries rather than Sparkfun/Adafruit as they are more user friendly.

  [1]: https://github.com/BareConductive/mpr121


message:
Brushless motor "jiggles"

When I run my code, the ESC makes some noises, different on the high pulse and low pulse, then it begins to jiggle for a bit when it gets to the loop. Here is the code:

    #include <Servo.h>

    #define MAX_SIGNAL 2000
    #define MIN_SIGNAL 1000
    #define MOTOR_PIN 10

    Servo motor;

    void setup() {
      Serial.begin(9600);
      Serial.println("Program begin...");
      Serial.println("This program will calibrate the ESC.");

      motor.attach(MOTOR_PIN);

      // Wait for input
      while (!Serial.available());
      Serial.read();

      Serial.println("Now writing maximum output.");
      motor.writeMicroseconds(MAX_SIGNAL);
      delay(2000);

      // Send min output
      Serial.println("Sending minimum output");
      motor.writeMicroseconds(MIN_SIGNAL);
      delay(2000);

    }

    void loop() {
      motor.writeMicroseconds(MAX_SIGNAL);
    }

body:
Your code is familiar to the process of calibrating ESC controllers and is common. As your code is correct, we have to look at the connections. How is arduino connected to the ESC controller? can you provide a diagram? Only GND and Pin 10 should be connected. Do not connect the 5V of arduino. Power up the ESC with an external source. I think ESC signal port is Hi impedance so it should be no need for any resistor. Take a look at this site: http://robots.dacloughb.com/project-2/esc-calibration-programming/

You can see in that picture ( and the picture on the link provided), only pwm pin and ground are connected to arduino. Show us your connections if things keep going wrong. Also, does your power source provides enough juice to the motor?


message:
Can't read from DHT sensor when motor is running

I've been following [this tutorial][1] and I've run into some weird problems. When my motor starts running, I get "Failed to read from DHT sensor" on my serial window, meaning that readHumidity() and readTemperature() functions are returning NaNs.

This **only** happens while the motor is running. Once I stop the motor even momentarily, the DHT sensor starts working again.

Does anyone know why this is happening? I'm using a genuine UNO and a RHT03 sensor and some 5.9V motor (TD599839).

I've attached a diagram I made of my circuit in fritzing -
[![][2]][2]

  [1]: http://www.electroschematics.com/11291/arduino-dht22-am2302-tutorial-library/
  [2]: https://i.stack.imgur.com/CI1q2.png

body:
The problem may be electrical noise from the motor, or
you may have a wiring problem (an incorrect or intermittent connection).

1.  Kira San’s comment “try to add a 100nF ceramic capacitor between the motor terminals” is directed toward suppressing electrical motor noise.  As brushes make or break connections on a motor's commutator, arcs and sparks can occur.  The capacitor will limit voltage rate of change thus suppressing some of that electrical noise.

2.  CharlieHanson's comment (add a flyback diode across the motor terminals) is partly related to noise suppression but mostly to suppressing high voltage excursion that occurs when you shut off motor power.  While the motor is running, the magnetic field in it stores ½ L i² joules of power.  When current stops suddenly, those joules of power convert to a high voltage spike.  A [flyback diode](https://en.wikipedia.org/wiki/Flyback_diode) acts as a near-short to absorb that spike.  The cathode (cross-bar) of the flyback diode attaches to the high side of the motor voltage, as shown in [the circuit diagram](http://www.electroschematics.com/wp-content/uploads/2015/02/arduino-dht22-circuit.png) of the [project you linked to](http://www.electroschematics.com/11291/arduino-dht22-am2302-tutorial-library/) on electroschematics.com.

3. Re “you are using a resistor with that LED, yes? I'll overlook the fact that it's the wrong way round in the schematic!”, if the LED is wired backwards as shown in your drawing, it won't turn on – which is a good thing, because without a resistor (say 300-3000 Ω) in series with the LED, enough current may flow to damage the Uno or the LED.  Turn the LED around on the schematic (and on your wiring setup if you didn't already), and add a series resistor.

*Edit:* A comment says, “Don't have a diode either :S Will an LED work instead?”.  LEDs typically have rather low reverse-voltage ratings – 4 to 5 volts.  You could put two or three in series and if they don't burn up you're ok for this experiment.  But in production, don't depend on LEDs as flyback diodes except where it doesn't matter what happens.

4. Gerben's comment, “What is that capacitor doing there? Slow start?” refers to the 100 μF capacitor shown between transistor base and emitter.  In conjunction with the 1KΩ resistor from D4, that gives RC=0.1 second, so the transistor will take an appreciable amount of time to turn on.  This has a couple of consequences:  PWM control may be less effective (at low duty cycles, PWM depends on short, high-current pulses, to overcome stiction etc) and the transistor will run hotter.  If it's a big power transistor, ok.  If it's a small switching transistor intended for full-on or full-off, no.

*Edit:* A comment refers to a *[fan speed controlled temperature](http://www.electroschematics.com/9540/arduino-fan-speed-controlled-temperature/)* page at electroschematics.com.  That page shows a [BD139 power transistor](http://www.st.com/web/en/resource/technical/document/datasheet/CD00001225.pdf), and says the 100 μF capacitor between transistor base and emitter eliminates some motor noise.  Thus it falls into the “big power transistor, ok” category.  Well, more or less ok.  A heat sink may be needed on the transistor and the capacitor probably doesn't need to be that big; eg try 10 μF instead of 100.

5. An ordinary 9V battery easily supplies a dozen milliamps, but current draw larger than that quickly depletes it.  See eg [9V Alkaline tests](http://www.powerstream.com/9V-Alkaline-tests.htm) at powerstream.com and my answer to a previous question, *[Using Arduino Micro With 12V Buzzer](https://arduino.stackexchange.com/a/9853/3917)* that's somewhat related.  The motor shown ([TD599839](http://www.precisionmicrodrives.com/admin/a/search?q=124-001)) is rated at 35 mA at 5.9 V no-load, so will draw say 50 mA no-load from a 9V battery and will try to draw several times that if loaded; ie it will overstress an ordinary 9V battery.  In brief: Use a wall-wart or equivalent, or a big battery, rather than a small 9V battery when running motors.


message:
ATTiny 85 analog input pin number problem

I am using AT Tiny 85 to read voltage from lead acid battery charger while charging.  Basically the setup has two 7-segment displays driven by two SIPO shift registers(74ls164n). And used tiny 85's pin 4 (physical pin3) to read voltage.

I tested the code using arduino and finally burned it to AT Tiny 85,   it didn't worked, i debugged it for hours, and pulled hair out of my head, tested it on bread board, eventually i changed the port to "A2" from "4" and surprisingly, everything runs as expected.

My question is why this happens? why `analogRead(A2)` works while `analogRead(4)` don't. ?

I am using Arduino IDE 1.6.5 with https://github.com/damellis/attiny  (1.0.1 installed from the board manager) .
 [![datashett from sparkfun:][1]][1]

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

**Full Code:**

    //// Arduino Uno Pins
    //const int data = 8 ; //Tiny pin 3 (Physical 2)
    //const int clock = 9 ;//Tiny pin 2 (physical 7)
    //const int battery_Sensor = A0; //Tiny pin 4 (physical 3)
    //const int charger_ctrl = 5;   //Tinypin 1 (physical 6)

    // ATTiny 85 Pins
    const int data = 3 ;
    const int clock = 2 ;
    const int battery_Sensor = 4;
    const int charger_ctrl = 1;

    int outputValue = 0;
    int sensorValue = 0;
    int voltage_reading = 0;
    int msb = 0;
    int lsb = 0 ;

    // Qo -> 1
    // Q1 -> 2
    // Q2 -> 4
    // Q3 -> 5
    // Q4 -> 6
    // Q5 -> 7
    // Q6 -> 9
    // Q7 -> 10

    char c_array[10] = { '0', '1', '2',  '3',  '4',  '5', '6',  '7', '8', '9'} ;

    int measure_voltage(){
     sensorValue = analogRead(battery_Sensor);
     return map(sensorValue, 0, 1023, 0, 50);
    }

    byte seven_segment(char input, bool period){
      byte output_byte;
      switch (input) {
          case '0':
            output_byte = B11101110;
            break;
          case '1':
            output_byte = B10000010;
            break;
          case '2':
            output_byte = B11001101;
            break;
          case '3':
            output_byte = B01101101;
            break;
          case '4':
            output_byte = B00101011;
            break;
          case '5':
            output_byte = B01100111;
            break;
          case '6':
            output_byte = B11100111;
            break;
          case '7':
            output_byte = B00101100;
            break;
          case '8':
            output_byte = B11101111;
            break;
          case '9':
            output_byte = B00101111;
            break;
          default:
            output_byte = B00000001;
          break;
        }
      if(period == 1){
        output_byte = output_byte ^ B00010000;
      }
      return output_byte;
    }

    void setup()
    {
      pinMode(clock, OUTPUT); // make the clock pin an output
      pinMode(data , OUTPUT); // make the data pin an output
      pinMode(charger_ctrl, OUTPUT);
      pinMode(battery_Sensor, INPUT);

    }

    void loop() {
        voltage_reading = measure_voltage() ; // voltage x 10
        msb = voltage_reading/10;
        lsb = voltage_reading;

        shiftOut(data, clock, LSBFIRST, seven_segment(c_array[lsb], 0));// send this binary value to the shift register
        shiftOut(data, clock, LSBFIRST, seven_segment(c_array[msb], 1));
        delay(1000);
    }

body:
See the [analogPinToChannel](https://github.com/damellis/attiny/blob/master/attiny/variants/tiny8/pins_arduino.h#L52) function.

    static const uint8_t A0 = 6;
    static const uint8_t A1 = 7;
    static const uint8_t A2 = 8;
    static const uint8_t A3 = 9;

    ...

    #define analogPinToChannel(p)   ( (p) < 6 ? (p) : (p) - 6 )

Using `A2`, which is `8`, will return `2` (`8-6`) from the `analogPinToChannel` function.

Using `4` will give `4`. There is no (useful) analog channel `4`.


message:
Connect Antenna to GPS Module ET314AC

How can I connect antenna to GPS Module ET314AC?(it is not on a breakout board). I have an antenna like this one [GPS Active Antenna][1] and Here is the datasheet of ET314AC[ET314AC Datasheet][2].I want to connect it manually without any connectors or other things in fact I want to cutoff the connector from antenna.

  [1]: http://www.aliexpress.com/item/1575-42MHZ-Magnetic-base-GPS-active-Antenna-with-SMA-Plug-connector-for-GPS-receivers-and-Mobile/1531700595.html
  [2]: https://www.google.com.pk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0CC0QFjADahUKEwil6qrq4vnIAhVBhRoKHQePBOM&url=http://www.szstoton.com/res/stotongps/pdres/201203/20120320163340251.pdf&usg=AFQjCNFOZ31eexhFJWxNYqHvN-QWt4GoEA

body:
Read the datasheet!

> **V_ANT_IN**
>
This pin is reserved an external DC power supply for active antenna.
If using 2.85V active antenna, pin 19 has to be connected to pin 20.
If the bias voltage of active isn’t 2.85V,you can input bias voltage of you need to this pin.

So just wire the antenna to the RF_IN pin and GND, and connect pin 19 to +3.3V (since your antenna is 3.3V not 2.85V).


message:
Communication between two arduinos over wifi esp8266

I have two arduinos one is Arduino Mega while other is Arduino UNO and I want to send data from UNO to Mega and vice versa over wifi using two ESP8266 wifi modules without use of any router in between, so what is the simplest procedure I can use to do this? Moreover how can I do this with a router in between?

body:
The simplest solution is to turn on Access Point Mode on one of Wifi modules. and the other one has to be set to Station Mode in order to connect to the first one.

In case you want to add a router, just set both ESP8266 modules to Station Mode and connect them to the router.

Also, I would recommend replacing the Original Firware (AT firmware) of ESP8266 with NodeMCU Firmware. It uses lua language to write programs directly to ESP8266 which means that you can even make 2 ESP8266 modules talk with each other without even using Arduino.


message:
Arduino Bootloader availability

When I look at arduino and arduino-like boards featuring ATMEGA328 chip, I see that they either use a micro controller or a FTDI chip to program the ATMEGA through Arduino board pin 0 and 1.

This only works because there is a bootloader available on the chip. Is the bootloader present by default or do I need to install it.
What I mean is can I just buy 10,000 ATMEGA328 from ATMEL, put them on boards and program them through UART or do I need to first flash them with a bootloader?

body: The bootloader is the feature supplied with the Arduino board, but not a chip itself. If you want to clone Arduino (fully or partially), you will have to burn the bootloader yourself.


message:
avrdude: verification error, first mismatch at byte 0x0000 : 0x00 != 0x16 using USBasp

I'm having this strange error, which pops up around 90% of the time. I am trying to program my attiny25 using USBasp and the Arduino IDE / library. Sometimes it works, most times it doesn't.. This error occurs on large sketches as well as new sketches, with just the empty setup() and loop() functions. The error looks quite random to me, because my program just uploaded after trying around 10 times. Compiling goes fine. The error always occurs at byte 0x0000, and always in the format 0x00 != 0x _ _. I have six wires (correctly) connected from the USBasp to the attiny25. I do not use any resistors, capacitors etc.

Could anyone tell me what could possibly cause this error, and what to do to fix it?

body:
The cause is most likely the fact that you *"... do not use any resistors, capacitors etc."*

Connect a 100nF capacitor between Vcc and GND.  Connect a 10KΩ resistor between RESET and Vcc.


body: The problem has to do with the auto-reset feature, so you have to make sure the Reset pin is connected to VCC via a pull-up resistor. Generally, a 10k resistor will be just fine.


body: I had the same issue even with capacitor between Vcc and GND and resistor between RESET and Vcc. Finally, I use 5V Instead of 3.3V to power up my ATTINY and the problem was solved!


message:
Mac Arduino IDE Connection to Min Seg (Mega 2560). No tty

I own a Macbook running OS X 10.10.3 (Yosemite)

I own a [Min Seg][1].
My Min Seg model is built on an Arduino Mega 2560.

Problem
--

When I connect the board to the Macbook,
using either of the Macbook's two USB 2.0 ports,
using either of two USB A to B cables,
the board lights up, but I am unable to connect
to the tty device using the Arduino IDE.

`Tools --> Port` offered:

    /dev/cu.Bluetooth-Incoming-Port
    /dev/cu.Bluetooth-Modem
    /dev/cu.usbmodem621 (Arduino Genuino Mega or Mega 2560)

I was expecting to also see:

`/dev/tty.usbmodem621 (Arduino Genuino Mega or Mega 2560)`

If I unplug the board, the third listed option
from `Tools --> Port` disappears, as expected.

Verification 1
--

I opened the System Information utility application.

    USB --> USB Bus -->Arduino Mega:

      Product ID:    0x0042
      Vendor  ID:    0x2a03
      Version:       0.01
      Serial Number: 75435353038351316281
      Speed:         Up to 12 Mb/sec
      Manufacturer:  Arduino Srl
      Location ID:   0x06200000 / 3
      Current Available (mA): 500
      Current Required  (mA): 100

Verification 2
--

I used the Sparkfun [Terminal Basics][2] wiki to check for the device.
I used the Terminal utility application.

`ls /dev/tty.*` offered:

    /dev/tty.Bluetooth-Incoming-Port
    /dev/tty.Bluetooth-Modem
    /dev/tty.usbmodem621

`screen /dev/tty.usbmodem621 9600` offered a successful connection.
[A white screen, which allowed for exit using `Control+A` followed by `Control+/`]

Attempted Solutions
--

I tried several means from [here][3]:

I installed the [FTDI drivers][4].
I ran `sudo nvram boot-args="kext-dev-mode=1"` in the Terminal application.
Is an alternative driver worth attempting, such as that listed [here][5]?

I also attempted to connect through Mathworks Simulink.
When setting connection options, the program states
that a cu device is expected, rather than a tty.

  [1]: http://minseg.com/
  [2]: https://learn.sparkfun.com/tutorials/terminal-basics/all#coolterm-windows-mac-linux
  [3]: https://arduino.stackexchange.com/questions/12133/mac-osx-yosemite-no-serial-ports-showing-for-uno-r3
  [4]: http://www.ftdichip.com/Drivers/VCP.htm
  [5]: http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

body:
What you are seeing is normal.

In BSD (which is the OS that Mac OS is based on) a serial port has two distinct devices for two distinct roles.

The tty, or TeleTYpe interface is used for incoming connections, be that from a modem, serial terminal, whatever. You would normally run a process called getty on it to present a login prompt.

The cu, or Call Unix interface is used for making outgoing connections to other devices. Traditionally that was mainly other Unix servers through modems. Nowadays it includes many other devices such as an Arduino.

The theory is that when you try and initiate an outgoing connection through the cu interface it first checks that no-one is connected in through the tty interface and if the serial port is available it disables the tty interface so the listening getty process doesn't interfere with your call. Also the tty and cu interfaces deal with the modem control lines differently.

The Arduino IDE is merely honouring that system by only offering you the outgoing device in the port list. As far as the Arduino communication is concerned there should be no difference.


message:
How to display variables on 0.96" OLED with u8glib library?

I have Arduino Uno and 0.96" I2C Oled 4 Pinned display. These are my Arduino codes:

    #include "U8glib.h"

    U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE); // VDD=5V SCL=A5 SDA=A4

    int a = 10;

    void setup(void) {
    }

    void loop(void) {

      u8g.setFont(u8g_font_gdr25r);
      u8g.drawStr(8, 30, "E");
      u8g.setFont(u8g_font_gdr25r);
      u8g.drawStr(30, 30,"l");
      delay(2000);

      //  u8g.println(a);  //This code raw is not working
      //  delay(2000);
    }

I am trying to indicate integer type variable is called "a" to the OLED screen, but u8glib library hasn't got

> println( (int) a );

 function to do this. I only see
> u8g.drawStr();

function that this can't handle integer variables to the display. How can I do that?

body:
The [U8glib user reference](https://code.google.com/p/u8glib/wiki/userreference) page mentions a couple of ways to print the value of a number using ASCII characters.

Eg, following the idea at the second mention of `sprintf` at above link:<s>

    char buf[9];
    sprintf (buf, "%d", a);
    u8g.drawStr(33, 33, buf);

</s>*Edit:* The above follows the example at the link, but I've struck it out because in general `snprintf` is safer than `sprintf`.  See below.

    enum {BufSize=9}; // If a is short use a smaller number, eg 5 or 6
    char buf[BufSize];
    snprintf (buf, BufSize, "%d", a);
    u8g.drawStr(33, 33, buf);

The other way is via `print`.  (Search for U8GLIB::print in above link, and also see arduino.cc's [Print](https://www.arduino.cc/en/Serial/Print) docs).

Eg:

    u8g.print(a);

To get a `newline` effect, you may need to have a variable keeping track of the current line number; add 1 to it to get next line's number, and use that as a position parameter in a `drawStr` call.


body:
Ok, I have found the solution (Thank you @jwpat7) Here is my working code:

    #include "U8glib.h"

    U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE);  // VDD=5V GND=GND SCL=A5 SDA=A4

    int a = 0;

    void setup() {      }

    void loop() {

    u8g.firstPage();
     do {
    u8g.setFont(u8g_font_gdr25r);
    //u8g.drawStr(8, 30, "Eeee");

    char buf[9];
    sprintf (buf, "%d", a);
    u8g.drawStr(18, 3, buf);

      } while( u8g.nextPage() );
      delay(200);
    }


message:
Any way to use F macro with a passed variable?

I want to know if it's possible to use the F() macro on text that is being passed to a function.

This is an example function:

    void displayMenu(const char * txt, byte &var) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(txt);
      lcd.setCursor(0, 1);
      lcd.print(var);
    }

This is how I'm calling the function:

    displayMenu("Backlight:", backlight);
If I didn't separate the repeating code into a separate function, I would've been able to write it out like this:

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(F("Backlight: "));
    lcd.setCursor(0, 1);
    lcd.print(var);

If I try to do:

    displayMenu(F("Backlight"), backlight);
it doesn't work. Also if I try to do this in the function:

    lcd.print(F(txt));
that also doesn't work.

I'm just wondering if such a thing is possible.

body:
There is a special type for just this occasion - the `__FlashStringHelper` type.

    void displayMenu(const __FlashStringHelper *txt, byte var) {
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print(txt);
      lcd.setCursor(0, 1);
      lcd.print(var);
    }

Note I removed the `&` from `var` - you don't want that unless you are passing a complex class or are wanting to modify the contents of `var` in the function and have it reflected back outside the function.  Passing a reference to a byte (`&var`) requires two bytes of data - just passing the content of a byte only requires one byte of data.


message:
Arduino Micro tone() PWM Pins

according to the [tone()][1] documentation using tone() interferes with PWM output:

> Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

On my **Arduino Micro** it seems to interfere with PWM on pin 5. After using tone() the PWM does not seem to work anymore. If I use pin 3,9 instead everything works fine.

So can someone explain why that is happening and if there is a way to circumvent that?

  [1]: https://www.arduino.cc/en/Reference/Tone

body:
It's called a *resource conflict*.  The Arduino only has limited resources, and some resources are shared between different tasks. You can use that resource for one task or the other but not both.

In this case the resource is a *timer*.  You can use that timer to generate PWM or you can use it to drive the `tone()` system - but not both.

By default the timer is configured for PWM, but once you use `tone()` it re-assigns the timer to be used to trigger an interrupt at a specific frequency to toggle an IO pin.


body:
The pin 3 and 11 only refers to boards based on the ATMega328. On these boards timer2 is used by tone, disabling PWM on pins 3 and 11. See Majenko answer about timers.

The Micro (ATMega32u4) tone uses timer 3, which is connected to pin 5 only.

So on the Micro, just don't use pin 5 for PWM when using tone.

Secondly don't trust everything on the arduino.cc website. There quite a bit of misinformation on there.


message:
How to send and receive hex or binary numbers via BLE UART?

I am trying to send hex or binary numbers through BLE UART, but it is taking only char value which is converted into ASCII value.

I am using Adafruit's Bluefruit micro device and Bluefruit LE apps.

https://github.com/adafruit/Bluefruit_LE_Connect_Android
https://github.com/adafruit/Adafruit_BluefruitLE_nRF51

    Serial.print(F("[Recv] "));
    Serial.println(ble.buffer);
    BluetoothData=ble.buffer[0];
    Serial.println(BluetoothData);

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

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

In the UART box I want to type only a hex number and receive it in the Ble.buffer of the Arduino only.

body: ASCII is just a pattern of 0s and 1s, and can therefore be represented in binary, hex, octal, or decimal. The interpretation is entirely up to you in your code.


body:
The hex button toggle switch will show what the value of your characters are in hex. find the character that matches the value you want to send and use that. if you type the string 0x01 the app will send 0x30 0x78 0x30 0x31 0x0A. Since it trys to convert your characters to hex.

this table is pretty handy showing what characters are represented by which hex numbers http://web.cs.mun.ca/~michael/c/ascii-table.html.

unfortunately the character representing 0x01 is pretty difficult to type.

You can work around this issue by using the toInt() function in Arduino if you send the number 1 as a character the toInt() function will convert it to an int with value of 1. The hex equivalent is 0x01.


body:
Following code changes have been made to send the values in hex as input from user

1. replace the utf-8 conversion

value = message.getBytes("UTF-8");

by hex

int len = message.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
    data[i / 2] = (byte) ((Character.digit(message.charAt(i), 16) << 4)
            + Character.digit(message.charAt(i+1), 16));
}
value=data;

2. suppress the exception headlining for UnsupportedEncodingException
otherwise it throws a compile time error  UnsupportedEncodingException

Result examples :

3F ( hex ) results in ? ( ascii )
63 results in c


body:
This is a question about data representation. The value you are entering is a string, a sequence of characters, e.g. 0x42. The string can be parsed and converted to binary form either on the transmitting or receiving side.

The string must first be checked that it is valid. In this case a valid hex or decimal number. There are conversion functions that do both at the same time. The standard string function [strtol][1]() is perfect for the job. With zero as base argument it will parse both hex, oct and dec number formats.

    // Receive string
    char buf[BUF_MAX];
    ...
    // Convert string to number
    char* bp;
    long value = strtol(buf, &bp, 0);
    bool valid = (*bp == 0);

There is also an unsigned variant, [strtoul][2].

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaf8ce3b8dae3d45c34c3b172de503f7b3
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaea44aa48bda8261f794dcb2d1e7ab2b2


message:
Two commands in Void loop?

So basically I'm making 2 buttons turn on and off 2 different LEDs using debounce.
I got that settled with one button to turn on and off 1 LED.
But how do I make it so I can use the same lines but obviously different names of pins in Void loop?

So this is the one command line, but how do I make 2 commands with the if statement, may I have an example? Thanks

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int inPin = 22;         // the number of the input pin
    int inPin2 = 26;
    int outPin1 = 13;       // the number of the output pin
    int outPin2 = 6;

    int state = LOW;      // the current state of the output pin
    int reading;           // the current reading from the input pin
    int reading2;
    int previous = HIGH;    // the previous reading from the input pin
    int previous2 = HIGH;

    // the follow variables are long's because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long time = 0;         // the last time the output pin was toggled
    long debounce = 200;   // the debounce time, increase if the output flickers

    //===============================================================================================
    void doIt(int outPin)
    {
      Serial.print("Button Switch State Change:");
      if (state == HIGH) state = LOW;
      else state = HIGH;
      Serial.println(state);
      lcd.clear();
      lcd.print("Zone1|State: ");
      lcd.print(state ? F("On") : F("Off"));
      Serial.print(state ? F("On") : F("Off"));
      digitalWrite(outPin, state);
    }
    //===============================================================================================
    void setup()
    {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("System Activated");
      //
      lcd.setCursor(0, 1);
      lcd.print("Ready...");

      pinMode(inPin, INPUT);
      pinMode(outPin1, OUTPUT);
      pinMode(inPin2, INPUT);
      pinMode(outPin2, OUTPUT);

      Serial.begin(9600);
      Serial.println("System Activated");
      Serial.println("Made by Mateo Holguin");
      Serial.println("0 = Light is Off | 1 = Light is On");
      Serial.println("=======================================");
    }

    //===============================================================================================

    void loop()
    {
      reading = digitalRead(inPin);
      reading2 = digitalRead(inPin2);

      if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        doIt(outPin1);
      }
      else if (reading2 == HIGH && previous2 == LOW && millis() - time > debounce){
        doIt(outPin2);
      }

      previous = reading;
      previous2 = reading2;
      time = millis();
    }

body:
I think you are asking

    if (value > 5)
    {
      StatementOne;
      statementTwo;
    }

But I think you might want to write a function, which would look like this

    void doThing(int button, int led)
    {
      if (digitalRead(button))
         digitalWrite(led);
    }

[Edit after reading your comment]
So you need to store the state of the system as a variable in the code.

    bool state = false;
    if (button1 && !state)
    {
      state = true;
      // Your on code.
    }
    if (button2 && state)
    {
      state = false;
      // Your off code
    }

You need to add your existing code for turning your LCD and LED on and off where the comments are.
The state variable holds the on or off state of your LCD and LED.
You can of course split it even further so your LCD and LED come on separately of each other.

Does that help?  If so don't forget to mark it as answered.


body:
**Edit:** Use the code below as it is, it's working for me:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int inPin = 22;
    int inPin2 = 26;
    int outPin1 = 13;
    int outPin2 = 6;

    int state1 = HIGH;
    int state2 = HIGH;
    int reading;
    int reading2;
    int previous = HIGH;
    int previous2 = HIGH;

    int debounce = 150;   // the debounce time, increase if the output flickers

    //===============================================================================================
    void doIt(int outPin, int state)
    {
      Serial.print("Button Switch State Change:");
      if (state == HIGH) state = LOW;
      else state = HIGH;
      Serial.println(state);
      lcd.clear();

      if (outPin == outPin1)
        lcd.print("Zone1|State: ");
      else if (outPin == outPin2)
        lcd.print("Zone2|State: ");

      lcd.print(state ? F("On") : F("Off"));
      Serial.print(state ? F("On") : F("Off"));
      digitalWrite(outPin, state);
    }
    //===============================================================================================
    void setup()
    {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("System Activated");
      //
      lcd.setCursor(0, 1);
      lcd.print("Ready...");

      pinMode(inPin, INPUT);
      pinMode(outPin1, OUTPUT);
      pinMode(inPin2, INPUT);
      pinMode(outPin2, OUTPUT);

      Serial.begin(9600);
      Serial.println("System Activated");
      Serial.println("Made by Mateo Holguin");
      Serial.println("0 = Light is Off | 1 = Light is On");
      Serial.println("=======================================");
    }

    //===============================================================================================

    void loop()
    {
      reading = digitalRead(inPin);
      reading2 = digitalRead(inPin2);
      delay(debounce);

      if (reading == HIGH)
      {
        state1 = !state1;
        doIt(outPin1, state1);
      }
      else if (reading2 == HIGH){
        state2 = !state2;
        doIt(outPin2, state2);
      }
    }


message:
8x8 solenoid matrix

I've been teaching a blind student how to program and build electronics with Arduino. So far I've substituted LED's with piezo buzzers with excellent results. We are getting to the point where more complicated output is required and braille displays are excessively expensive.
I've found these micro solenoids on eBay.
[![micro solenoids ][1]][1]

They are 5 volts and small enough to place on a grid to create display. Could I substitute these on a regular LED grid and run it via conventional shift register or MAX7219 methods?

Here is the link to the [micro solenoids][2].

  [1]: https://i.stack.imgur.com/wxNg7.jpg
  [2]: http://m.ebay.com/itm/2pcs-x-DC-5v-6V-inhaled-Type-Push-Pull-Solenoid-Electromagnet-DC-Micro-Solenoid-/331680100757?nav=SEARCH

body:
If I understand Chinglish, you won't be able to drive it with the typical LED drivers... it give 350mA for "Current".  That's 30-40 times the normal LED current, and would require special driver circuitry capable of 0.350A * 5 V = 1.75W per device, over 100W to activate all of them!

I *think* it also says they cannot be continuously activated, which makes sense, given the small package and high power.  Leave 'em on long enough and they would probably burn your fingers.  :(


body:
Yes the power requirements are a lot more than LEDs but theres a trick with solenoids which is each solenoid output would be PWM rather than DC.

You could experiment with different frequencies/duties but I reckon start with a 100-200Hz pulse at around 25-50% duty. Can drop your power down by at least a 1/4 or less.

This is obviously a bit more complex than a simple off or on. But solenoids have no problem with holding their magnetic field with a pulse and its recommended to avoid overheating the coil.

Edit: so there are 2 ways to approach it that I see. Either dedicate 1 pin on your micro for each solenoid which would go through a driver (with diode protection) and setup a PWM routine to pulse each output. or..
use a matrix approach with an oscillator on each solenoid. Meaning you would just switch the oscillator on and off

The first approach is more code intensive and would be limited by the micro.
The second is more hardware intensive limited by the components you have.

Also to make sure they retract a short reverse polarity pulse would do that.


body:
Looking at the description. They have a permanent magnet inside, so they are kind of "latching". So using an H-bridge you can have them move outward or inward.

The only problem will be that a finger will be **pushing** on the shaft. So unpowered, they will move when a finger goes over them. You would have to add some mechanism that moves another pin, and locks it in place.


message:
uint8_t * to integer and string

**Convert text array/buffer to integer and string.**

hi! i'm sending text to an arduino and the output of that library is a
uint8_t array.

Atm the text send is a number between "0" and "1023"

    void something(uint8_t * text){
     analogWrite(13,text);// does not work
    }
    /*
    toInt() also not
    int() not
    atoi() not
    invalid conversion from 'uint8_t* {aka unasigned char*}' to 'const char*'
    */

i need to convert it to an  integer or better to a uint16_t.

As i plan to send custom commands in near future it would also be good to know how to convert that array to a string, that i then split/manipulate/parse.. whatever.

i looked in various posts but i couldn't get it to work on that simple example above. i'm new to c++

if it's needed the length is also aviable inside the function.

body:
Your problem is that you are storing your text in an *unsigned* pointer (`uint8_t *`)instead of a *signed* pointer (`char *`).

If you change all your text types to `char *` then you can directly use `atoi()`.  If you have a lot to change, though, you can just *cast* the unsigned pointer into a signed one (and make it `const` at the same time):

    analogWrite(13, atoi((const char *)text));


body:
analogWrite is a function to set a PWM duty cycle value to a pin on the micro

Usually to control a motor speed or LED brightness or similar.

Unless you plan to use the char value to set the PWM value??

A bit more context would help with your problem.


message:
Communication via IP adress with Arduino IDE and ESP8266

I have two Arduino boards and two ESP8266 modules with the NodeMCU firmware, and I want to make this:
One Aruino will be connected to one module and a vibration sensor, and when this sensor detects some vibration, it will send some data using the ESP8266 module as a server, then, the other Arduino will recieve the data with the other ESP module and display a message to a LCD screen.

I've already programmed the WiFi modules as a server and as a client using NodeMCU firmware and LuaUploader. The issue I have is that I don't know how to make a program in the Arduino IDE that communicate both Arduino boards using the ip adress assigned to both ESP modules, can you help me? Thanks

body:
You have the esp8266 talking.  Now you need to come up with a method of passing data from the arduinos to the esp.

You can use serial, you can use i2c, spi? Or something of your own design.  The problem wit using serial is the you are already using serial to communicate with the board from your PC.  You can use SoftSerial on the Arduino, but not sure how you'd do it on the ESP.
There are ways of making both boards work as master and slave i2c and spi, but it's probably overkill.
You could use two pins, one pin sends a binary bit and the other to clock the data, set high when new data has been written and set low when it has been read.
Then just use the same sort of algorithm as you did between you eps.

I have assumed that one Arduino is connected to one esp.  Let the ESPs worry about ip addresses.  If you want the Arduino to specify the destination then use a simpler addressing system than IP and let the ESPs translate that.