# Question
Title: How can I power an Arduino in a 3-phase environment?
I am working on a project which uses an Arduino board. Currently I am testing my device using 2-phase power and it works fine. I want to use that device in agriculture fields where 3-phase power is available instead. How can I do this?

# Answer
The very short answer is that the Arduino board itself is designed to be powered by low-voltage DC (but you almost certainly already know this). So what you're really asking, I think, is "can you use the mains power supply that converts mains AC to DC on a three-phase supply?"

The answer to that is a guarded yes. You will need to confirm that you are connecting to a single phase (basically what you were doing in testing) and that the voltage is appropriate for your power adapter.

The abridged version of the gory details follows…

Three-phase supplies are almost always used for motor or other power applications – for a low power device like an Arduino (or even lighting or small appliances) you don't typically need three-phase. What is usually done is to take the power supply for those devices either from phase-to-neutral or phase-to-phase – depending on the configuration of the three-phase supply.

Wikipedia has an article on three-phase power that explains the common connection schemes (Y or star where the three phases are wired to a common point, and delta where they are wired in a triangle). What is significant is that you will typically get a high and a low voltage depending on how you connect to a three-phase system. For example in the US a common Y three-phase service will give you 120 V phase-to-neutral and 208 V phase-to-phase.

A true 3-phase (as in needs to connect to all three phases) low-voltage power supply will probably be quite expensive. But you also don't need one. Unless you are building an "industrial" device all you need is a "normal" low-voltage power supply that is designed for the voltage that you'll be connecting it to.

All you need to do is to confirm the voltage that you'll be using and check that your power supply is rated for it. Many low voltage supplies are designed to be "universal" and you'll see a rating like 100-240 V, 50-60 Hz. That's likely to work on most three-phase supplies as long as the connection isn't phase-to-phase in a part of the world where the high voltage is in the 400 V range.
> 3 votes

---
Tags: arduino-uno, power, voltage-level, current
---


# Question
Title: Unsure about how the code works for this Make-It Robotics kit
I have been using a **Make-It Robotics kit**, that I picked up from a RadioShack that was closing, to learn more about Arduino, C, etc. After building the **line-following robot** and downloading the correct libraries, I can get the robot to function as intended. It uses 2 optical sensors in front of 2 driving wheels that are controlled by independent DC motors. The optical sensors determine if the left or right side of the front of the robot is over a white or black area on the test track. The necessary motor then turns on to keep the black line roughly between the 2 sensors as the robot moves along. The default test track that came with the kit was a large black circle on a white background.

I want to make some modifications to the code (and maybe the underlying library files) to try to make the robot able to handle other types of paths with more acute angles and sharper turns, etc. But, I don't understand some aspects of the highest level .ino source code file.

I am a little unsure of pasting such a long code block below and also don't think an image of it will help. The version data for the file I'm using is below. The files can be found online @ LINK

```
// ******************************************************************************    **
// * File Name          : linefollow
// * Author             : RadioShack Corporation
// * Version            : V1.0
// * Date               : 2014/01/16
// * Description        : Optical sensors send feedback to PCB
// *                      to make the robot follow a black line on a white background.
// ********************************************************************************

```

In this .ino file, **I don't understand the code from line 68 onwards**: from the Read Left/Right Optical Status onward...

I don't understand some of the bitwise operations there and don't really see how the sensor readings (whether it is over a white or black area on the surface) correlates to which motor activates to keep the robot on the course...

From my limited understanding of Arduino, this robot kit, and the code, it seems like the software and hardware have to interact in this way:

1. Robot moves forward using both motors turning the wheels in the same direction. It approaches the black test circle at a shallow angle (i.e. almost tangent to it) to allow one sensor to go over the black line before the other one does.
2. Optical readings of each sensor are taken periodically.
3. If both sensors detect white space, robot continues to move forward.
4. If the right sensor detects that it has gone from white to black and then to white, it means that the robot needs to turn to the left to stay on the path.
5. To turn left, the left motor is un-powered and the right motor is powered until the right sensor detects black again.
6. Now that the robot is on course, it will keep turning in the direction of the sensor that detects a white to black to white transition.

I am not seeing how my intuitive understanding of the robot's operation matches with that of the code...

# Answer
Indeed, the way the bitwise operations are written is confusing.

```
  if((sensor_in & 0xf00)==0)
    sensorValue1=sensor_in & 0xff;
  else if((sensor_in & 0xf00)>>8==1)
    sensorValue2=sensor_in & 0xff;
  if (sensorValue1 == 0x00)
    action1 =action1 & 0xfe;
  if (sensorValue1 == 0xFF)
    action1 = action1 | 0x01;
  if (sensorValue2 == 0x00)
    action1 = action1 | 0x02;
  if (sensorValue2 == 0xFF)
    action1 = action1 & 0xfd;

```

Basically you have two input values that can be in the same variable - differentiated by the 9th bit of the value. Values between 0 and 255 relate to one sensor, between 256 and 511 to the other. The bitwise operators split that into sensorValue1 and sensorValue2 accordingly.

Then those sensor values are compared to 0 or 255 and used to define the action to perform - that action being comprised of the lowest two bits of a byte variable, so you have three possible actions:

```
0 = both sensors off
1 = sensor 1 on, sensor 2 off
2 = sensor 1 off, sensor 2 on
3 = both sensors on

```

The comments in the program also tell you this information:

```
action1
         left        right
0x00    black        black
0x01    black        white
0x02    white        black
0x03    white        white

```

Now you have how to deal with the action value:

```
if(action1 != action2)
{
  if (action1 == 3 )
    line_following.go_forward(50);
  if (action1 == 1)
    line_following.line_following_turn_left(50);
  if (action1 == 2)
    line_following.line_following_turn_right(50);
  if (action1 == 0)
    line_following.go_forward(50);
}
action2=action1;

```

So if the action has changed, we can change what we are doing:

* If action is 3, so if both sensors read as white, or if action is 0, so both sensors read black (in other words if both sensors read the same) then move forwards.
* If action is 1 (so the left sensor reads black) then turn to the left.
* If action is 2 (so the right sensor reads black) then turn to the right.

So basically if it doesn't know anything better, it drives forwards, otherwise it turns in the direction that it finds the black line, thus keeping it always on that line. As it drifts off the line one sensor will sense white, so the robot will turn away from that whiteness and back on to the line.
> 2 votes

# Answer
In addition to the answer given on this site, I had to do some reading up on what bit-wise operations are and how they are useful. I did most of that reading on the Arduino website reference section.

I also stumbled across an online tech blog that actually dissected the inner workings of this program! The blog's author seemed glad to help Arduino beginners who got this kit, but had trouble understanding how exactly the robot moved in response to the sensor data.

JoesTechBlog

Someone even asked the blog's author about why anyone would code the logic in this manner. I too was wondering the same as to why it wasn't done at a higher (thus easier to understand level). Below is the author's response to that question. Can anyone here comment on it in terms of its veracity?

> Hello Richard, Yes I agree this logic is non-intuitive. I would have done the \>logic on the mirco-controller, that lives on the driver board, and just had \>the read\_Optical() method return a 0, 1, 2, or 3. But there is one possible \>reason for this logic. Performing bitwise operations in most cases takes up \>less CPU cycles than complex number comparisons. Since Radio Shack is not \>providing us the source code that runs on the driver board. Then we can only \>guess. Also sometimes bare metal programmers think in these terms, which may \>seem non-intuitive at times, but the more we start working at the bit level \>the more it makes sense.
>
> Thanks for the post.
>
> Joe
> 0 votes

---
Tags: robotics
---


title: Why does my Arduino keep waking up?

text:
# Question
Title: Why does my Arduino keep waking up?
This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search.

I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial here. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds).

In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish *sleep until interrupt wakes, perform interrupted action, then go back to sleep.* What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?

Thanks for the help!

```
#include <avr/sleep.h>
#include <avr/power.h>

ISR(TIMER1_OVF_vect)
{
 //do nothing
}

void enterSleep(void)
{
  set_sleep_mode(SLEEP_MODE_IDLE);

  sleep_enable();

  /* Disable all of the unused peripherals. This will reduce power
   * consumption further and, more importantly, some of these
   * peripherals may generate interrupts that will wake our Arduino from
   * sleep!
   */
  power_adc_disable();
  power_spi_disable();
  power_timer0_disable();
  power_timer2_disable();
  power_twi_disable();

  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the timer timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  /* Re-enable the peripherals. */
  power_all_enable();
}

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

  /*** Configure the timer.***/

  /* Normal timer operation.*/
  TCCR1A = 0x00;

  /* Clear the timer counter register.
   * You can pre-load this register with a value in order to
   * reduce the timeout period, say if you wanted to wake up
   * ever 4.0 seconds exactly.
   */
  TCNT1=0x0000;

  /* Configure the prescaler for 1:1024, giving us a
   * timeout of 4.09 seconds.
   */
  TCCR1B = 0x05;

  /* Enable the timer overlow interrupt. */
  TIMSK1=0x01;
  while(!Serial);
}

void loop()
{
    enterSleep();
    Serial.println("Waking");
    //delayMicroseconds(10000);
}

```

# Answer
Yes. Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.

You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.

If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent. If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done. A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.
> 3 votes

---
Tags: arduino-uno, interrupt, avr, sleep
---


title: Atmega328P burn bootloader with FTDI

text:
# Question
Title: Atmega328P burn bootloader with FTDI
I need your help.

I am using Arduino ProMini in my project.

In project board there is Atmega328P which doesn't have Arduino bootloader, and Atmega328P RXD, TXD pins are connected to FTDI Basic(sparkfun)'s TXD and RXD pins. I searched on internet how to burn bootloader for arduino. Most of them use other Arduino's built in SPI or other method. Problem is Atmega328P is already assembled to PCB board and I cannot make any soldering or change. Atmega328 and FTDI basic are connected and assembled to upload sketch (if there is bootloader of Arduino inside of Atmega328P, no problem to upload sketch).

Is there any solution or suggestions to burn bootloader using FTDI?

Thank You.

# Answer
> 1 votes
You cannot upload the bootloader through the ATmega's UART pins.

Perhaps the the necessary pins (SPI & reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.

Otherwise you may just have to desolder the chip.

A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part.

---
Tags: bootloader, arduino-pro-mini, ftdi
---


# Question
Title: How can I program RFduinos and how can I connect them with Bluetooth?
My RFduino dev kit just arrived, and for my project I have to connect a few RFduinos via Bluetooth and light up certain LEDs attached to the RFduinos. If anyone could point me in the right direction as to where I can program them/how I can connect them, it would be GREATLY appreciated.

# Answer
I am starting on a similar project (without the Dev Kit). Hooking the Bluetooth module to the RFduino is pretty straight forward, PWR to PWR, GND to GND, remember to cross the transmission wires: TX to RX & RX to TX.

In your `void setup()`, you need to start the connection:

```
Serial.begin(9600); // check your documentation to see the baud rate

```

In your `void loop()`, read or write to/from the bluetooth connection with serial write/read. `Serial.read()` or `Serial.write()`

Remember that Bluetooth is a communication protocol, not a controller. You don't mention WHAT you are connecting your RFduinos to using Bluetooth. You still need a controller capable of sending a signal to light up the LEDs using Bluetooth.
> 1 votes

---
Tags: bluetooth, communication, ide
---


# Question
Title: Read data from 3 ColorPal 28380 simultaneously on Uno/Mega
I've been trying to get an Arduino (I have a Mega and Uno lying around) to read values from a small array of 3 ColorPal 20380, which individually, work as intended with some reflective material. The demo gives no problem, but I am confused as to how to approach activating all the 3 sensors and reading the 3 different sets of values so that I can analyze them in a program on the Arduino.

**How can I get all three sensors to output data to my program in parallel?** I want to use the values at the same point in time on all three sensors to do some calculations in my program. Should I approach something like a state machine? Or at least near-parallel (a few ms delay is fine too)? How would an example look like?

The most confusing thing for me is the non-inverted, open-drain protocol it uses. From the documentation:

> Because of the open-drain protocol, the pin used to communicate with the ColorPAL should always be configured as an input, except when being driven low. Also, when starting up, you should wait for this pin to be pulled high by the ColorPAL before trying to send it any commands.

I tried modifying the demo to something silly in sequence like this just to see how it would work in the Arduino but I got nothing (pins 2, 4 and 6 are the data pins):

```
/* ColorPal Sensor Example for Arduino
  Author: Martin Heermance, with some assistance from Gordon McComb
  This program drives the Parallax ColorPAL color sensor and provides
  serial RGB data in a format compatible with the PC-hosted
  TCS230_ColorPAL_match.exe color matching program.
*/

#include <SoftwareSerial.h>

int sio = 0;
const int unused = 255;         // Non-existant pin # for SoftwareSerial
const int sioBaud = 4800;
const int waitDelay = 10;

// Received RGB values from ColorPAL
int red;
int grn;
int blu;

// Set up two software serials on the same pin.
SoftwareSerial serin = SoftwareSerial(sio, unused);
SoftwareSerial serout = SoftwareSerial(unused, sio);

void setup() {

  // Unoptimized setup

      sio = 2;
      serin = SoftwareSerial(2, unused);
      serout = SoftwareSerial(unused, 2);
      Serial.begin(9600);
      reset();                // Send reset to ColorPal
      serout.begin(sioBaud);
      pinMode(2, OUTPUT);
      serout.print("= (00 $ m) !");       // Loop print values, see ColorPAL documentation
      serout.end();           // Discontinue serial port for transmitting

      serin.begin(sioBaud);           // Set up serial port for receiving
      pinMode(2, INPUT);

      sio = 4;
      serin = SoftwareSerial(4, unused);
      serout = SoftwareSerial(unused, 4);
      Serial.begin(9600);
      reset();
      serout.begin(sioBaud);
      pinMode(4, OUTPUT);
      serout.print("= (00 $ m) !");
      serout.end();

      serin.begin(sioBaud);
      pinMode(4, INPUT);

      sio = 6;
      serin = SoftwareSerial(6, unused);
      serout = SoftwareSerial(unused, 6);
      Serial.begin(9600);
      reset();
      serout.begin(sioBaud);
      pinMode(6, OUTPUT);
      serout.print("= (00 $ m) !");
      serout.end();

      serin.begin(sioBaud);
      pinMode(6, INPUT);
}

void loop() {

  sio = 2;
  serin = SoftwareSerial(sio, unused);
  serout = SoftwareSerial(unused, sio);
  readData();

  sio = sio + 2;
  serin = SoftwareSerial(sio, unused);
  serout = SoftwareSerial(unused, sio);
  readData();

  sio = sio + 2;
  serin = SoftwareSerial(sio, unused);
  serout = SoftwareSerial(unused, sio);
  readData();
}

// Reset ColorPAL; see ColorPAL documentation for sequence
void reset() {
  delay(200);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  pinMode(sio, INPUT);
  while (digitalRead(sio) != HIGH);
  pinMode(sio, OUTPUT);
  digitalWrite(sio, LOW);
  delay(80);
  pinMode(sio, INPUT);
  delay(waitDelay);
}

void readData() {
  char buffer[32];

  if (serin.available() > 0) {
    // Wait for a $ character, then read three 3 digit hex numbers
    buffer[0] = serin.read();
    if (buffer[0] == '$') {
      for(int i = 0; i < 9; i++) {
        while (serin.available() == 0);     // Wait for next input character
        buffer[i] = serin.read();
        if (buffer[i] == '$')               // Return early if $ character encountered
          return;
      }
      parseAndPrint(buffer);
      delay(10);
    }
  }
}

// Parse the hex data into integers
void parseAndPrint(char * data) {
  sscanf (data, "%3x%3x%3x", &red, &grn, &blu);
  char buffer[32];
  sprintf(buffer, "R%4.4d G%4.4d B%4.4d", red, grn, blu);
  Serial.println(buffer);
}

```

# Answer
> 1 votes
I'm doing something similar with you right now. I'm troubleshooting this right now so we can collaborate.

First of all, even though you have setup 3 pins, you're only telling the Arduino to read only 1 sensor because they're using the same variable (pin6 since it's the last one you set up). You have to declare each pin with a different variable then create 2 more readData() functions to read each pin as a start. But even after I set it up with that, it only read one colorpal. Reading up a little more on the Uno board, it seems that only pin 2 and 3 can do serial interrupt which we need to use to communicate with the ColorPal. I'm not 100% sure as I'm a novice still, but from what my analysis and research shows, that's the problem right now. I'll update if I find anything.

# Answer
> 1 votes
Try using `serin.listen()` for each SoftwareSerial before using `serin.read()`.

Only one pin can be read at a time and by default it's reading from the last pin initialized.

---
Tags: arduino-uno, arduino-mega, c
---


title: Arduino in-built LED is not turning off

text:
# Question
Title: Arduino in-built LED is not turning off
I have an Arduino Uno whose LED, which is connected to pin 13, is not turning off and it always stays on, and it annoys me.

Touching any exposed pins turns off the LED after removing my hands from the pins it turns back on *slowly*.

However it works perfectly with the programs. This program does turn the LED off and it stays that way while the program is running.

```
void loop() {
  digitalWrite(13, LOW);
}

```

When I upload other programs that don't use pin 13 then it stays on again. How can I fix this?

# Answer
> 3 votes
If you don't tell it to turn off, it behaves "as it wants". If you don't write a 0 on its pin, how can you force it to stay shut down?

If you want it to be in an off state, force it: in your setup function write

```
pinMode(13, OUTPUT);
digitalWrite(13, LOW);

```

No need to refresh it every loop, just in the setup.

# Answer
> 0 votes
You could try to actually remove the LED with a soldering pen... I haven't tried it however, so you could end up disabling pin 13 (or worst).

---
Tags: arduino-uno
---


# Question
Title: How to use FTDI to program Lilypad Arduino?
I am trying to upload a basic Blink code from my computer to Arduino Lilypad contains Atmega 328. While my Blink codes are uploading, **FTDI 1402-C CN480661 FT232RL** module is not responding to the Arduino IDE at the end of the process. So I couldn't upload any codes with this uploading method, I mean using FTDI modules directly.

This is how I do the connections:

This is my Blink code:

```
void setup() { pinMode(13, OUTPUT);}

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

```

I chose **AVRISP mkII** as a programmer. **ATmega328** as a processor. **Arduino Lilypad** as a board on *Arduino IDE* **v1.6.6**

At this point, I got this error:

> avrdude: ser\_open(): can't open device "\\.\COM4": Access is denied

Windows's device manager says: USB Serial Port is attached to COM4, also Arduino IDE saw that.

I downloaded FTDI driver for Windows, but still, I can't upload any code into my Lilypad Arduino.

How can I use FTDI to program my Lilypad Arduino?

# Answer
"Access is denied" this looks like you should at least restart your computer after you installed the FTDI driver if you have not already.

Run Arduino IDE as Administrator and also make sure you are logged into an Administrator account in your windows login.

If all this fails this means another application is using that com port you will need to figure out what could be using that com port another instance of Arduino IDE opened? Etc

If all else fails restart your computer with the usb unplugged, login, open arduino IDE and plug in your usb and select the com port.

Edit: You can also try changing the USB port you are currently using for another one, this will also change your com port to a new number
> 2 votes

# Answer
The error message

> "avrdude: ser\_open(): can't open device "\\\.\COM4": Access is denied"

tells me that the error occurs when the Arduino IDE tries to open a connection to the FTDI adapter "serial port", long before the Arduino IDE actually sends anything through the FTDI adapter to the Arduino.

Have you read the Arduino Troubleshooting guide? The Arduino Troubleshooting guide recommends

> Access to the Serial Port
>
> * On Windows, if the software is slow to start or crashes on launch, or the Tools menu is slow to open, you may need to disable Bluetooth serial ports or other networked COM ports in the Device Manager. The Arduino software scans all the serial (COM) ports on your computer when it starts and when you open the Tools menu, and these networked ports can sometimes cause large delays or crashes.
> * Check that you're not running any programs that scan all serial ports, like USB Cellular Wifi Dongle software (e.g. from Sprint or Verizon), PDA sync applications, Bluetooth-USB drivers (e.g. BlueSoleil), virtual daemon tools, etc.
> * Make sure you don't have firewall software that blocks access to the serial port (e.g. ZoneAlarm).
> * You may need to quit Processing, PD, vvvv, etc. if you're using them to read data over the USB or serial connection to the Arduino board.

If I were you my next steps would be:

* Unplug the USB cable from my computer, and check the "Tools \>\> Serial Port" option. Usually when the USB cable is unplugged, that option is greyed out (empty list), but sometimes there is a few things listed. Remember that list.
* Plug the USB cable from the FTDI back in (preferably in a *different* socket of the computer this time), and check the "Tools \>\> Serial Port" option. Do you remember the list from the previous step? There should be a new item on the list, representing the FTDI adapter -- pick that one.
* I would unplug the FTDI from the Arduino Lilypad, and then tell the Arduino IDE to upload the sketch. Obviously with the Arduino airgapped from your computer it won't be able to upload the sketch, but does it give a useful error message?
* Reboot the computer with nothing plugged into its USB ports. Plug the FTDI adapter directly into the Arduino Lilypad ("BLK" to "B", "GRN" to "G"). Start the Arduino IDE in Administrator mode. Make sure the board type is set correctly. Try to plug in the USB cable, set the Serial Port, and upload a sketch before any other program has a chance to grab that COM port.
> 1 votes

---
Tags: ftdi
---


# Question
Title: How to install a library for a single project
How do you install an Arduino library so it's only available for a specific project?

Say I have a codebase located at /myproject, and I want to install libraries at /myproject/lib/somelib. I can't find how to make `arduino myproject.ino` find the libraries under ./lib.

Googling "installing Arduino libraries" only finds me examples of installing libraries globally (and through the GUI no less), which is horrible practice and guarantees version conflicts.

When I used `ino`, it supported a local ./lib directory, but I can't find any equivalent feature in `arduino`.

# Answer
I ended up switching to ano, which supports a local `lib` directory.
> 1 votes

# Answer
You want to switch to my UECIDE for that functionality. You can then place libraries inside a folder called *libraries* in your sketch folder.

You also get the benefits of a much improved IDE :)
> 0 votes

---
Tags: library
---


title: Arduino Due SPI speed reduction

text:
# Question
Title: Arduino Due SPI speed reduction
I need to reduce the SPI clock speed of the Arduino Due down to about 100 kHz. Unfortunately my hardware doesn't support higher speeds.

With the current maximum divider of 255, I can only reach a speed of still 320 kHz (SPI.setClockDivider(10, 255);).

Of course I could use a software SPI, but I'm still interested in using the build-in hardware. A possible solution could be to lower the overall clock speed of 84 MHz. Any idea how to achieve this?

# Answer
You can try using the SPISettings interface:

```
SPISettings settings(100000, MSBFIRST, SPI_MODE0);

SPI.beginTransaction(settings);
... do your stuff ...
SPI.endTransaction();

```
> 2 votes

---
Tags: arduino-due, spi, code-optimization, oscillator-clock
---


title: arduino uno external power supply

text:
# Question
Title: arduino uno external power supply
I have an arduino uno which is powered by batteries. I have 6 AA-Batteries (1,5V each) connected to Vin and GND.

Thats cool because I don't have any cables and works pretty good. The reason I need 6 AA batteries is, that I have a SIM900-module connected to my arduino uno. My USB Port (5V and 500mA) and my standard external power supply (9V and 1A) doesn't deliver enough current for the SIM900. But with the batteries the SIM900 gets enough power (current).

But there is the problem, that the batteries get sucked empty pretty fast and i don't want to exchange them every day. :-)

I searched for an power supply which can deliver 3A with 9V and found one. But i'm not sure if the arduino uno can handle that input via the on-board power-jack? The reason I want a 3A power supply is, that some users on the internet say that the sim900 sometimes uses more than the maximum current written in the documentation (which is 2A).

I'm an electronic noob.

So is there a risk if I try to use the 9V-3A power supply? Does the arduino only pull the power it needs? So when it needs only 900mA, it only takes 900mA even if the power supply can deliver 3A? As far as I know, it should work, because the batteries deliver as much current as the arduino (ad sim900) needs. So the batteries don't have an ampere limit, right?

# Answer
> 1 votes
The Arduino itself has a limit of about 800mA. That is imposed by the voltage regulator that converts the incoming voltage to 5V.

If you need more than 800mA then you need to provide your own regulated 5V power source and feed it in to the 5V pin (not VIN).

Suitable power sources are mobile phone chargers (*modern USB ones*). They generally come in multiples of amps.

And to answer your theory question - the current is the *maximum* that the supply can provide. It's the voltage that is *fixed* and the current varies depending on the *load*.

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


# Question
Title: Buying Arduino Parts Different Manufacturers
I'm looking to buy my first arduino kit. However I have a concern.

If my Arduino Mega is bought from one manufacturer, then can I buy shields or other parts from other manufacturers? Are there any incompatibility issues

Thanks!

# Answer
Of course you can. In just the same way that you can buy a car from one manufacturer and bumper stickers from another.

That's the whole point of the Arduino platform - mix and match to make things -just like LEGO®.
> 1 votes

---
Tags: arduino-mega, hardware
---


# Question
Title: Cannot control servos through 32-servo-controller on Aurduino Duamilanove
I have servo (TowerPro sg90) connected to 32 servo controller (this one) through UART interface (RX-TX, GND-GND). Seller provide documentation how to connect and control my servos, but it isn't work.

Servo work if I connect it indirectly to Arduino. Controller indicate that it is working too (photo below - red led).

I already try different servos. Also try use provided software to control servos from pc through Mac/PC. But it's interface is unreadable for me. I tried different options but servos not responding.

Sketch code below (from sellers examples):

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

void loop() {
  Serial.print("#3P500T2000\r\n");
  delay(2000);
  Serial.print("#3P1500T2000\r\n");
  delay(3000);
  Serial.print("#3P2500T2000\r\n");
  delay(2000);
  Serial.print("#3P1500T2000\r\n");
  delay(2000);
}

```

Photo of my connections:

Sorry if it post duplicate some, but I cannot google this problem.

# Answer
> 3 votes
There is one connection missing - the one that powers the servo and board.

At the moment your servo board is getting a small amount of power through the RX pin - **disconnect it immediately, you are damaging it**.

You need to provide +5V to the +5V terminal block, and also a suitable voltage (+5V should do) to the VCC on the terminal block.

---
Tags: servo, uart, arduino-duemilanove
---


# Question
Title: How to read RC receiver channels without using pulsein() command with arduino
I am building a quad-copter, the problem is of stability and for better stability lesser sampling time is required. For lesser sampling time I need to have faster loop() function. But the Pulsein() command takes very large time which in turn expands the sampling time. Is there any method to read the rc channels in background and read them from an integer.

# Answer
The keyword you are looking for here is *interrupt*. What is a pulse but a signal that goes from low to high followed by going from high to low, with some period of time between them?

Instead of sitting there waiting for the pulse to arrive then measuring how long it is, which is essentially what `pulseIn()` does, you need to attach the signal to an interrupt pin. Then you write an interrupt routine that triggers when the signal changes from one level to another which looks to see what the level actually is.

If the signal has risen from low to high then you record the time it happened. If the signal has fallen from high to low then you look what the time is, and subtract the time you remembered from when the signal rose. That difference is then the width of the pulse, which you can store in an integer to read in your main loop.

If you have a number of signals you want to monitor you might want to look into using the *pin change interrupt* which allows you to use any pin as an interrupt source.
> 1 votes

# Answer
You may find my answer to another question – *Read RC receiver channels using Interrupt instead of PulseIn* – useful. It includes the sketch shown below, which is intended for background timing of four RC channels attached to pins A0-A3. See the other answer for further comments about the code, example output, etc.

```
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}

```
> 0 votes

---
Tags: arduino-uno, robotics, pid, pulsein
---


title: Using 2 PING Senors at Once

text:
# Question
Title: Using 2 PING Senors at Once
I am trying to get values for two ping sensors, but am not getting any returns, can someone help me edit my code?

# Code

```
void setup()
{
  Serial.begin(9600);
  pingRange(2);
  pingRange(3);
}

void loop(){
}

  long pingRange (int pingPin)

{
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  return microsecondsToCentimeters(pulseIn(pingPin, HIGH));
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

```

# Answer
> 1 votes
There's one part of your code conspicuous by its absence:

```
pingRange(2);
pingRange(3);

```

You're calling the functions, but you're not doing anything with the returned value. I think you meant to print that value to the serial interface...

```
Serial.println(pingRange(2));
Serial.println(pingRange(3));

```

---
Tags: sensors
---


title: OOP vs Inline with Arduino

text:
# Question
Title: OOP vs Inline with Arduino
I have been programming for quite a while now but I am new to Arduino and AVR Programming. The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples?

In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?

Say for example we have a Class:

```
class SomeClass(){

private:
   int x;
   int y;

public:
   void foo();
   void bar();
}

SomeClass thisClass;
thisClass.foo();
thisClass.bar();

```

Would there be any performance or memory gains designing the program in a more inline fashion like:

```
int x;
int y;

void foo(){ /*** Do something ***/};
void bar(){ /*** Do more stuff ***/};

```

I tried doing some searches on Stack Exchange and Google but couldn't find quite the answer I am looking for the closest thing I was able to find was this Stack Exchange Question.

The reason I am asking about this is I have a project that needs to be as light as possible and I am not clear how I should be designing my program in this environment.

---

**Edit**

Thank you for the answers, this has shed light on things. There is one thing that I am not quite clear about.

Say you have a class that you are designing that utilizes the u8glib as follows:

```
class UserInterface{
private:
   U8GLIB_ST7920_128X64 Display;

public:
   UserInterface();
}

```

How would you get around using "Dynamic Memory" like:

```
UserInterface::UserInterface(){
   UserInterface::Display = U8GLIB_ST7920_128X64(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE);
}

```

# Answer
> 2 votes
> The main question I have about programming these Micro-controllers is are there major differences in designing code in Object Orientated Classes vs the more traditional inline programming I have seen in many examples?
>
> ...
>
> In other words in the world of Arduino/AVR Controllers are there any savings with Memory and Performance utilizing classes or visa versa?

Yes, there is a great difference between using C or C++ for small scale embedded systems such as Arduino/AVR. C++ allows more information to be provide for compiler optimizations.

If you are implementing an OOP framework, platform or runtime C++ and classes can also help with software architecture and reuse. In Cosa a number of OOP design patterns are used to achieve interfaces for both application programmers and device driver programmers. The most common is delegation.

Using abstract classes, virtual member functions, inlining, and templates can help achieve lower foot-print and higher performance than traditional implementations. As an example the Cosa Pin classes are X5-X10 faster than the Arduino core and at the same time smaller in foot-print. Please see the benchmarks.

One thing to "unlearn" from traditional C++ programming is the usage of new/delete (malloc/free). With SRAM size of only a few Kbyte using a heap is very much a risk. The answer is static classes and stack based data.

There is much more to be said about OOP framework architecture but I hope this helps answer your initial questions.

Cheers!

# Answer
> 4 votes
The reason you can't find the answer is because the answer is both Yes and No.

For basic class stuff - defining your class with methods etc and instantiating objects from it - there's little difference in the end result compared with "vanilla" C. The compiler's optimizations are so good now that performance is just the same. Yes, there may be slight increases in memory use since you're passing an extra pointer with each method call (instead of `foo(int x)` you have `foo(MyClass *this, int x)`) but that's so small as to not be noticeable.

The big differences come when you start playing with *polymorphism* and other advanced topics. When start doing these complex programs the compiler is not always unable to work out which functions are required and which aren't, and it's not able to cut out the unused functions (*"garbage collection"*). So you may well end up with bigger code.

That doesn't mean slower code, just chunks of code that are hanging around that never do anything.

Of bigger importance is managing your dynamic memory better than you are used to. Since there is such a small amount of memory the heap is very small, and as a result it gets fragmented very easily. Dynamic creation and destruction of objects (`new myClass`, `delete myClassObject`, etc) is very bad. Class objects really need to either be statically defined (in global scope is the most common) or temporarily allocated on the stack (local instances). Otherwise you're asking for trouble - and the first you will know of it is strange things happening (no error reports or exceptions, you see...).

---
Tags: programming, arduino-mega, memory-usage, performance
---


title: Arduino power sources

text:
# Question
Title: Arduino power sources
Is it safe to connect a USB input to an Arduino (Nano) at the same time as an external regulated 5V supply to its 5V pin is connected, assuming the supplies have common grounds ? Will (I hope) the external 5V be used so as to not draw too much current out of the USB supply ?

# Answer
From the Arduino Nano at Arduino.CC:

> The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

Or, take if from the schematic:
> 3 votes

# Answer
OK, I see a section labelled +5V auto selector, with a Schotky diode between +5V and the VUSB rail, I don't understand enough about electronics to see what this does though. I get that if I supply 7V, say, to Vin then the Nano will use that as the 'highest voltage source'. I could perhaps use a variable voltage source fed from the batteries and set it to, say, 5.2V and force the Nano to use that? The reason for all this is that the Nano will be connected to a Raspberry Pi via USB for communicating with the ros system, and the Pi is unable to supply much from its USB ports, it cant run, for example, a WiFi dongle, mouse and keyboard at the same time.
> 0 votes

---
Tags: power, usb, arduino-nano
---


# Question
Title: Looking at Adafruit's website I'm confused which wallcharger I should get
As the title says there are many different wall chargers to choose from.

12v, 9v, 5v, with different mA amounts...

The starter kit on Adafruit's website mentions to get the 9V 1000mA switching power adapter, so I'm curious if that's what we should get?

here is the link to all of them.

There are regular wall adapters, and these big power supplies...

http://www.adafruit.com/search?q=switching+power+adapter&b=1

I'm just looking to run some LED Strip lights from the arduino and power some joystick buttons, some rotary encoder/knobs, and a keypad to work the LED lights

Thoughts?

Thanks!

# Answer
> 0 votes
This website looks like a pretty official answer for you. http://playground.arduino.cc/Learning/WhatAdapter

> Since you'll probably be connecting other things to the Arduino (LEDs, LCDs, servos) you should get an adapter that can supply at least 500mA, or even 1000 mA (1 ampère). That way you can be sure you have enough juice to make each component of the circuit function reliably.

And

> The Arduino's on-board regulator can actually handle up to 20V or more, so you can actually use an adapter that puts out 20V DC. The reasons you don't want to do that are twofold: you'll lose most of that voltage in heat, which is terribly inefficient. Secondly, the nice 9V pin on the Arduino board will actually be putting out 20V or so, which could lead to potential disaster when you connect something expensive to what you thought was the 9V pin. Our advice is to stick with the 9V or 12V DC adapter.

# Answer
> 0 votes
Your Arduino Uno will use 35 to 50 mA at 5V. The “joystick buttons, some rotary encoder/knobs, and a keypad” will draw a small amount of current, probably between 1 and 10 mA. Thus, power for the Uno and your controls will be well under 100 mA and can be supplied via USB without any problem. (Also see: *How to get more than 100mA from a USB port*.)

If your Uno enumerates and negotiates to get 500 mA via USB, you might have 450 mA available out of the +5V pin. However, in some cases if you need more than a few dozen mA to power other devices, it will make sense to get a separate 5V supply for them. (Eg, if the devices drag down the +5V and cause the Uno to reset, or if the devices are electrically noisy, like motors, RC servos, relays, solenoids.) Also, note that thread #70450 at forum.arduino.cc says you can draw 650 mA (or 3.25 W of power) when the Uno is powered via its DC power jack.

If your LED string has up to 6 or 7 WS2812B equivalents, you can power it from the Uno's 5V. Here is the all-lights-on, full-brightness calculation for six of them: 6 WS2812Bs x 3 LEDs per WS8211 x 21 mA per LED = 378 mA. For seven: 7 x 3 x 21 mA = 441 mA, which is out there on the edge.

For longer LED strings, figure on a little over 3 W of power for every 10 WS2812B equivalents. (Calculation: 5 volts x 10 WS2812Bs x 3 LEDs per WS2812B x 21 max mA per LED = 3150 mW = 3.15 W.) For example, get a 10 W (2 A x 5 V) or greater 5V power supply for a meter of 30- WS2812B-per-meter LED strip, etc. This power supply will connect directly to the LED strip's power connectors. The ground from the LED strip will connect to the Uno's ground, to establish a signal reference point.

Note, the absolute max voltage rating for a WS2812B, according to its datasheet, is 5.3 V, so use a supply whose voltage does not exceed 5.3 V. The absolute min voltage rating is 3.5 V; they will work ok on 3.7 V LIPO batteries, but 3V3 power is out of spec for a WS2812B.

As mentioned in a previous question, if your LED strip is being installed inside a desktop PC, the PC's power supply will have lots of 5 V power available, and you can hook on to one of the red +5V wires and black Gnd wires from its supply to power the LEDs, either while powering the Uno itself from USB power or while using the same +5V to power the Uno as the LEDs.

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


title: Newbie and string of 300 WS2811s

text:
# Question
Title: Newbie and string of 300 WS2811s
I’m trying to make a string of 300 Christmas tree lights where the colour of each of the lights is entirely controllable by my own code. I am a programmer so that side of things is the easy part as far as I’m concerned.

My researches so far have led me (no pun intended) to WS2811s driven by an Arduino. I prefer the look of these to the flat Adafruit-type ones. I don’t own an Arduino yet but have been dipping my toe into this site for quite a while now so am beginning to understand the basics.

I’ve established that I will need to have a fairly hefty 5volt power supply for the LEDs but that the Arduino itself can then run happily on its own USB supply.

Some of the things I’ve read seem to imply that the Arduino will struggle to process my program and supply the data to 300 LEDs at the same time, but it’s not clear what the problem will be. I assume each LED will continue to glow with the same colour until it receives the data for its next colour and the code for “Fire!” which then prompts all of them to switch to their next colour. Is this wrong?

I realise that 3 bytes per LED for 300 LEDs is a fair amount of data to keep having to send up the wire. I will also be having an array in the program to keep track of all 300 colour values.

Will this work? Can you offer any advice that might mean I don’t hit a brick wall somewhere when putting all this together?

# Answer
I don't think you'll have any problems. The LED's have a data rate of 800kbps, so you can theoretically push out 110 frames per second if your Arduino does nothing but transmit data. If you keep the routine that updates the colors fairly efficient then you'll have nothing to worry about.

Note that the array storing the colors would take up 900 bytes of memory, leaving you with only 1100 bytes for everything else your program would need to store (which should be fine).
> 1 votes

---
Tags: led, rgb-led
---


title: Using a state machine

text:
# Question
Title: Using a state machine
I'm trying to get a strip of Neopixels to circle through its length, one LED at a time, I want it to do it faster as the value received from the sensor increases

```
#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure,
    barometricToRGB,
    frequency       = 0,
    high            = 0,
    low             = 600,
    interval        = 50;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR_PIN,INPUT);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  airPressure = analogRead(SENSOR_PIN);
  autoTune();

  unsigned long currentMillis = millis();
  Serial.print("frequency ");
  Serial.println(frequency);
  Serial.print("Time to beat ");
  Serial.println(frequency*interval);
  Serial.print("Last Called ");
  Serial.println(currentMillis - previousMillis);

  if(currentMillis - previousMillis > (frequency/interval)) {
    previousMillis = currentMillis;

    for (int i=0; i<NUM_LEDS; i++) {
          leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
          FastLED.show();
        }
  }
}

void autoTune() {
  if (airPressure < low) {
    low = airPressure;
  }
  if (airPressure > high) {
    high = airPressure;
  }
  barometricToRGB = map(airPressure, low, high, 1, 255);
  barometricToRGB = constrain(barometricToRGB, 1, 255);
  frequency = map(airPressure, low, high, 1, 100);
  frequency = constrain(frequency, 1, 100);

}

```

While I had managed to cause the color to change based on the sensor, I can't seem to understand how to control how fast it will go, every how long.

# Answer
Ok, if I understood what you meant, you want that a single led in the ring is on and the refresh rate is dependent on the pressure, right?

If so, you did not write any "select this led" code, so it can't work.

I fixed a couple of things in your code. Mainly:

1. added the circularity to the ring (with variable `currentlyOnLed`)
2. fixed some types (use the `byte` unless you need a bigger type)
3. removed some `constrain`s, which were reduntant
4. `frequency*interval` instead of `frequency/interval` (I guess it was a typo)
5. I prefer summing the step instead of setting `previousMillis` to `currentMillis`, so you will not add error with time passing
6. moved `FastLED.show()` outside the loop: I'm not sure about this, but I think that you don't need to call it every loop. I can't test it, anyway.

So, here is the fixed code. Let us know if it works for you

```
#include <FastLED.h>
#define NUM_LEDS    34
#define DATA_PIN    6
#define SENSOR_PIN  A0

int airPressure;
int high  = 0;
int low   = 600;
byte barometricToRGB;
int frequency = 0;
byte interval = 50;
byte currentlyOnLed;

long previousMillis = 0;

CRGB leds[NUM_LEDS];

void setup() {
    Serial.begin(115200);
    pinMode(SENSOR_PIN,INPUT);
    FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
    currentlyOnLed = 0;
}

void loop() {
    airPressure = analogRead(SENSOR_PIN);
    autoTune();

    unsigned long currentMillis = millis();
    Serial.print("frequency ");
    Serial.println(frequency);
    Serial.print("Time to beat ");
    Serial.println(frequency*interval);
    Serial.print("Last Called ");
    Serial.println(currentMillis - previousMillis);

    if(currentMillis - previousMillis > (frequency*interval)) {
        previousMillis += (frequency*interval);

        //Set next on led
        if (currentlyOnLed >= NUM_LEDS - 1)
            currentlyOnLed = 0;
        else
            currentlyOnLed++;

        for (byte i=0; i<NUM_LEDS; i++) {
            if (i == currentlyOnLed)
                leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB);
            else
                leds[i] = CRGB::Black;
        }
        FastLED.show();
    }
}

void autoTune() {
    airPressure = constrain(airPressure, low, high);
    barometricToRGB = map(airPressure, low, high, 1, 255);
    frequency = map(airPressure, low, high, 1, 100);
}

```
> 2 votes

# Answer
Are these reversed?

```
high            = 0,
low             = 600,

```

It looks like high and low both get set to airPressure on the first pass through autoTune(). If the pressure drops after this, for example, low will track airPressure and high will stay the same.

Also, with frequency 1 to 100 and interval 50 the largest time difference is 2 milliseconds and the smallest is 0. Your loop could be taking 2 ms without the if statement.
> 1 votes

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


# Question
Title: How can I connect the MP503 to an Arduino Uno (Smoke, Alcohol Sensor)?
I don't know how I can connect an MP503 sensor to my Arduino.

Please help.

http://eleparts.co.kr/data/design/product\_file/SENSOR/gas/MP503%20(Ver1.4)%20-%20Manual.pdf

# Answer
> 3 votes
Ok, first of all I doubt you will be able to get a lot of measurements with that. Because... I know that kind of sensors and you will quickly get tired of it.

Anyway, you have to connect

1. pin 1 to +5V
2. pin 2 to ground
3. pin 3 to +5V
4. pin 4 to a resistor towards ground. Value has to be determined.

To chose the value, you have to try. Change resistor values until, in fresh air, the voltage you can sense across the resistor is approx 1V. I think it is arount 10k, but you'll have to try

Chosen the resistor, you have to simply attach the node between pin 4 and the resistor to an analog input and then read the voltage.

Now you have to calibrate the sensor. Put it in a fixed-concentration gas and measure the voltage: `nCalib = analogRead(sensorPin);`.

Then, when you need to measure the concentration, you just have to read the voltage again with `nMeas = analogRead(sensorPin);`. The factor Rs/Ro can be calculated with the formula

```
Rs_over_Ro = nCalib / (1024 - nCalib) * (1024 - nMeas) / nMeas;

```

Once you have the factor, look at the graph in figure 3 to get the concentration:

As I told you, I think you will quickly get tired of it, but this is how to use it.

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


# Question
Title: How to read a higher voltage digital input?
Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.

I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.

How can I do this?

# Answer
> 1 votes
As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes.

This EE.SE post has some good info about this, related to ADC, but still the same.

First off, a voltage divider circuit is easily found on the internet,

1. Google
2. Wikipedia

This circuit from Hyperphysics shows the basics:

---

To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the **Vout**. That would give you something like this(Olins):

This will give you the desired range to give legitimate High and Low on an I/O.

---

If you wanted to forgo the voltage divider and zener you can use clamping diodes to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.

simulate this circuit – Schematic created using CircuitLab

The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.

---

Another method, which I have used before and is reliable, is to use a diode and two resistors like below:

The logic is that, when the input `IN` is \> Vcc(5V) the signal on the I/O `_IN` will be the voltage of the pull\_up resistor `R2`, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.

*Edit*: Changed the image to proper logic flow.

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


# Question
Title: I2C connection with MT9D111 camera module, strange results after writing registers via i2C
I am currently working on a camera platform based on the MT9D111 module from Micron. The first thing to do is to write the configuration to the numerous registers of the chip which is done via an i2C connection.

I adapted the code from here for testing this with an Arduino Uno. 3.3V supply and 8MHz clock are also provided by the Arduino.

Everything seems to work fine, but there are some odds which I don't know the reason for.

So here is the code (I just added the soft reset sequence according to the Developers Guide):

```
const int freqOutputPin = 9;   // OC1A output pin for ATmega328 boards

#define TMR1 0

#include <Wire.h>
#include <avr/io.h>
#include <util/delay.h>
//#include <TimerOne.h>
#include <avr/interrupt.h>

void setup() {
  pinMode(freqOutputPin, OUTPUT);
  Serial.begin(9600);

  TCCR1B |= (1 << CS10);  //selecting prescaler 0b001 (Tclk/1)
  TCCR1B &= ~((1 << CS12) | (1 << CS11)); // turn off CS12 and CS11 bits
  TCCR1A |= ((1 << WGM11) | (1 << WGM10)); //Configure timer 1 for TOP mode (with TOP = OCR1A)
  TCCR1B |= ((1 << WGM13) | (1 << WGM12));
  TCCR1A |= (1 << COM1A0); // Enable timer 1 Compare Output channel A in toggle mode
  TCCR1A &= ~(1 << COM1A1);
  TCNT1 = 0;
  OCR1A = TMR1;

  delay(500);  //Initial delay
  Wire.begin(); // join i2c bus as master
  Serial.begin(9600);
  Serial.println("MT9D111 Camera Module + Arduino");
  Serial.println("Read and Write 16-bit register value example");
  Serial.println("*  Read expected value = 0x1519 from Register 0x00");
  Serial.println("*  Write value = 0xA5F0 to Register 0x20:1");
  Serial.println();
  init1(); //execute code just 1 time
}

void loop() {
}

void init1() {
  int16_t a;

  delay(500);  //wait until start
  Serial.print("Soft reset first");
  Serial.println();
  soft_reset();//do a soft reset at startup

 //***************Configuration here!****************//
  Serial.print("Read result from register 0x00");
  a = read_reg(0);
  Serial.println();
  Serial.print("0x");
  Serial.println(a, HEX);  //print result
  Serial.println();
  Serial.print("Read original data from register 0x0a, should be 11");
  Serial.println();
  a = read_reg(10);
  Serial.print("0x");
  Serial.println(a, HEX);  //print result
  Serial.println();

  //Enable this part for writing register
  //Some example reads and writes follow
  Serial.print("Writing 0xA5F0 in register 0x20:1");
  Serial.println();
  write_reg(32, 1, 165, 240);
  Serial.print("Read new value from register 0x20:1");
  Serial.println();
  a = read_reg(32);
  Serial.print("0x");
  Serial.println(a, HEX);  //print result
  Serial.println();
  Serial.print("Writing 0xA1F3 in register 0x20:1");
  Serial.println();
  write_reg(32, 1, 161, 243);
  Serial.print("Read new value from register 0x20:1");
  Serial.println();
  a = read_reg(32);
  Serial.print("0x");
  Serial.println(a, HEX);  //print result
  Serial.println();
}

//Write 2Byte register
void write_reg(int reg_address, int page, int data_msb, int data_lsb) {
  delay(5);  //5ms
  Wire.beginTransmission(93); // transmit to device 93, Camera Module
  Wire.write(240);   //page register address
  Wire.write(0);
  Wire.write(page);   //select page 0/1/2
  Wire.endTransmission(1);    // stop transmitting
  Wire.beginTransmission(93); // transmit to device 93, Camera Module
  Wire.write(reg_address);   //register address 8bit, decimal
  Wire.write(data_msb);  //msbyte
  Wire.write(data_lsb);  //lsbyte
  Wire.endTransmission(1);    // stop transmitting
}

//read 2Byte register
//be careful about selected register page
int16_t read_reg(int reg_address) {
  int16_t err;
  delay(5);  //5ms
  Wire.beginTransmission(93); // transmit to device 93, Camera Module
  Wire.write(reg_address);   //register address 8bit, decimal
  err = Wire.endTransmission(1);    // stop transmitting
  Serial.println(err);
  Wire.requestFrom(93, 2, 1); //request value form device 93, 2 bytes with stop bit
  int16_t result = ((Wire.read() << 8) | Wire.read());  //read 16 bits
  return result;
}

//Perform Soft reset, required at startup
void soft_reset(){
  write_reg(101, 0, 160, 0);//write registers according to dev guide
  write_reg(195, 1, 5, 1);
  write_reg(13, 0, 0, 33);
  delay(5);
  write_reg(13, 0, 0, 0);
  delay(5);//wait for i2c to be ready again
}

```

Running this code gives me the following result on the serial monitor:

So here are the questions:

1. Do you have any ideas why I get an extra FFFF when reading a register after writing it? (underlined in blue)
2. Why are there some extra zeros in the output? (marked in yellow)

# Answer
The `0` comes from your code:

```
Serial.println(err);

```

It's printing the error code. 0, hence no error.

As for the extra `FFFF` I'd say it's because you are using signed integers. Change your `a` declaration to `uint16_t` and see if that fixes it.
> 1 votes

---
Tags: arduino-uno, serial, programming, i2c
---


# Question
Title: Using digital pin 11 for DMDCon and IR remote
I have a project where I would like to control a countdown clock using a remote with:

Arduino Uno R3 Development Board

Funduino Uno Protoshield Board

Freetronics Dot Matrix Display Connector

Arduino IR Reciever

Both the DMDCon and the IR use digital pin 11. Can these two share the pin 11 or is there a workaround of sorts?

# Answer
> 1 votes
The workaround would be to configure the https://github.com/shirriff/Arduino-IRremote library referenced in your question to any available digital input.

---
Tags: arduino-uno, led, ir
---


# Question
Title: Is it possible to transmit using an NRF24L01+ without an Arduino?
I have two NRF24L01+ modules which are transceivers, but for my project I would like to send a very simple signal from one of these modules to the be read by the other.

That would've been very simple if I had an Arduino on each side but due to power consumption constraints as well as size, cost and practicality, the transmitting side won't have one. Would it still be possible to do this?

To clarify, the message itself is not important and can be set in stone, it will never change. I really just want to detect on the receiving side (which will have an Arduino) that the transmitter is in fact transmitting. Transmission will be triggered by a push-button.

Ideally I would have a way of identifying my particular transmitter from others on similar frequencies but I am not too precious about that.

# Answer
> 5 votes
The nRF24L01+ has a somewhat complex SPI based interface, where many registers have to be configured and tested and timeouts honored. Therefore it requires some kind of microcontroller to send or receive even the simplest message.

This can be as simple as a 3.3v Arduino Pro Mini (less than $3 with shipping), and there are libraries which simplify the task of interfacing to it - in particular see the RF24 library (there are many variations, see https://github.com/TMRh20/RF24 for a good one).

But many other microcontrollers could work as well.

Once you bite the bullet and accept the need for a microcontroller, yes the code can identify the source of the signal (which pushbutton) and much, much more.

Or you could use a dedicated device like an xBee which can be configured using a Windows utility to send the state of an input pin to another xBee; basically there is already a programmed microcontroller on the module along with the radio (not nRF24L01+ compatible).

# Answer
> 3 votes
An ATTiny85 can drive the NRF24L01+: "nrf24l01+ control with 3 ATtiny85 pins"

At least this is not a "full" Arduino...

Edit 2015-06-06:

Hackaday News: "EMBED WITH ELLIOT: MULTIPLEXING SPI USES FEW PINS"

The referred blog entry is: "nRF24l01 control with 2 MCU pins using time-division duplexed SPI".

(-: Nice countdown... 3 pins, 2 pins, ... ;-)

# Answer
> 3 votes
Note, there is also the NRF24LE1 SoC which has its own ULP MCU - good for transmitting simple data such as sensor readings. If used to Arduino, ARduino Pro Mini 3.3v and the NRF24L01+ is easier and better way to go. (Mod the Arduino to be ULP)

# Answer
> 2 votes
The nRF24L01+ needs an external microcontroller to be used.

I believe an XBee could be used if you want a "single module" solution, however using even the Atmega328p (standard for Arduino Uno) would probably be cheaper than this.

# Answer
> 0 votes
1) Easy way

This transmitter uses *only* SPI interface so you need to drive it some logic unit, i.e. microcontroller that supports this interface (i.e. AVR atmega8) and is able to use driver for this module as a ready to use set of high level functions to express your intentions in your code.

2) Badly bad way

You can use the SPI to I2C converter as well. Connect it to your computer via serial port - but note that it's a big effort. You will need to port nRF24L01 driver, etc.

http://www.elecrow.com/nrf24l01-wireless-shield-spi-to-i2c-interface-for-arduino-p-737.html

---
Tags: networking, system-design, remote-control
---


# Question
Title: Serial: What is different between Gammon's RS485 (blocking) and RS485 "non blocking" libraries?
The RS485 master-slave communication library on Nick Gammon's page http://www.gammon.com.au/Arduino/RS485\_protocol.zip is working for me OK, but on the same hardware wiring is not working for the non-blocking library http://www.gammon.com.au/Arduino/RS485\_non\_blocking.zip.

I can not find information about the connection of MAX485 on Arduino for non-block version. Is MAX485/RS485 from HW serial (ie Rx=0 and Tx=1)?

If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor? Thank you for the explanation.

When I added the SoftwareSerial library into Nick's example for non-blocking, so it works, but is it still a non-blocking?

```
//Master:
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 4;
SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

size_t fWrite (const byte what) {
  return mySerial.write (what);
}

RS485 myChannel (NULL, NULL, fWrite, 0);

void setup () {
  Serial.begin (9600);
  mySerial.begin (28800);
  myChannel.begin ();

  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}  // end of setup

const byte msg [] = "Hello world";

void loop () {
  digitalWrite (ENABLE_PIN, HIGH);  // enable sending
  myChannel.sendMsg (msg, sizeof (msg));
  digitalWrite (ENABLE_PIN, LOW);  // disable sending
  delay (1000);
}  // end of loop

//Slave:
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 4;
SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

int fAvailable () {
  return mySerial.available ();
}

int fRead() {
  return mySerial.read ();
}

RS485 myChannel (fRead, fAvailable, NULL, 20);

void setup() {
  Serial.begin(9600);
  mySerial.begin(28800);
  myChannel.begin();
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}  // end of setup

void loop() {
  if (myChannel.update()) {
    Serial.write (myChannel.getData(), myChannel.getLength());
    Serial.println();
  }
}  // end of loop

```

Regards, Vava (Sorry for my English... :-)

# Answer
Reference page: http://www.gammon.com.au/forum/?id=11428

---

The blocking library is intended where you want to wait for incoming data, and are prepared to do nothing else while it arrives. There is also a timeout parameter which lets the code proceed if nothing happens for a specified number of milliseconds.

The non-blocking library is intended for where you need to do other things (like control motors, or read switches) at the same time you are receiving data. For that situation you call an `update` function periodically which assembles the incoming packet, byte-by-byte if necessary.

When the data is fully received the `update` returns true, and you can process the packet.

---

> If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?

As I stated above in neither case do you receive and print "at the same time", however the non-blocking one does not simply wait until all the data has arrived.

---

Example code from the linked page:

```
void loop ()
  {
  if (myChannel.update ())  // returns true when packet fully received
    {
    Serial.write (myChannel.getData (), myChannel.getLength ());
    Serial.println ();
    }

  // do other things while waiting

  }  // end of loop

```

---

> If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins?

The hardware is the same.

---

> there is limitation for use - only pins which supports change interrupts.

Of course. If the underlying protocol is SoftwareSerial then the usual limitations apply (that is for the Rx pin).
> 2 votes

# Answer
The hardware connection should be the same, as blocking vs non-blocking is referring to how you handle the incoming data packets.

Don't quote me on this, but generally, blocking vs non-blocking refers to the use of `delay()` or similar, which will block anything else from running while that function is being executed.
> 0 votes

---
Tags: serial, rs485
---


# Question
Title: Using a class instance with Wire.onReceive
Is it possible to register a class instance member function with Arduino's Wire.OnReceive?

I'm trying to make my code object-oriented, and want a specific non-static class function to handle I2C data, but if I'm reading this thread correctly, `onReceive` is incompatible with classes since it only accepts a function pointer, which won't store context.

# Answer
> 0 votes
A non-static class member function has an implicit `ClassName *this` parameter inserted as the first parameter in the parameter list.

Because the function prototype required for `Wire.onReceive()` does not have that parameter specified in its parameter list a non-static member function is not compatible with it.

The same goes for `attachInterrupt()` and anything else that takes a function pointer.

---
Tags: wire-library
---


title: ESP8266 & websockets

text:
# Question
Title: ESP8266 & websockets
At the moment, I'm using various operating systems and devices like the Raspberry pi to control lights and other stuff over websockets. I use websockets since they added the support on Chrome. I write a lot of Javascript stuff for fun. Websockets allow you to communicate with another server without the need of reloading a page. It's a lot better than Ajax. Once the connection is open with a web server data can travel both ways. No unnecessary headers to send. No unnecessary requests. You just send only the data you want, this in both directions. AND FAST, DAMN FAST.

For example I use Javascript's `requestAnimationframe` to send RGB values (based on music frequency) to lamps connected to the network. `requestAnimationframe` executes approximately at 60 Hz. But that's not the highest speed, I also created some "web controllers" to control servos and other stuff with touch and mouse events. In that case it probably touches transmission frequencies of 200-300 data packets (normally I use JSON- encoded strings) or more per second.

Websocket servers have also broadcast which allows you for example to control multiple RGB lamps based on the music you play from basically every modern device that has a browser. I don't use "normal" sockets because of the simple fact that there is no support for sockets in a standard web browser. So I would need to create a custom iOS app, custom Windows app, custom Android app. I said that we know that websockets are made for a fast multi-user / multi-device / bidirectional communication. And it should be really fast or it's useless.

Lately I have a lot of fun with electronics and MCUs, so I made even more lamps and stuff controlled from Arduinos, ATtinys and other microcontrollers. I'm new to C++ but since I write Javascript code since the previous century I just have to slightly modify old Javascript functions to run in the Arduino IDE.

But for sure I'm not ready to write a perfect library for an MCU, so I need to use what I find online.

Apparently there are not many people into websockets. I tested 2-3 Arduino websockets libraries and couldn't get them to work properly.

The last one I tested(Links2004) works but I can't send a 4 decimal string faster than 2 times per second or it crashes.

All I did was to add this code for testing:

```
void onWebsocketMessage(uint8_t * payload) {
 analogWrite(13,atoi((const char *)payload));
}

```

Where `payload` is the data received.

Problems that could slow down/crash everything:

1. My code. Does `atoi` take too much to execute?
2. My code. Is the `(const char *)` cast filling memory?
3. The lib itself?

I know that the CPU memory or whatever else is not the problem because of this video:

https://www.youtube.com/watch?v=8ISbmQTbjDI

He gets realtime stats from the controller at 200-600 Hz.

While it's supercool and I could just install that "custom firmware" I prefer to stay in the Arduino IDE for now.

How to fix websockets on the ESP8266 device using Arduino IDE?

Or maybe can I extract only the websocket part from that firmware (CNLohr's Video)?

Suggest another lib?

I posted here because I use the Arduino IDE. And the ESP8266 has also been part of the Arduino world for a while. And maybe some not so popular Arduino-based websockets work also on the ESP8266.

Wouldn't it be nice to control your ws2812b strip with a web interface showing the preview like this?

http://jsfiddle.net/dgws3usa/5/

---

**EDIT**

links2004 @ github

1. The network should be fine. It's a relatively expensive Cisco/Linksys N router at 20cm/8inch away from the ESP8266 module.
2. Luckily the module I'm using is one of the modules listed in the Arduino IDE, the MOD-WIFI-ESP8266-DEV, but I have another one with fewer GPIOs.
3. I just noticed now that I programmed it at 80 Mhz instead of 160 Mhz.
4. The program I uploaded consists only of the basic websockets server example with in addition just the code posted above.
5. If `atoi` is the problem/is slow, what are other ways to convert the received array to a string?
6. I use both the latest versions of the Arduino ESP8266 port and the arduinoWebSockets. At least I guess so. I followed the install instructions one day before I asked this question.
7. By crash I mean, while moving the range slider, if updating in realtime with `addEventListener('input',function,false)` at some point (after 1 sec/ 3-4 messages send/received) it stops sending or receiving data. By the way, the video you posted seems to work properly with a lot more code. Also that guy updates in realtime with `oninput` vs 'onchange', which would only update when the user releases the slider.
8. I think for now I can't use `Serial.setDebugOutput(true);` as I didn't get the serial communication working. I'm using a cheap CH340G to program the chip.

Japanese post.

9. I'm doing exatly the same thing but in a much simpler way. No web server, no ping pongs, no serial stuff, I don't use complex functions to elaborate the web server's data. Altough his example works.
10. He is doing, code-wise, a lot more than I do.

for(i=0; i\<4; i++) { mask\[i\] = client.read(); } byte m\_data\[data\_len\]; char data\_c\[data\_len\]; Serial.print("Receive Data = "); for(i = 0; i1-0x30); break; case 3: data\_b = ((data\_c\[0\]-0x30)\*100) + ((data\_c-0x30)\*10) + (data\_c-0x30); break; } LED\_PWM(data\_b);

My full "test" code:

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsServer webSocket=WebSocketsServer(81);
void webSocketEvent(uint8_t num,WStype_t type,uint8_t * payload,size_t lenght) {
  switch(type) {
    case WStype_DISCONNECTED:
      break;
    case WStype_CONNECTED:
      {
      IPAddress ip=webSocket.remoteIP(num);
      }
      break;
    case WStype_TEXT:
      analogWrite(13,atoi((const char *)payload)); // MY CODE
      webSocket.broadcastTXT(payload,lenght);
      break;
    case WStype_BIN:
      hexdump(payload,lenght);
      webSocket.sendBIN(num,payload,lenght);
      break;
  }
}
void setup() {
  pinMode(13,OUTPUT); // MY CODE
  for(uint8_t t=4;t>0;t--) {
    delay(1000);
  }
  WiFiMulti.addAP("ssid","pass");
  while(WiFiMulti.run()!=WL_CONNECTED) {
    delay(100);
  }
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}
void loop() {
  webSocket.loop();
}

```
11. I normally write Javascript code. Converting a string to a number or vice-versa is much simpler. `num=1; str=1+''; num=str*1;` So all this binary array is relatively new for me.
12. Note that while I convert the binary array to an int now. In the future I need to convert that to a string which then will be parsed. Something like JSON. And so update more channels per message.
13. On the client side, like I said, I'm sending the data really fast. So if there is no buffer on the server side that could be a problem. Solving that is simple: `requestanimationframe`. Continuously check if the input changed. That allows you to send the data every 16-17ms. So 60 Hz. Not slower, Not faster. But again that should be the maximum pause between messages.

I said that I will reprogram it at 160 Mhz now and hope there are other ways to convert the received data faster and hope for updates relative to my code.

---

**EDIT2**

Right. The serial works. Reprogrammed the ESP8266 At 160 Mhz.

The error I get when when I set `Serial.setDebugOutput(true);` is:

```
LmacRxBlk:1

```

If you need some other information just ask.

**EDIT3**

Sorry for the late response.

```
webSocket.broadcastTXT(payload,lenght);

```

Broadcasting seems to be the problem. I just have a few minutes so for now I can't do the describe debug stuff... But I will do as soon as I have a little more time.

**EDIT4** for Aditya Tannu

Added

```
#include <NeoPixelBus.h>
#define pixelCount 16
NeoPixelBus strip = NeoPixelBus(pixelCount,13);

```

Inside the webSocketEvent function

```
case WStype_TEXT:
for(uint8_t i=0;i<pixelCount;i++){
 strip.SetPixelColor(
  i,
  RgbColor(i==(atoi((const char *)payload)%pixelCount)?255:0,0,0)
  // i need to put the above outside of the loop.
  // it does not work if i do so
 );
}
strip.Show();
break;

```

HTML JS

```
var ws,form;
function msg(a){
  console.log(a);
}
window.onload=function() {
  form=document.getElementById('form');// change
  ws=new WebSocket('ws://IPNUMBER:PORT');// change
  ws.onopen=function() {
    ws.send('0');
  };
  ws.onmessage=msg;
  form.addEventListener('input',function() {
    ws.send(this.firstChild.value) // firstchild is the range
  }, false);
}

```

vid, I use a logic level converter from 3.3v to 5v: pca9306.

**EDIT 5** for Links2004

> I think I should rework the examples. It looks like most users don't understand it well.

Nono. At some point you need to broadcast back the actual position anyway.

Sorry. I forgot to test the debug stuff again. But we know it's the broadcast. We just need to send back data only when there is not too much traffic.

# Answer
> 1 votes
I tried to port Charles Lohr's implementation to esp8266/Arduino. An initial working version is up here: https://github.com/AdySan/ESPSocket

I'm able to get ~150Hz without any disconnections or crashes. I'll keep working on it to add more functionality and hopefully improve speed.

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


title: Teensy MIDI Show Control

text:
# Question
Title: Teensy MIDI Show Control
I'd like to use my Teensy 3.1 to send MIDI Show Control messages using USB MIDI in order to control an ETC Nomad system. These are different from standard NoteOn, NoteOff, ProgramChange, etc. commands, but as far as I can tell they are not supported by the standard library.

Is there any way I can send these messages directly (using lower level commands), as seen here, or does anyone know of a library that supports this? Google has, unusually, not been much help.

# Answer
According to the documentation, SysEx messages are sent like any other messages:

```
array[0] = 0xf0;
array[1] = 0x7f;
array[2] = 0x7f;
array[3] = 0x02;
array[4] = 0x7f;
array[5] = 0x01;
array[6] = 0xf7;
usbMIDI.sendSysEx(7, array);

```
> 5 votes

---
Tags: teensy, midi
---


title: Pixel font resources in byte format

text:
# Question
Title: Pixel font resources in byte format
To write text on a dot-matrix or LC display with an Arduino you need to have a pixel font in byte format (i.e. typically 1 bit = 1 pixel). On the Internet I have found surprisingly few resources for this.

Most of the results when searching for pixel fonts return true-type fonts (or similar) which are rather complicated to convert to obtain a satisfying result. Also, most of the fonts are rather high resolution. Any good resources I have missed?

# Answer
The UTFT library has a SmallFont which is 8x12. Not sure whether this is too big for you, but it could be worth looking into. It is ASCII only, so you might want to add some characters yourself. But as someone mentioned, memory is limited, so add sparingly.
> 1 votes

# Answer
You could create the character data yourself. I've built a little script for a similar prospect a while ago that does translate a matrix of checkboxes to a bit-array: http://jsfiddle.net/qrsye920/
> 0 votes

# Answer
Try the Dot Factory and The LCD Assistant. I'm happy with both. Let's you create any Windows font.
> 0 votes

---
Tags: display
---


# Question
Title: Making Servo Motor Automatically Move Based on Input
sorry if I sound incompetent, but I know nothing about coding. I have a group project where I must sort various balls into different tracks. The final issue I have is that I must use an arduino for this portion. However, none of us know how to program, and the only experience we have is from doing the lessons from adafruit (copy and paste written code).

What I am attempting to do is attach a paddle to the tip of a high torque servo motor. I will then automatically feed the servo signals, ranging from 0 to 5. Each signal tells which position for the servo to turn to. Could anyone please help guide me in how to write this code? I was thinking of using this guide for my motor. However it uses a POT. My project must be completely automated. The positons also are all within 180\*.

Thank you!

# Answer
So you have a "number" and you want to set the servo to some angle. The logic is very simple:

* If number is 0 then set angle to 90
* If number is 1 then set angle to 45

etc.

How you "get" the number hasn't been specified, so I will assume you just have an integer with a value between 0 and 5 inclusive.

Setting a servo's angle is as simple as *writing* that angle to the servo:

```
servo.write(45); // Set the angle to 45 degrees

```

So how do you join the two together? Well, there's three different ways that spring to mind.

1. A string of `if` statements
2. A switch construct
3. An array

The first one is just like the bullet points above, just written as C:

```
if (number == 0) servo.write(90);
if (number == 1) servo.write(45);
... etc ...

```

The second method is very similar but can be more efficient when you know you only ever select one item from a list of options. Read this to see how: http://hacking.majenko.co.uk/time-to-make-a-switch

The third option, the array, is especially good when you have a lot of options to manage and they are all the same result with a different value:

```
const int angles[6] = {90, 45, 315, 0, 0, 0};

// ... later ...
servo.write(angles[number]);

```
> 1 votes

---
Tags: motor, servo
---


# Question
Title: multiple connection with ISP Pin at Arduino Micro
Actually I'm not good at English ;-) trying to ask to you. please understand me :)

I needed connect SD card Shield and TFT LCD Screen to Arduino Micro.

successfully finished compile at source code but when i connect MISO together

it doesn't work. only SS pin is connected separate Pin's to Micro

How can i make it work together to Micro..

i've checked each device perfectly work at Micro

Plese Help me!!

Regards and Thanks

# Answer
> 2 votes
Each SPI device must have a separate device/slave select pin. The device must disconnect (high impedance state) when not selected. The SD shield will have a level shifter. It may not correctly disconnect from MISO.

Depending on what libraries you are using you might also need to check that they set the SPI hardware attributes correctly (clock, mode, etc).

For more help please post code and references to the shields and libraries.

Cheers!

---
Tags: arduino-micro, isp
---