title: sending ctrl-z in a struct?

text:
# Question
Title: 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": Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?

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);
}

```

# Answer
> 2 votes
First off, consider trying '\032' or '\x1A' for the ctrl-z. (See, eg, *How to send ctrl+z in C* on stackoverflow.)

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 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   ) 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) 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 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.

---
Tags: button, keyboard, pointer, struct
---


# Question
Title: Can I safely integrate 3,3v sensor with 5v Arduino UNO? How?
I plan to use Adafruit's RGB sensor with Arduino working as a RGB controller running on 5V. In my location, the 5V-compatible version of the sensor 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 are available in my country (Poland).

# Answer
> 3 votes
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

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

<sub>(source: arduino.cc)</sub>

# Answer
> 1 votes
You can use "logic level converter bidirectional," to connect modules with different voltage requirements. They are pretty cheap.

---
Tags: arduino-uno, i2c
---


title: Mpr121 multiple using breakout

text:
# Question
Title: 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.

# Answer
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 libraries rather than Sparkfun/Adafruit as they are more user friendly.
> 2 votes

---
Tags: arduino-mega
---


title: 433MHz sending not receiving

text:
# Question
Title: 433MHz sending not receiving
I'm trying to send data using these 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;
}

```

# Answer
> 2 votes
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!

# Answer
> 3 votes
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").

---
Tags: arduino-nano, arduino-micro, virtualwire
---


title: Brushless motor "jiggles"

text:
# Question
Title: 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);
}

```

# Answer
> 1 votes
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?

---
Tags: motor, pwm, servo
---


# Question
Title: 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?

# Answer
> 1 votes
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

**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.

---
Tags: arduino-uno
---


# Question
Title: 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) .

**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%10;

    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);
}

```

# Answer
See the analogPinToChannel 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`.
> 6 votes

---
Tags: attiny
---


# Question
Title: Need help converting a processing sketch for a robot arm with servo shield
I'm currently building a robotic arm. I'm using an Adafruit servo shield, 7 servos, Arduino uno, and a 5V 10A power supply.

I found a program that controls the arm with mouse movement using a processing sketch, Fixbot.

However I'm using the Adafruit servo shield, and I've got no clue how to convert the program. I've found the center points for the servos, so I've managed to make the robot stand upright using my own code.

If someone could give me some pointers as to how to convert from the on-board PWM outputs to the servo shield outputs for the linked program, and how to set servo max/min, I would highly appreciate it.

# Answer
> 1 votes
I use a generic servo shield, and the *servo PWM outputs* (3 pin inline connector) on the shield are labeled accordingly (`0` \- `15`). Your Adafruit servo shield should be the same, see below.

The link that you provide also has the *Arduino* version, see below. You should use that, instead of the *Processing* version.

The Arduino library `Servo.h`, handles all of the "Servo PWM to Arduino pin conversions" that you ask for. So, looking at the Fixbot code, it would seem that all you would need to do is change the five pins (servo PWM outputs) to which the servos are `attach`ed in `setup()`, according to which servo PWM outputs you attach each servo to.

```
#include <Servo.h>

String command;

Servo seg0;
Servo seg1;
Servo seg2;
Servo seg3;
Servo seg4;

void setup() {
  Serial.begin(115200);
  seg0.attach(8);            /* <--- Change Me !!! */
  seg1.attach(9);            /* <--- Change Me !!! */
  seg2.attach(10);           /* <--- Change Me !!! */
  seg3.attach(11);           /* <--- Change Me !!! */
  seg4.attach(12);           /* <--- Change Me !!! */
}

void loop() {
  if(Serial.available() > 0) {
    char inChar = Serial.read();
    command += inChar;
    if(inChar == '\n') {
      // clear command
      performCmd(command);
      command = "";
    }
    Serial.flush();
  }
}

void performCmd(String cmd) {
  int comma1 = cmd.indexOf(',');
  int comma2 = cmd.indexOf(',', comma1+1);
  int comma3 = cmd.indexOf(',', comma2+1);
  int comma4 = cmd.indexOf(',', comma3+1);

  int cmd0 = stringToInt(cmd.substring(0, comma1));
  int cmd1 = stringToInt(cmd.substring(comma1+1, comma2));
  int cmd2 = stringToInt(cmd.substring(comma2+1, comma3));
  int cmd3 = stringToInt(cmd.substring(comma3+1, comma4));
  int cmd4 = stringToInt(cmd.substring(comma4+1, cmd.length()));

  seg0.write(cmd0);
  seg1.write(cmd1);
  seg2.write(cmd2);
  seg3.write(cmd3);
  seg4.write(cmd4);

}

int stringToInt(String str) {
  String tmp = String(str);
  return str.toInt();
}

```

Regarding your question about the maximum and minimums, again, these will be handled by the `Servo.h` library.

---

### TL;DR

Change the five servo `attach` lines in the `setup()` routine, to reflect which servo ports your servos are connected to.

---

**Power Requirements**

As an aside, remember that you will need to supply external power (+5V) to the Adafruit Servo board, via the blue screw terminal block, in order to have sufficient power (current) to actuate the servos. In the photo above the screw terminal block is not shown, but would be mounted half way up on the left hand side of the PCB (where it says `5-6V Servo`). It can be seen in this photo, at the top:

If you do not supply external power, then the Arduino board, by itself will not be able to supply enough power. Even though the code may be running, the lack of power may make it appear that there is no output, as the servos remain immobile, due to the lack of current.

---
Tags: arduino-uno, servo, arduino-motor-shield, adafruit, processing-lang
---


# Question
Title: 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?

# Answer
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.
> 2 votes

---
Tags: arduino-uno, arduino-mega, esp8266
---


title: Arduino Bootloader availability

text:
# Question
Title: 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?

# Answer
> 2 votes
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.

---
Tags: bootloader
---


# Question
Title: Can't read from DHT sensor when motor is running
I've been following this tutorial 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 -

# Answer
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 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 of the project you linked to 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* page at electroschematics.com. That page shows a BD139 power transistor, 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 at powerstream.com and my answer to a previous question, *Using Arduino Micro With 12V Buzzer* that's somewhat related. The motor shown (TD599839) 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.
> 0 votes

---
Tags: arduino-uno, motor, temperature-sensor
---


title: Connect Antenna to GPS Module ET314AC

text:
# Question
Title: 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 and Here is the datasheet of ET314ACET314AC Datasheet.I want to connect it manually without any connectors or other things in fact I want to cutoff the connector from antenna.

# Answer
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).
> 1 votes

---
Tags: arduino-mega, gps
---


# Question
Title: 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.
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 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:

I installed the FTDI drivers.
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?

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.

# Answer
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.
> 1 votes

---
Tags: arduino-ide, mac-os, port-mapping
---


# Question
Title: Is it possible to upload a program from a tablet?
Is there any easy way to upload a program/sketch from an iPad or Android tablet without adding extra an shield (Bluetooth or Wi-Fi)?

If not, can it be done using shield? Which shield is preferred?

Also what are the IDE options available?

# Answer
I figured out a way to do this without having to port the compiler to iOS. It only works with the arduino Yún, but the Yún can send code to other arduinos with an spi cable.

* Install an SSH app on your device so you can communicate with the arduino
* Using that, install Ino on your Yún, a command line arduino compiler
* Create a file, put your code in it, then save it
* use Ino to upload your code!

kind of confusing, but it could work!
> 6 votes

# Answer
Unfortunately Apple doesn't allow apps that implement programming languages. This being said, it is unclear why they would not allow an app that has to do with the Arduino IDE due to the fact that the code doesn't actually run on the Ipad itself.

See here for more Info.

As far as an Android IDE, I have heard that there are a few people working on different IDEs that sends the code to the Arduino over the internet, although they have not been released yet, and the details are still a bit unclear.

Source: http://forum.arduino.cc/index.php?topic=61305.0
> 2 votes

# Answer
You can always upload to the Arduino via Bluetooth.

1. You must have a bluetooth chip/shield (any should do) and a PC that has bluetooth (or a table that can compile, most likely an Android tablet)
2. You must change the BT baud rate to the same as normal arduino upload, which is 19200 (default BT baud is 9600).
3. Connect the BT to Pin 0 and 1 so act the same as having a USB cord connected
4. Connect a wire to the reset pin to allow remote resetting the arduino to statup the bootloader
    * There must be a delay before hitting the reset pin as the bootloader must be active when hitting the upload button.
5. Enjoy

For a more detailed description please read: http://ame2.asu.edu/staff/kidane/ArdWilessBtProg.pdf
> 2 votes

# Answer
Since your question is only about uploading, this will work with a Yun

* compile your sketches with the IDE on your pc
* for each hex file, copy it to the yun and run `merge-sketch-with-bootloader.lua PATH_TO_HEX_FILE`
* manage to connect to the Yun from your tablet via SSH
* once logged in, run `run-avrdude PATH_TO_HEX_FILE`
> 0 votes

# Answer
> Is there any easy way to upload a program/sketch from an iPad or Android tablet without a shield (Bluetooth or Wi-Fi)?

If you don't mind re-writing your program in an interpreted language, one option is:

* Install an interpreter on the Arduino, perhaps using the standard Arduino IDE running on a standard desktop PC -- like the bootloader, this only needs to be done once.

Then:

* Use your favorite terminal emulator on the tablet
* Somehow link the Arduino and the Android together, and tell the terminal emulator to talk over that link.(\*)
* Tell the terminal emulator to send the (more-or-less human-readable plain text) program to the interpreter over the link. (No compiler necessary on the tablet).

(\*) There are several different ways to make this link; some of them are mentioned at How do I write an Arduino sketch and an Android application to talk to each other over a standard USB cable? .
> 0 votes

# Answer
i have been trying out arduinodroid - it's an ide that claims you can upload to your arduino from it. you need an OTG cable (on the go) and to be honest i never actually managed to upload from arduinodroid but others seem to be able to...

my arduino is currently not talking to my computer - a bootloader problem it seems - so i'm getting hold of an AVR ISP MKii - with one of them it is apparently possible to send from terminal ide - an android app, will feedback when and if i get it to work.
> 0 votes

# Answer
I have tried android app to programming Arduino Uno via bluetooth, simply by adding Bluino\_Shield to your Arduino Uno. This link app https://play.google.com/store/apps/details?id=com.bluino.bluinoloader
> 0 votes

# Answer
Yes, you can upload over BLE with free(mium) iOS app - Apploader

http://www.apploader.info
> -1 votes

---
Tags: uploading, ide, android
---


# Question
Title: 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?

# Answer
> 5 votes
The U8glib user reference 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:

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

```~~

*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 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.

# Answer
> 0 votes
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);
}

```

---
Tags: arduino-uno, i2c, display
---


# Question
Title: 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.

# Answer
> 2 votes
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.

---
Tags: flash, string
---


title: Arduino Micro tone() PWM Pins

text:
# Question
Title: Arduino Micro tone() PWM Pins
according to the tone() 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?

# Answer
> 2 votes
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.

# Answer
> 3 votes
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.

---
Tags: pwm, arduino-micro
---


# Question
Title: How do I connect this string of LEDs to my Arduino Uno?
I'm an electronics noob. I have this string of LEDs but don't know how to connect them to my Arduino Uno. As they are wired in parallel, there are two wires / four ends. What do I plug where?

# Answer
Connect the negative ( or cathode ) to ground ( 0V ) and the postive ( anode ) to the output pin of the controller.

Firstly connecting that many LEDS directly to a single micro pin is not a good idea. Usually you would need to go through a buffer/driver first which can deliver the correct power to the LEDS.

I'm not that familiar with the UNO but unless that board has a driver circuit on it you might need a few extra components.

What are the specs of the LEDS?
> 1 votes

---
Tags: led
---


title: 8x8 solenoid matrix

text:
# Question
Title: 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.

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.

# Answer
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. :(
> 0 votes

# Answer
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.
> 1 votes

# Answer
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.
> 0 votes

---
Tags: led, hardware, shift-register, max7219
---


# Question
Title: Arduino IDE, Underlying Code and Libraries
I'm trying to better understand what is going on behind the Arduino IDE. First off I am no expert in C or writing firmware to boards but do have experience in real development.

I see currently the Arduino IDE is one big vast library we first select our board. What I don't understand is where are our header files? The source files for the board you select?

Not only that we use a number of functions already detected within the IDE where are these located also is any of this code editable?

I had a look through the Arduino directory and most of this stuff looks like its Java I was hoping for C files. Thanks for any links, help or info anyone can give.

# Answer
> 0 votes
Just check the source code. Specifically look at `Arduino.h`, `main.cpp` and `wiring*`.

These files should also be present in the Arduino application folder somewhere, but you'll have to go through quite a few subfolders to find them.

The different boards have different .h file that will specify the pin-numbers and other chip specific data.

The "auto detect" functionality is done by `keywords.txt` files. At least for libraries. That way if you install a new library with keywords.txt file, the library functions-names are recognized.

The processes of taking all these files, and the users code, and compile it all whole story on it's own.

---
Tags: arduino-ide
---


title: Two commands in Void loop?

text:
# Question
Title: 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();
}

```

# Answer
**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);
  }
}

```
> 1 votes

# Answer
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.
> 1 votes

---
Tags: c++, debounce
---


# Question
Title: Is it possible to package a sketch with dependent libraries for cross-platform compatibility?
I have a complex sketch that I spent many weeks working on, which I am backing up frequently because I'm afraid of losing any of my progress.

I'm wondering if it's common practice to make a self-contained package of the sketch and all its dependencies, so that it can be moved easily to another OS if necessary. My concern is that if my OS crashes and I have to reinstall everything or move to another OS, I might run into library and dependency errors, especially with the libraries that I altered/customized. I need my sketch to be able to compile as quickly as possible on whatever OS I end up using, since it's a home-automation sketch that controls dozens of things around me.

Is this a valid concern? And if so, what are some preferred ways to make a sketch become "self-contained", so that everything necessary is included? Is there some kind of a better version-control system for Arduino sketches that an amateur programmer might not be aware of?

# Answer
> 2 votes
I would suggest switching to UECIDE instead of the Arduino IDE. (Yes, shameless plug, it's my IDE).

UECIDE has a facility that I dubbed "localizing" a library whereby it copies it into a libraries folder within the sketch folder itself, and that copy of the library is used in preference to any other library named the same in the system.

That means that a sketch and its libraries then become completely self contained in one folder, and it's perfectly possible to have different versions of the same library in different sketches.

# Answer
> 1 votes
A way to do so is to include all the library files (\*.cpp, \*.h) in your sketch folder and then include them in your code.

There are many solutions that you might find handy in this link: How to organize my Arduino projects' structure for easy source control?

---
Tags: arduino-ide, library, ide
---


# Question
Title: Flexibility of SoftPot Membrane Potentiometer during the use?
Does anybody have some information or experiences with the flexibility of Spectra Symbol's SoftPot Membrane Potentiometer during the use? Is it possible to partly wind it up on a reel (or something similar) and use the remaining part dynamically without loosing precision and control? Are there "ghost touches" caused by the force/pressure of bending/winding the sensor strip? Or should the sensor always be used in a flattened position?

Thanks for any helpful comments.

# Answer
As you can see from this data sheet it will show you examples on how it is used. https://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf

I'd buy a curved one just to make sure, because as it bends, the 2 conductive materials will touch.
> 0 votes

---
Tags: potentiometer
---


# Question
Title: How do I create a 9 bit number based on values from 9 digital inputs?
I have 9 pins that are inputs from 9 IR LEDs. I want to combine all their results into one 9 bit number.

example: pin1 = high, pin2 = high, pin3 = high, pin4 = low, pin5 = high, pin6 = low, pin7 = low, pin8 = high, pin9 = low

9 bit number = 111010010

# Answer
In your code you would use a 16 bit unsigned integer as your variable. As there is no such thing as a 9 bit type.

If the pins correspond to different ports on your micro, you basically do this:

Read the pin value from the port register, and bit shift to the right bit position then OR with the variable.

Say you had 8 of the LEDS on PORTB (pin 0 - 7 )and the 9th on PORTC (pin 2)

```
unsigned int ir_inputs = 0

ir_inputs = PORTB; //just reads the register directly
ir_inputs = ir_inputs|((PORTC & 0x04)<<6); //reads the bit on pin 2 then shifts it 6 places to bit 8 (or the 9th bit remember bits always start at 0) and does not affect the other bits

```

something like that

actually you could put it into a function

```
unsigned int getIRinputs(void){
    return (unsigned int)PORTB|((PORTC & 0x04)<<6);
}

```

Easy done

Even if you had the inputs on 9 separate ports the principle is the same. Read, Shift, OR
> 6 votes

# Answer
Something like this:

```
typedef union NUM_9_BITS_t {
    unsigned int U;
    struct NUM_9_BITS_FIELD {
        unsigned int BIT0 : 1;
        unsigned int BIT1 : 1;
        unsigned int BIT2 : 1;
        unsigned int BIT3 : 1;
        unsigned int BIT4 : 1;
        unsigned int BIT5 : 1;
        unsigned int BIT6 : 1;
        unsigned int BIT7 : 1;
        unsigned int BIT8 : 1;
        unsigned int BITO : 23;
    } BITS;
} NUM_9_BITS;

NUM_9_BITS num;

num.BITS.BIT0 = digitalRead(PIN0);
num.BITS.BIT1 = digitalRead(PIN1);
num.BITS.BIT2 = digitalRead(PIN2);
num.BITS.BIT3 = digitalRead(PIN3);
num.BITS.BIT4 = digitalRead(PIN4);
num.BITS.BIT5 = digitalRead(PIN5);
num.BITS.BIT6 = digitalRead(PIN6);
num.BITS.BIT7 = digitalRead(PIN7);
num.BITS.BIT8 = digitalRead(PIN8);

Serial.print(num.U);

```
> 3 votes

# Answer
As @KiraSan said, You need something larger than a byte for 9 bits. However:

```
int tally;
tally=0;
for (char pin=1; pin<=9; pin++) {
    if (digitalRead(pin)==HIGH) {
        tally|=1<<(9-pin);
    }
}

```

This is done from memory and is untested, if anyone spots any errors, let me know.

Explanation: tally is the sum (you should do something with this at the end, obviously, or it has no effect). It is defined and set to 0. Then, for each pin (1-9), read the pin; if the pin is high: take the number '1', and double it (9-pin) times; so if pin=9, it is doubled 0 times; for pin=2, it is doubled once (for a total of 2), and so forth. Set this bit on the tally.

Note that this reads digital pin 1 (which happens to be the second pin, the first being pin 0) - this should be marked as "tx" to set in the first bit, not the one referred to as "pin1" (which might be a constant or a variable, and therefore could point to any given pin). This method also assumes the pins are in order - you could easily change it to start from 0, or 7, but they have to be in order.

If you want arbitrary pins, or variable pins, you might try this:

```
const PIN_COUNT=9;
char pins[PIN_COUNT]={13,2,5,4,3,6,7,8,9};
int tally;

tally=0;

for (char pin=0; pin<PIN_COUNT; pin++) {
    if (digitalRead(pins[pin])==HIGH) {
        tally|=1<<pin;
    }
}

```

Changes: add PIN\_COUNT as a constant at the start, set the order of the pins (which can include any digital pins, including repeating a given pin if you feel so inclined, even after the start of the code.). You can also change them by doing: `pins[0]=1;` \- note that they are numbered from 0-8 for 9 pins. Since they now start at 0, the line with \<\< is now adjusted accordingly, as is the line that starts with `for...`.
> 2 votes

---
Tags: led, pins, input
---


# Question
Title: 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

# Answer
> 0 votes
First, you need a SoftwareSerial interface, since the hardware serial is already used for debugging. To setup a SoftwareSerial this is an example:

```
#include <SoftwareSerial.h>

const byte rxPin = 6; // Wire this to Tx Pin of ESP8266
const byte txPin = 7; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got Data from ESP8266: " + inData);
     // The rest of your code...
  }
}

```

To send data from ESP8266 back to Arduino try something like this:

```
uart.setup(0, 115200, 8, 0, 1, 1 ) -- Change the baudrate to 115200
-- A simple http server
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
        payload = payload + "\n"
        uart.write(0, payload) -- send it back to Arduino via Serial interface
    end)
      conn:on("sent",function(conn) conn:close() end)
    end)

uart.on("data", function(data)
    -- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)

```

# Answer
> 0 votes
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.

# Answer
> 0 votes
After reviewing your codes, I've rewritten them this way, I didn't get a chance to test them though, so try them and let me know.

**Server code: a. Arduino**

```
#include <SoftwareSerial.h>

int ledPin = 13;
int txPin = 2;
int rxPin = 3;

SoftwareSerial wifi(rxPin, txPin);

void setup() {
    pinMode(ledPin, OUTPUT);
    Serial.begin(115200); // This baudrate is better than 9600
    wifi.begin(9600);
    wifi.println("dofile('wifiserv.lua')"); // This where it goes
    digitalWrite(ledPin, LOW);
    delay(2000); // delay is necessary
}

void loop() {
  while(wifi.available())
  {
     digitalWrite(ledPin, HIGH);
     String inData = wifi.readStringUntil('\n');
     if (inData.startsWith("Server IP: "))
        Serial.println(inData); // This is just the Server IP address
     else
        Serial.println("Got new sensor value: " + inData)
  }
  digitalWrite(ledPin, LOW); // This means no data is available
}

```

**Server code: b. ESP8266**

```
uart.setup(0, 9600, 8, 0, 1, 1 )
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")
print("Server IP: " .. wifi.sta.getip() .. "\n")

srv = net.createServer(net.TCP)
srv:listen(80,function(conn)
    conn:on("receive",function(conn, s)
        data = s:match("sensor=(%w+)")
        data = data + "\n"
        uart.write(0, data)
    end)
end)

uart.on("data", function(cmd)
    -- When ESP8266 receives data from Arduino, it will trigger this event
end, 0)

```

**Client code: a. Arduino**

```
#include <SoftwareSerial.h>

int ledPin = 13;
int EP = 9;
int txPin = 2;
int rxPin = 3;

int dato = 10;

String ip; // Assign this to your server IP

SoftwareSerial wifi(rxPin, txPin);

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT);
  Serial.begin(115200);
  wifi.begin(9600);
  wifi.println("dofile('wificlie.lua')"); // This where it goes
  delay(2000); // delay is necessary

}

void loop()
{
  long medida = TP_init();
  delay(50);

  if(medida > 1000)
  {
    Serial.println(medida);
    digitalWrite(ledPin, HIGH);

    String cmd = "ip=" + ip + " " + "data=" + String(dato);
    Serial.println("Sending: " + cmd);
    wifi.println(cmd);
  }
  else
  {
    digitalWrite(ledPin, LOW);
  }
}

long TP_init()
{
  delay(10);
  long medida = pulseIn(EP, HIGH);
  return medida;
}

```

**Client code: b. ESP8266**

```
wifi.setmode(wifi.STATION)
wifi.sta.config("mynet","pass")

uart.setup(0, 9600, 8, 0, 1, 1 )
uart.on("data", function(s)
    uart.write(0, "GoSending!")
    ip = s:match("ip=(%d+.%d+.%d+.%d+)")
    data = s:match("data=(%w+)")
    conn = net.createConnection(net.TCP, 0)
    conn:on("connection", function(c)
        print("connected");
        conn:connect(80,ip)
        conn:send("sensor=" .. data)
        uart.write(0, "Data has been sent successfully")
    end)
end, 0)

```

---
Tags: arduino-uno, esp8266, nodemcu, lua
---


title: Power maximum output power for each pin

text:
# Question
Title: Power maximum output power for each pin
A have Arduino Mega 2560. I found in the spec that the maximum output current for each I/O pin is 40 mA.

Can i use 40 IO in parallel? That's mean 40\*40ma\*5 volt = 8000 mw = 8 watt.

What about the heat?!

# Answer
> 4 votes
There are also limits on the total power of groups of pins,

> 1. The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed 200mA.
> 2. The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
> 3. The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
> 4. The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
> 5. The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.

So you are already limited to 800mA.

Secondly, you have to be careful to change all the pins at exactly the same time. Otherwise some pins will be low, and others high creating effectively a dead short. Or if you make sure the pins are inputs before changing, some pins will be on sooner, and those pins will then for a short period, handle all the current, and thus exceeding their limit for a brief moment. Which isn't that bad, but still not ideal.

So definitely don't use `digitalWrite` to change all the pins, one after the other.

# Answer
> 2 votes
No, you can't. Read the rest of the specifications and you'll see why. Also the 40mA is wrong. That is the *absolute* maximum. 20mA is the guaranteed limit for steady-state IO.

---
Tags: arduino-mega
---


# Question
Title: How does the speed work in VirtualWire Library
I'm analyzing the VirtualWire library and in it, the send messages are being sent with digitalWrite in the "send" method. However, there is a setup speed function. I'm reading that function and I see a lot of prescalers and TCCR variables. However, I'm not quite sure what these things do. Because, if it uses digitalWrite anyway to send the bits, then really is no intrabit delay, etc. Can someone please clarify this?

Sorry if question is convoluted. Happy to do any clarification. Thank you for all guidance!

EDIT: Also, how do I transmit a block of message. Something greater than a byte? I'm trying to calculate BLER of messages and software serial only transmits 1 byte at a time. While virtualWire uses low-level error detection (and i want to avoid the use of any error detection/correction).

# Answer
> 1 votes
I think that is used for receiving. By setting the speed, it knows how often it needs to read the input pin. It does this using timer interrupts, so it will run "in the background" without interfering with the main (loop) code.

The TCCR stuff is the set the interval for the timer interrupt.

---
Tags: arduino-uno, serial, virtualwire
---


# Question
Title: is it possible to convert a 328 design to use a 32U4?
I have several projects that use simple 328 based arduinos that I built myself, similar to the familiar "arduino on a breadboard" projects that I'm sure everybody has seen. They have just the bare minimum, no ftdi, etc.

Is it possible to drop in the 32U4 without modifying the circuits, or would I have to do a bunch of work to the circuits to get them to work with the 32U4 chips, and if so what are the general steps?

# Answer
Just had a quick look at the datasheets, and the main difference I see physically is the 32u4 is 44 pin package and the 328 is either 32 or 28 pin. Also the 32U4 seems to have a lot more peripherals.

So based on that yes you will have to modify your circuit. Atmel are fairly consistant with ports and what their alternate functions are though.

eg SPI on portB, uart on portD

But you are just going to have to compare the pinouts on the datasheets see how they differ. And adjust pin connections accordingly.

Datasheets are easy to find. Good Luck!
> 4 votes

---
Tags: atmega328, atmega32u4
---


title: Why are Arduino clones cheap?

text:
# Question
Title: Why are Arduino clones cheap?
You can buy Arduino Nano v3 clones from Alibaba at the cost of roughly $2-$3.

I have calculated the cost for fabricating and all the parts in the BOM for Arduino Nano V3, and it ended up costing around $10 to $12 (depending on where you fabricate the board, buy the components and purchasing volume - assuming less than 100 units).

However, how are Chinese clone manufacturers able to slash the price so much it's only ~1/10 of the BOM cost.

Could it purely be due to economy of scale, lower fixed costs (cheap labor), low quality parts *(How do you define **low quality parts**)*? Or are there other factors at play as well?

# Answer
> 4 votes
All the factors mentioned in the question apply to make the cost so low. However, with an exception or two as noted in the next paragraph, “low quality parts” is not much of a factor, as explained in two paragraphs after that.

Possible low quality parts include the USB mini-B socket, crystals or resonators, and the reset switch. The socket and switch contain metal shapes that can be well made or badly (and more cheaply) made. Those badly made will function but may have shorter lives and higher failure rates. For example, the USB cable fit may be loose, or the switch may fall apart. Crystal or resonator accuracy and stability can be poor while still allowing a Nano clone to appear to function ok.

However, SMT (surface mount technology) or SMD (surface mount device) parts on the board cannot be made significantly more cheaply than can good parts. SMD LEDs, resistors, diodes, voltage regulators, and capacitors come off of automated assembly lines with little or no manual intervention. See, eg, ceramic capacitor manufacturing at wikipedia. Parts are automatically packaged into sealed reels of parts suitable for use on an automatic pick-and-place machine that populates PCBs. In short, the dozen 0603-size SMD LEDs, resistors, and caps, and the nine other passive or small-scale-integration SMD parts on the board will cost about the same coming off a bad manufacturing line as from a good line, so there is little profit to be made producing bad parts. The 20-odd passive parts probably cost a couple of cents, at manufacturing scale.

Active SMD parts like voltage regulators, the ATmega328P, and the 32U4 or CH340, likewise come off automated manufacturing lines. As these parts are more expensive, there is more economic incentive for cheating, and from time to time fake parts get sold and used. In the past (and perhaps still) there have been manufactories that specialize in removing labeling on the tops of cheap or non-functional chips, and putting accurately detailed fake labels for expensive chips on instead. (For example, NCP5318 buck regulators relabeled as ATmega328s.) In short, most of the active SMD parts on a Nano either are genuine and work or obvious fakes that don't work and earn their sellers bad reputations or jail.

The CH340g USB-to-serial chip vs. ATmega32U4 USB issue is more complicated. Ie, some may think of the CH340 as a lower quality part than a 32U4. The CH340 may need a different USB driver than the 32U4 and may not support 57600 BPS serial in some cases. , . The ATmega32U4 seems to be available on Alibaba for $0.10 to $.20 in moderate quantities. I think the CH340g is made only in China and is somewhat cheaper than the ATmega32U4, so its contribution to the BOM total cost may be a few cents.

The PCB probably costs 5 to 10 cents, and assembly is free except for amortized costs of pick and place machines and an IR reflow system with a conveyor. Boards probably are processed (components placed and soldered automatically) in panels of several dozen units, tested automatically, and then separated for packaging.

Summary: Inexpensive parts and automated processing hold down the per-board costs, moreso than cutting corners on component quality. Corners may get cut on assembly quality and on quality assurance inspections.

---
Tags: arduino-nano, clones
---


# Question
Title: Are there any good and maintained libraries for using DS2482 I2C to 1-Wire bridge?
The DS2482-100 and DS2482-800 are I2C to 1-Wire bridges which are useful for driving complex 1-Wire networks.

These are natively supported by a number of packages in Linux so you can interface easily with them on a Raspberry Pi.

I was surprised to find there is not an obvious library for accessing them on an Arduino however.

I have found the following:

* An Arduino library \- has some quirks and not-maintained.
* Part of AVR-Liberty - less quirks, not sure if maintained, not "Arduino" as such, more AVR.

It is helpful to be able to rely on maintained libraries to deal with any changes to the Arduino environment.

Arduino libraries are often easier to use than ones designed for AVR in general, which means more people are able to use the software.

Is there a better library available?

# Answer
> 0 votes
I have implemented a library, based on the Paeaetech one linked to above, but tidying up defines, fixing the listed issue, adding lookup table based CRC and support for passively powered sensors.

# Answer
> 2 votes
I believe the library linked by Cybergibbons has a bug in

uint8\_t OneWire::wireSearch(uint8\_t \*address)

A discrepancy at i = 0 (bit zero in this library, id\_bit\_number = 1 in a Maxim example) only follows the direction = 1 path and fails to find ROM addresses where bit zero = 0 (i.e. even family codes are missed when mixed devices, some with even and others with odd family codes, are present on the 1-wire bus).

A fix I have just implemented and appears to work is to modify the library to declare searchLastDiscrepancy and last\_zero as int8\_t (not uint8\_t), initialise/reset them to -1 (not zero) and, near the end of the method

```
    if (!last_zero)
            searchLastDeviceFlag = 1;

```

becomes

```
    if (last_zero == -1)
            searchLastDeviceFlag = 1;

```

I hope that helps.

---
Tags: library, i2c, 1-wire
---


# Question
Title: Is it possible to make a mathematical function generator using Arduino?
I want to build a function generator but not the ones which outputs square wave or sawtooth ect. I will input a discrete function lets say f(n) = e^n for n=0 to n=100 and the output array will be outputs as voltage samples creating a e^x like signal on a scope?

Is this possible?

# Answer
You can generate arbitrary waveforms using either the built-in PWM and a low-pass filter or an external DAC.

You won't get more than 16-bits in PWM ( or AFAIK non-audio DAC with arduino libraries ), so your e^N function will be below your resolution for most of the cycle.

Alternatively, generate a saw-tooth and use an op-amp exponential function
> 3 votes

# Answer
Arduino DUE has a built-in DAC (has two in fact) and so you can do arbitrary function generation fairly easily by just going over some arbitrary table (that sampled the function) and output that with `analogWrite` to the DAC channel\[s\]; details in this arduino.cc tutorial. They only show sine/triangle/square waves there, but if you look at Waveforms.h at the end of that tutorial you can put arbitrary shapes in there.

By the way this technique of waveform generation of using a lookup table and a DAC is abbreviated DDS for Direct Digital Synthesizer. Here's a more conceptual tutorial on DDS (not involving arduino): http://www.ni.com/white-paper/5516/en/

The DACs built-in Arduino DUE have 12-bit resolution by the way, i.e. 4096 discrete output levels. IF you need better than that, an external DAC is required, which you could connect by TWI/SPI etc.

You can get a poor man's DAC on the Arduino UNO or Leonardo by PWMing with `analogWrite` on the GPIO pins (as suggested in the other answer), but you need understand low pass filter fundamentals to get that done.
> 3 votes

---
Tags: analogwrite, digital-analog-conversion
---


# Question
Title: 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.

# Answer
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.
> 2 votes

# Answer
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!).
> 1 votes

---
Tags: arduino-uno, continuous-servo
---


# Question
Title: How can i connect the Mics-5132 to Arduino Uno (Carbon Monoxide Sensor)
hi. i don't know how can i connect Mics-5132 CO Sensor to my arduino.

plz help

# Answer
That is a very skimpy data sheet for the MiCS-5132 . (Shame on manufacturer for not including isolation information between heater and resistor output).

Connect 3.2 volts (3.3 volts is ok) to pins 1 and 3 (heater). Keep in mind the heater will draw about 32 mA.

Pins 2 and 4 are the output. The output is a resistor, whose value changes with the degree of detected gases. And the resistance is about 160 k ohms.

Wire a resistor (call it R1) from VCC (positive power) to your input. Start out with R1 = 150k (anything from 120K to 180K). .

Wire the sensor (pin2) to your input (use an input that can do A/D conversion). Wire the other side of the sensor (pin 4) to your board ground.

This makes a resistor voltage divider to your input pin. Your input pin should be an A/D converter. The A/D converter input should return a value dependent upon the sensor resistance.

Experiment with different values for R1, to get the input range that you desire.
> 1 votes

---
Tags: arduino-uno, sensors
---


# Question
Title: Ideal settings for regulated power using Arduino Uno VIN?
Is there a downside to providing a lot of amps to Arduino UNO's VIN? Is there any advantage to only supplying a limited amount of amps? I have a regulated power supply and I'm curious what I should set it to when going through the 5v port?

Also, should I stick with 5 volts? I've seen some tutorials say if powering the board through VIN it should ideally be much more than that?

Is there a spec sheet of sort that tells you this?

# Answer
> 2 votes
Honestly, it doesn't matter how much power (amps) you make available, it will only draw what it needs.

However, there is definitely something to be said for limiting how much power you provide. If something in your circuit is miswired or otherwise shorts out, limiting the circuit to something reasonable (wisely including a fuse in your design as well) means that you won't have some enormous current suddenly passing through burning stuff out and possibly injuring someone. :)

As far as what to provide in terms of volts and amps, the data sheet for your particular arduino is the place to go. As long as you are providing *that* you are in good shape.

# Answer
> 2 votes
From https://www.arduino.cc/en/Reference/Board :

> The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin. Note that different boards accept different input voltages ranges, please see the documentation for your board.

For specific values, visit https://www.arduino.cc/en/Main/Products?from=Main.Hardware and select your board, and look down to where it says "Input voltage" - there's a "recommended" and "limit", each being a range. Note that some power sources will fluctuate (e.g. 4 AA batteries are 6 volts, possible slightly higher when brand new, but will drop down if there is a high drain, or as they get used up. 4 AA batteries will not provide 6v for long).

As for current (measured in amps or milliamps), if the power supply cannot supply what is used by the board, it will overheat; if it provides more than is required, then it will work 100% perfectly well (so long as you don't have a short circuit). The current an Arduino on it's own will draw will vary depending on the board, Nick Gammon measured an Arduino Uno Rev 3 board at 50 milliamps, but LEDs will typically draw around 20mA each; motors will draw a lot more. 1000mA = 1 amp, so Nick's Uno would draw 0.050 amps. Power supplies typically say on them how many amps (or in some cases, milliamps) they can (safely) provide.

---
Tags: arduino-uno, power
---


# Question
Title: Need to power Arduino Mega 2560 with 3.3V
I found an LCD for my Arduino Mega 2560 that's parallel (I like that, I don't like SPI), but it works at 3.3V and isn't 5V tolerant. That's why I'd need to use level shifters, but that would use too much space and I'd like to power the microcontroller with 3.3V. But that would cause problems because the USART communication is set to be on 5V and that can't be changed.

Is there a way to power my Arduino at 3.3V? Is there an alternative Arduino for that?

Also, if there is, I'd need to have a 16MHz crystal on it. I know it's overclocking, but Gamebuino works at 16MHz on 3.3V and I would like to do the same.

# Answer
Have you considered maybe using the Iteaduino MEGA2560?

The Iteaduino MEGA2560 uses the same ATmega2560 processor as the Arduino Mega 2560, but is physically much smaller, the size of a Arduino UNO. It has a switch to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules. It breaks out *all* the GPIO pins of the ATmega2560, so it actually has more I/O on its connectors than the Arduino Mega 2560.

If I'm reading this right, the Iteaduino schematics and a typical Iteaduino features list seems to say it already has a 16 MHz crystal.
> 3 votes

# Answer
Have you considered maybe using the "Sparkfun Mega Pro 3.3V" plus a "SparkFun FTDI Basic Breakout - 3.3V" ?

It uses the same ATmega2560 processor and has the same I/O arrangement as the Arduino Mega 2560, but it runs off 3.3 V. It doesn't have the 16 MHz crystal you wanted, but if you really insist on overclocking, perhaps you could replace its 8MHz resonator with a 16 MHz crystal?
> 2 votes

# Answer
Have you considered maybe using the Inhaos Buono Mega 2560 (see ), also called the Inhaos Mega2560?

As far as I can tell, it is pretty much identical hardware as the Arduino Mega 2560 -- including the ATmega2560 processor -- except it has a selector to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.

Like many websites, every page on the Inhaos website http://www.inhaos.com/ has a "Contact Us" link at the top of each page. Click that link to get a list of several ways to contact the company.
> 1 votes

# Answer
Have you considered maybe using the ElecFreaks Freaduino MEGA2560 ?

It has an identical I/O arrangement and dimensions as the Arduino Mega 2560 -- including the ATmega2560 processor. It has a selector to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules. The voltage regulators and reset switch position are better than the Arduino Mega 2560.
> 1 votes

# Answer
What about a 3.3v Arduino Pro Mini, you'll need to solder headers but that's not too onerous. See here Arduino pro Mini or even cheaper from eBay
> 0 votes

---
Tags: arduino-mega, voltage-level
---


# Question
Title: How to transmit more than 1 byte continually?
In software serial, the write function only sends 1 byte at a time. Is there someway, some library, that i can send multiple bits/bytes, without stopping (and not using digitalWrite)? i want to be able to transmit at least 16 bits as opposed to just 8.

I know i can send 2 bytes, or even 100 bytes. But the thing i'm trying to do is, implement my own LDPC(error correction) codes on the Arduino. Therefore, i'm taking a lot of channel measurements. One of them is figuring out how the error happens during the delay between the stop bit and the next startbit. Often times, this is were synchronization problems occur. So I'm trying to track this down. Hence why, I need to send more than 8 continuous bits. In software serial, it transmits 8 bits, then transmits the stop bit. then write() restarts on the next call. Instead of this, i just want to send more bits, like 64 bits for instance, and look at the BLER on the received data. (the reason why I'm staying away from hardware serial is because i'm doing this with wireless RF modules) Do you guys have any further info regarding this? I'm very grateful! Thank you so much!

Also, it was suggested that I write my own softwareserial, but that's a pretty daunting task. I would like to avoid it, if i can.

**EDIT: Let me show you my data.** So, I'm constantly transmitting the values; 123,124,125,126.

```
1111011
1111100
1111101
1111110

```

The above 4 lines repeat about 2 times. Then, suddenly, it synchronizes incorrectly, and the following 4 lines are being constantly repeated.

```
11110101
11111001
11101101
11110001

```

It never syncs back to the original 4 transmissions. Now, inside the unsynced block of 4 transmitted bytes, there are fragments of the correct transmission inside. For instance, start from the 2nd bit of the 3rd byte of the correct transmitted byte. Now, if you account for the '0' start bit, and try to matchup the bits, the correct bits are being picked up in the correct order. It's just a problem of what the receiver takes as the startbit.

As i'm typing this edit, i realized something else. What i said in the above paragraph is true, then for the unsynced block, there should be a '0' start bit in front. Now, if the messages match up exactly, and if the 0 start bit that is being transmitted is being treated as a payload, then which 0 is being treated as the startbit, because all the bits between the synced and unsynced data are matched up. However, there should be one missing 0 each time because it's being read as a startbit, not databit.

Sorry if this is convoluted. Happy to clarify any part of it. Thank you so much!!

# Answer
I want to point out here that async serial communications relies on both ends providing a clock (there is no transmitted clock signal). Thus the sender clocks out bits at the "baud rate" (eg. 9600 bits per second) and the receiver clocks them in at the same rate.

With a start bit and 8 data bits therefore you can tolerate some difference in the clocks between sender and receiver (and there will be *some* difference). Effectively you could probably tolerate around a 10% difference in clock frequencies, as even if they are out by 10% the sample at the receiver will still land inside the data bit of the sender.

Now if you want to transmit 64 bits you have reduced this error margin by a factor of 8. So let's say (ball park) that you can now only tolerate a difference of 1% between sender and receiver.

You now need to be pretty sure that the clocks on the respective boards are pretty accurate. The Uno, for example, has a resonator CSTCE16M0V53-R0 which appears to have a tolerance of 0.5% and a frequency stability of 0.2%.

So, if the sender is running 0.5% slow, and the receiver 0.5% fast, you will almost certainly get errors.

---

> However, when it becomes unsyncde, some new 0 bit should be treated as the startbit, in which case it should not be printed. But i don't see any misisng zero. It's as if the actual data just got shifted.

How will it get unsynced? I don't think you are following how serial comms works. If you don't have any delay between bytes (or batches of bytes in your case) then it is impossible to resync, because if you miss a start bit, all the following bits will appear valid, they'll just be shifted. This is exactly what you are describing.

Really, to **ensure** syncing you need to have a gap between bytes (or batches-of-bytes in your case) longer than a byte might be, otherwise you can get this mis-sync happening. So if you make your batches longer, the gap has to be longer, effectively removing the slight advantage of larger batches.

Imagine you have an incoming stream of bits on the receiver:

```
011110101101100011110101101101101100110101100101100110101111001010101110111001010101111
1101001010100101101001010100111011111001000010111100100011011001001001001011001001010

```

And imagine that you missed that first start bit. Without a gap between bytes (which would appear as: `111111111`) you have no way of knowing which is a start bit and which is a data bit. Valid data would have a start bit, so you don't mistake valid data for the inter-byte gap.

In other words, with 8-bit bytes, **data** will always be `0xxxxxxxx1` and thus a gap of `1111111111` must be the gap and not data because there is no zero there. But with any shorter gap, and if the receiver samples in the middle of byte, it certainly might think that the next 0 in the stream is a start bit (wrongly).
> 2 votes

---
Tags: arduino-uno, softwareserial, rf
---


# Question
Title: How to know if arduino activated its short breaker?
today i was trying to use arduino power headers as a power source for my basic laser.
I used pin "5V" to connect it to the laser anode and the "GND" pin to the laser groung pin.
after doing this arduino turned restarted, so I removed all the connections to the laser, now the arduino is normal.
booth "5V" and "GND" pins is working normal.
does this mean that I made a short circut and arduino protected it self ? should I do anything now ?

# Answer
It sounds like connecting your Laser to the 5 volts power supply did draw too much current, thereby the 5 volts dropped to very low voltage.

The Arduino didn't "protect" itself. The Arduino simply shut down because of voltage being too low. Then, upon reapplication of 5 volts the Arduino re-started as normal.

You don't mention any details about the Laser. But if your Laser is simply a Diode, the Laser diode would draw a lot of current, resulting in the 5 volts power source giving reduced voltage.

If your Laser is a "laser module" with a built in driver, perhaps you connected the Laser backwards to the 5 volts.

EDIT 11/20/2015 : IF you are using the Arduino UNO , : The PolyFuse only protects from 500 mA overload on the USB connector. Schematic for the UNO shows that 5 volts for USB is called "XUSB". The PolyFuse connects from "USB VCC" to the XUSB. When you connected your Laser to the +5 and ground, the PolyFuse was not involved. (Unless of course you did connect to the USB 5 volts (XUSB), and didn't tell us that.

HOWEVER, if you powered your UNO from the USB port, then the PolyFuse WAS involved and did shut you down as others have commented.
> 1 votes

# Answer
You uses more the 500mA limit, and the PolyFuse tripped. After unplugging the polyfuse cooled down and "reset" itself.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Why can only some digital ports output PWM and the others not?
If it matters, I'm talking about the arduino uno v3.

# Answer
Check out the ATMega328p datasheet: each of the 3 timer/counter blocks can generate PWM (2 PWM signals per timer) and on top of that, typically Timer1 (16 bits) is used by the OS/scheduler/whatever, unless you are really running on bare metal.

It's a limitation, but so is everything else.

If you do not like it, you can always choose a different microcontroller, either AVR or something else. Certain models might be designed to have more units of a specific type than you would find on generic microcontrollers.
> 1 votes

# Answer
That is one of the hardware features/functions of the microprocessor. It is like a bag of candy when you eat the last piece there is no more left. You can do software PWM but that can use a lot of compute power. You can also get PWM peripheral devices you can connect to it.
> 0 votes

# Answer
After all, it's a cost issue.
Not only of the Arduino/Atmel, but any microcontroller.

The outputs of the PWM unit (which has a limited number of PWM channels) have to be routed to the output pins.
This routing is basically fix, because the silicon mask is fix.

However, to add some flexibility, most controllers allow a limited configuration of this routing by adding some internal switches which can be accessed by writing to the specific registers.

But any additional routing capabilities means more of those internal switches, which results in
more size -\> more silicon -\> more expensive.

Therefore the micro designers say - for example - "OK, it's enough to be able to output x of the y available PWM channels at every edge of the micro", and the poor PCB designer has to cope with what he gets.

Using an FPGA instead of a microcontroller you are really free to setup your function to pin routing - but look at the price of an FPGA ;-)
> 0 votes

---
Tags: arduino-uno, pwm
---