# Question
Title: Do I need the Motor Shield to drive servo motors?
I was perusing Arduino's list of official shields and noticed the Motor Shield that can be used to drive up to 2 servo motors.

Being brand new to Arduino/robotics, I am wondering: do I *really* need this shield to drive a set of servos?

* What does this shield really offer in the way of driving motors?
* What is lost by *not* using this shield?
* What if I my project has more than 2 motors?!?

# Answer
> 1 votes
The shield will drive a pair of DC motors (the common small ones in models), or one stepper motor (the precision motors you find in dead printers, etc), and can also connect onwards to other stuff, which happens to include servos. I certainly wouldn't get one to run a servo...
If you want more than two motors, there are other motor shields, or you could make a custom board to suit. There isn't enough power from Arduino outputs to drive a motor (in general) so some sort of driver is needed - for a simple DC motor, a simple transistor would do, you need bridges for steppers, or ESC's for RC-model type high-power motors. Servo's have their own drivers built-in, so can just plug-in to Arduino.
If you just want to control a couple of motors or a single stepper, the shield is quick & easy, which is where it is placed in the market.

# Answer
> 2 votes
The Motor Shield is for driving bare motors, not servos. Servos already include drive electronics and only require a PWM signal in order to control them, whereas the Motor Shield provides the drive electronics for bare motors.

# Answer
> 2 votes
You don't need this shield to drive *servo* motors, they have their own controller, you need just a 5V power line, GND and digital output pin to generate a PWM and that's it. Usually Arduino has enough power to drive **servo motors**.

This shield you are talking about is used for DC (direct current) and stepper motor. These motors need power gain and the shield provides it and often has a chip called L298N (which implements H-bridge) with MOSFETs to properly feed the motor.

**What does this shield really offer in the way of driving motors?**

A proper circuit and components so you plug your motor and connect into your board leaving you just the programming task to control motor's position and speed.

**What is lost by not using this shield?**

Actually, you use this kind of component just for practice purposes. It is already built and you just use it. However, it's a good learning process building the H-bridge yourself and understanding how it works and why it is necessary (if you have time, this is a good task).

**What if I my project has more than 2 motors?!?**

Well, just decide how many H-bridges you need. This shield has the capacity for 2 DC motors or 1 stepper motor. In case they are servo motor, you just use this lib. It is possible to have plenty of servos working together and all you need are good battery and enough digital pins. They share timers of microcontroller, that's why it works for many motors.

---
Tags: arduino-uno, motor, servo, arduino-motor-shield
---


# Question
Title: what ftdi windows driver for arduino nano
at http://www.ftdichip.com/FTDrivers.htm they seem to divide chips into two categories, FT4222H vs. D2XX driver.

What's the correct for a arduino nano?

# Answer
> 2 votes
The Official Arduino Nano has an FTDI FT232RL.

You want to use the Virtual Com Port(VCP) Driver so the FTDI device appears as a COM port under windows.

See the getting started guide for details.

---
Tags: arduino-nano, ftdi
---


title: RGB LED Strips with Arduino

text:
# Question
Title: RGB LED Strips with Arduino
I am trying to control an RGB LED strip with an Arduino. I have followed the tutorials in both of these websites:
Using MOSFETs: https://learn.adafruit.com/rgb-led-strips?view=all
Using LED Amplifiers: http://www.instructables.com/id/LED-Strip-Controller-w-LED-Amp-Arduino/
I have tried both setups and none of them work for me. When I try the setup with the MOSFETs, I am able to control each color but the blue LEDs are dimmer than the red and green, and therefore I can't mix any colors with blue.
When I try the LED Amplifiers, I am not able to control any light at all. Only the blue LEDs light up but the red and green dont. Also the blue LEDs stay ON the whole time and the only way to turn them off is to disconnect them from the DC power source.
What am I doing wrong?

# Answer
For the mosfet circuit. Are you using an external power supply? The reason why you cannot mix any color might be due to the fact that you're not providing enough current to the led strip, so it just work fine when turning on each channel individually. Check the current the led strip draws (which usually is provided as amp per channel per meter) and use a power supply that can provide enough current for it.

From the adafuit page

> Connect a 9-12V power supply to the Arduino so that Vin supplies the high voltage to the LED strip. If you want, you can also just use a separate wire that connects to a power supply that provides about +12V. Make sure to connect the ground of that supply to the ground of the Arduino/MOSFETs!
> 2 votes

# Answer
The LED strip with blue ones requires a higher current drive. Arduino output pins can drive only 20mA max(ideal). Try an external power source.
> 2 votes

# Answer
From the drawings in that instructable, you need the Arduino ground and the 12 volt ground connected together - perhaps the line you have marked "+3v or 5v" should really be ground?
> 0 votes

# Answer
Your 12 strip probably puts each set of 3 LEDs in series. 3 Red LEDs take about 6V to be fully on, while 3 blue LEDs take about 9V; when you have 12v the resistors absorb the rest of the voltage drop (higher value resistors are needed for the red LEDs if you want about the same current in each color). Driving 3 in series is good - the same current travels through 3 LEDs producing 3 times as much light per amp than if each LED was separately driven. (Or from another perspective, with 3 in series the LEDs get 6-9v and thethe resistors and power amp need to drop the 3-6v from a 12v supply, versus a single LED dropping 2-3v and the resistors and power amp dropping the other 9-10v).

All is good, if you are driving each color with close to 12v.

BUT - your LED amplifier may expect more than 5v inputs in order to be fully on (eg: if it uses conventional FETs). Driving it with 5v may not fully turn on the LED driving transistors. In that case, the LEDs may be seeing less than 12V. The blue LEDs would be the first to suffer from this voltage sag.

Note that if this is the case, the LED amplifier may also overheat - the transistors dissipate more power when not fully on, which raises the temperatures, probably leading to shortened life at best, possibly release of the magic smoke that makes electronics work.

You can test this. Disconnect the Arduino. Connect the +12v to one of the inputs at a time. If that color is now fully bright, then you have shown that 12v input fully turns on the driving transistor, but 5v does not.

(If your LED amplifier says it's designed to be driven by 5v, do not do this test. Many of them however expect to be driven by the tail end of a previous strip, at roughly 12v)

An example of an LED amplifier which **IS** designed for 5v inputs: http://www.usledsupply.com/shop/rgb-mini-amplifier-ttl.html I have not used this device and am not recommending it, just using it as an example. Note that it appears that for this amplifier, you would connect the Arduino's +5 to the input (along with the PWM outputs from the Arduino), rather than ground - and the PWM sense would be reversed, with lower PWM values being brighter, because the amp would turn on when the output pin was **low**.
> 0 votes

---
Tags: mosfet
---


title: nRF24L01+ Arduino mpu6050

text:
# Question
Title: nRF24L01+ Arduino mpu6050
How do I ever understand what the Arduino IDE means when they advise you of any errors? The reason I ask is because I got several errors that don't make sense to me as I see what the error means and what line the issue is but I don't see anything wrong with the code. It's written how it should be, the reason I say this is because before I ended the code I was compiling/verifying my code every time I write a new line just to make sure if I got new errors. It's easy to check as it was more than likely the very last line of code I just wrote, rather than write a book then do a spell check you know?

I have included the part of the code where I get errors and the errors themselves. Hopefully someone can point out to me what is it that Arduino sees that I don't and in the same token I'll learn how to counter measure those errors.

```
1.  //imu's
2.  #include "Wire.h" // i dont think this will be needed on this mcu's "slaves"
3.  #include "I2Cdev.h" // i dont think this will be needed on this mcu's "slaves"
4.  #include "MPU6050.h" // i dont think this will be needed on this mcu's "slaves"
5.
6.  //motors
7.  #include "Servo.h" // select which motor this slave mcu has and comment out the other
8.  #include "Stepper.h" // select which motor this slave mcu has and comment out the other
9.
10. //wireless
11. #include "nRF24L01.h"
12. #include "RF24.h"
13. #include "SPI.h" // i dont think this will be needed on this mcu's "slaves"
14.
15. #define RF_CS 12
16. #define RF_CSN 13
17. RF24 radio(RF_CS, RF_CSN);//RF24 radio(9, 10);
18. const int pinCE = 9;
19. const int pinCSN = 10;
20.
21. byte bArray[] = {0000, 1000, 0100, 1100, 0010, 1010, 0110, 1110}; // this are the Ch 0/7 address from Mux
22. const uint64_t LA = 0xF0F0F0F0D2LL;//mcu1 address of Slave
23. const uint64_t RA = 0xF0F0F0F0C3LL;//mcu2 address of Slave
24. const uint64_t LL = 0xF0F0F0F0B4LL;//mcu3 address of Slave
25. const uint64_t RL = 0xF0F0F0F0A5LL;//mcu4 address of Slave
26. const uint64_t LW = 0xF0F0F0F0E6LL;//mcu5 address of Slave
27. const uint64_t RW = 0xF0F0F0F0F7LL;//mcu6 address of Slave
28. const uint64_t UT = 0xF0F0F0F0F8LL;//mcu7 address of Slave
29. const uint64_t BT = 0xF0F0F0F0F9LL;//mcu8 address of Slave
30.
31. /* MUX CH address To simplify things, 1 is HIGH, 0 is LOW
32.                                                                     0000 – 0
33.                                                                     1000 – 1
34.                   A multiplexer of this sort really just            0100 – 2
35.                   acts as a 16 to one 1 switch. The 4 digital       1100 – 3
36.                   pins are used to set HIGH or LOW, in a binary     0010 – 4
37.                   fashion (0-15) to determine what pin “SIG” is      1010 – 5
38.                   connected to. So bringing all 4 pins LOW would    0110 – 6
39.                   switch the CD74HC4067 to channel 0 (so SIG and    1110 – 7
40.                   C0 would be connected), bringing them all HIGH    0001 – 8
41.                   would switch it to 15 (so SIG and C15 would be    1001 – 9
42.                   connected)                                        0101 – 10
43.                                                                     1101 – 11
44.                                                                     0011 – 12
45.                                                                     1011 – 13
46.                                                                     0111 – 14
47.                                                                     1111 – 15 */
48.
49. int recivers[8][4] = {
50.   { 0xF0F0F0F0D2LL, { 0, 0, 0, 0 }, //0000 – 0 SDATA line from MPU to Multiplexer ch0
51.     { 0xF0F0F0F0C3LL, { 1, 0, 0, 0 }, //1000 – 1 SDATA line from MPU to Multiplexer ch1
52.       { 0xF0F0F0F0B4LL, { 0, 1, 0, 0,}, //0100 – 2 SDATA line from MPU to Multiplexer ch2
53.         { 0xF0F0F0F0A5LL, { 1, 1, 0, 0 }, //1100 – 3 SDATA line from MPU to Multiplexer ch3
54.           { 0xF0F0F0F0D6LL, { 0, 0, 1, 0 }, //0010 – 4 SDATA line from MPU to Multiplexer ch4
55.             { 0xF0F0F0F0E7LL, { 1, 0, 1, 0 }, //1010 – 5 SDATA line from MPU to Multiplexer ch5
56.               { 0xF0F0F0F0F8LL, { 0, 1, 1, 0 }, //0110 – 6 SDATA line from MPU to Multiplexer ch6
57.                 { 0xF0F0F0F0F9LL, { , 1, 1, 1, 0 } //1110 – 7 SDATA line from MPU to Multiplexer ch7
58.                 }
59.               }
60.             }
61.           }
62.         }
63.       }
64.     }
65.   }
66. }
67.
68. MPU6050 mpu;
69. int16_t ax, ay, az;
70. int16_t gx, gy, gz;
71.
72. long long  val[6];//6 DOF MPU 6050 thats where this val{6} come from
73. long val;
74. long prevVal;
75.
76. byte bArray[] = ( 0, 180 );
77.
78. //Mux control pins on the Arduino Digital pins
79. int s0 = 8;
80. int s1 = 7;
81. int s2 = 6;
82. int s3 = 5;
83.
84. //Mux in "SIG" pin
85. int SIG_pin = 0;
86. //int val = readMux(7);
87.
88. void setup()
89. {
90.   pinMode(s0, OUTPUT);
91.   pinMode(s1, OUTPUT);
92.   pinMode(s2, OUTPUT);
93.   pinMode(s3, OUTPUT);
94.
95.   digitalWrite(s0, LOW);
96.   digitalWrite(s1, LOW);
97.   digitalWrite(s2, LOW);
98.   digitalWrite(s3, LOW);
99.
100.      Wire.begin();
101.
102.      for (int i = 0; i < 10; i++) //10 mpu's
103.      {
104.        mpu.initialize();
105.      }
106.
107.      radio.begin();
108.      radio.payload = 6;
109.      radio.setAutoAck(false);
110.      radio.setDataRate(RF24_2MBPS);
111.      radio.openWritingPipe();
112.    }
113.
114.    void loop()
115.    {
116.      for (int i = 0; i < 16; i ++)//Loop through and read all 16 values
117.      {
118.        int readMux(int channel)
119.
120.        int controlPin[] = {s0, s1, s2, s3};
121.
122.        int muxChannel[8][4] = {
123.          {0, 0, 0, 0}, //channel 0
124.          {1, 0, 0, 0}, //channel 1
125.          {0, 1, 0, 0}, //channel 2
126.          {1, 1, 0, 0}, //channel 3
127.          {0, 0, 1, 0}, //channel 4
128.          {1, 0, 1, 0}, //channel 5
129.          {0, 1, 1, 0}, //channel 6
130.          {1, 1, 1, 0}, //channel 7
131.          {0, 0, 0, 1}, //channel 8
132.          {1, 0, 0, 1}, //channel 9
133.          //  {0, 1, 0, 1}, //channel 10
134.          //  {1, 1, 0, 1}, //channel 11
135.          //  {0, 0, 1, 1}, //channel 12
136.          //  {1, 0, 1, 1}, //channel 13
137.          //  {0, 1, 1, 1}, //channel 14
138.          //  {1, 1, 1, 1}  //channel 15
139.        }
140.      }
141.      //loop through the 4 sig
142.      for (int i = 0; i < 4; i ++)
143.      {
144.        digitalWrite(controlPin[i], muxChannel[channel][i]);
145.      }
146.
147.      //read the value at the SIG pin
148.      int val = analogRead(SIG_pin);
149.
150.      //return the value
151.      return val;
152.
153.      for (int i = 0; i < 6 i++)
154.      {
155.        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
156.        val[0] = map(ax, -17000, 17000, 0, 180);
157.        val[1] = map(ay, -17000, 17000, 0, 180);
158.        val[2] = map(az, -17000, 17000, 0, 180);
159.        val[3] = map(gz, -17000, 17000, 0, 180);
160.        val[4] = map(gy, -17000, 17000, 0, 180);
161.        val[5] = map(gx, -17000, 17000, 0, 180);
162.
163.        radio.openWritingPipe(recievers[i].address);
164.        radio.write(val);
165.      }
166.
167.      delay(50);

    Arduino: 1.6.4 (Windows 8.1), Board: "Arduino Nano, ATmega328"

    sketch_may19a:57: error: expected primary-expression before ',' token
    sketch_may19a:66: error: braces around scalar initializer for type 'int'
    sketch_may19a:68: error: expected ',' or ';' before 'MPU6050'
    sketch_may19a:73: error: conflicting declaration 'long int val'
    sketch_may19a:72: error: 'val' has a previous declaration as 'long long int                val [6]'
    sketch_may19a:76: error: redefinition of 'byte bArray []'
    sketch_may19a:21: error: 'byte bArray [8]' previously defined here
    sketch_may19a.ino: In function 'void setup()':
    sketch_may19a:104: error: 'mpu' was not declared in this scope
    sketch_may19a:108: error: 'class RF24' has no member named 'payload'
    sketch_may19a:111: error: no matching function for call to         'RF24::openWritingPipe()'
    sketch_may19a.ino:111:25: note: candidate is:
    In file included from sketch_may19a.ino:12:0:
    C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:324:8: note: void     RF24::openWritingPipe(uint64_t)
    void openWritingPipe(uint64_t address);
    ^
    C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:324:8: note:   candidate         expects 1 argument, 0 provided
    sketch_may19a.ino: In function 'void loop()':
    sketch_may19a:120: error: expected initializer before 'int'
    sketch_may19a:139: error: too many initializers for 'int [8][4]'
    sketch_may19a:140: error: expected ',' or ';' before '}' token
    sketch_may19a:144: error: 'controlPin' was not declared in this scope
    sketch_may19a:144: error: 'muxChannel' was not declared in this scope
    sketch_may19a:144: error: 'channel' was not declared in this scope
    sketch_may19a:151: error: return-statement with a value, in function     returning     'void' [-fpermissive]
    sketch_may19a:153: error: expected ';' before 'i'
    sketch_may19a:155: error: 'mpu' was not declared in this scope
    sketch_may19a:156: error: invalid types 'int[int]' for array subscript
    sketch_may19a:157: error: invalid types 'int[int]' for array subscript
    sketch_may19a:158: error: invalid types 'int[int]' for array subscript
    sketch_may19a:159: error: invalid types 'int[int]' for array subscript
    sketch_may19a:160: error: invalid types 'int[int]' for array subscript
    sketch_may19a:161: error: invalid types 'int[int]' for array subscript
    sketch_may19a:163: error: 'recievers' was not declared in this scope
    sketch_may19a:164: error: no matching function for call to 'RF24::write(int&)'
    sketch_may19a.ino:164:20: note: candidate is:
    In file included from sketch_may19a.ino:12:0:
    C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:281:8: note: bool     RF24::write(const void*, uint8_t)
   bool write( const void* buf, uint8_t len );
    ^
    C:\Program Files (x86)\Arduino\libraries\RF24/RF24.h:281:8: note:candidate     expects 2 arguments, 1 provided
    expected primary-expression before ',' token

```

# Answer
> 3 votes
You do know that you assign 6 different values to val, before you use the last one?

And assigning 4 interrupts? I have to question how well you understand what you are doing.

Google pastebin for a method of posting all of your code before asking for help. And be sure to include what you have already tried and how it failed. People are much more likely to help, as opposed to do it for you.

update: As pointed out using pastebin is not a good long term solution, just a quick fix.

You are doing quite a few newb things in your code. There is nothing wrong with that we were all newbs at some point.

First, you are driving 21 servos? Assuming you board has 21 PWM pins, do you realize they could be drawing up a half amp or more each? If at 1/2 that it would still be around 5 amps, that is probably 100 times more than the Arduino can handle. So I hope you have made provisions to power them externally.

The first real error is on line 130. You define a stepper motor called GzUT, then you pass it to a function expecting a pin number. This is not correct, and I also suspect the 'stepper' library would already set up the pins and there is no need for you to do that. Even beyond that, you declare the GzUT as part of a structure, but you never create a variable that is made of that structure.

This is indicative you are not an experienced programmer, and an embedded program is not the place to learn how to program.

You are trying to do too much at first. Go slower. Get 1 servo (or stepper) to work. then add the others once you understand how to do that. Refer to samples from the stepper library web site. (http://www.arduino.cc/en/Tutorial/MotorKnob)

The MPU-6050 is also a somewhat more advanced sensor. It look like you plan on multiplexing them? With an I2C multiplexer? Have you thought out the addressing? Do you have any idea of timing requirements of 21 servos and multiple i2c data streams and if the processor is even capable of meeting those requirements? My experience with an Arduino UNO is it barely can keep up with 1 mpu-6050. I doubt if you can add more than one servo.

The Arduinos in general are awesome prototype platforms. They are great for learning embedded programming. But they are not so good for just learning to program in general, especially when you are trying to do a lot of work, of which 21 servos certainly qualifies as. Again, my recommendation would be slow down, do one small thing at a time, or if this is a real project, contract it out to someone with experience.

Update: I didn't mean to offend. It is just unclear from your question and your code how much experience you have or do not have. That being said, I am not able to figure out which of the rlf2401 libraries you are trying to use. There 5 of them mentioned on this Arduino page http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01. So follow up with which one you used and I will take a look.

---
Tags: arduino-ide, compile
---


# Question
Title: Writing C Program outside of Arduino IDE?
I like the idea of using the Arduino IDE for simple projects and for getting started with Arduino, but the *consensus* I've gotten so far is that it is for those who are new to Arduino and/or programming in general.

My *understanding* is that it is possible to write a C program from scratch, completely outside of the Arduino IDE, and then use a tool like AVRDUDE to upload it to an Arduino MCU. This option, albeit appealing and interesting, leaves me with a few concerns:

* What Arduino libraries would need to be imported/linked by such a "raw C" program? I assume that when an Arduino IDE-based program executes a `digitalWrite(...)` it is *really* calling a C lib, probably provided by Arduino, under the hood. I am concerned about making sure all these "underlying libs" get included with my C program. Thoughts?
* Is anything else "lost" by flying solo and venturing outside the Arduino IDE? Any capabilities/features that I would now have to "roll my own"?

# Answer
Here you are two nice articles how Arduino actually works in background. How it removed friction from microcontroller programming.

1. A Tour of the Arduino Internals: How does Hello World actually work?
2. Arduino and GCC, compiling and uploading programs using only makefiles

It was also discussed here Is there a way or tutorial for converting Arduino code to C code?
> 4 votes

# Answer
You're absolutely right about needing to link against other libraries. However, you don't necessarily need to worry about all of the details yourself, unless you want/need to do something unusual. Several alternative IDEs already support Arduino, typically via plugins which handle a lot of the details automatically.

I normally recommend Eclipse as it's a very widely used IDE for various purposes. However, there are several other possibilities. See this question for more information:
> 5 votes

# Answer
Yes, you can write a program outside Arduino IDE. For example I tried Eclipse IDE with AVR plug-in and now I stick with AVR Studio. Of course,you won't have some functions that you maybe usually use when you write in Arduino IDE and also some libraries. But, why not to try implementing stuff. Why to limit yourself to functions and libraries made by others when you can learn and write your owns, maybe better than the existing ones.
> 1 votes

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


# Question
Title: Undefined functions send() and receive() on TwoWire/SPI
I have downloaded a sketch that uses SPI. The sketch includes the Wire library but at compilation time, I am getting errors that TwoWire doesn't have methods called `send()` and `receive()`?

# Answer
This is caused by the sketch you downloaded being old. In prior releases, the methods called `send()` and `receive()` were used to send and receive SPI data. These were renamed to be `write()` and `read()`. If you change your code where there are references to `Wire.send()` and change to `Wire.write()` and also change `Wire.receive()` to `Wire.read()`, you should find that your applications compile and run correctly.
> 7 votes

---
Tags: spi, wire-library
---


# Question
Title: How do i properly read an analog pin on attiny85?
Anyone ever run into a problem with your attiny not reading your analog pins correctly? (-1023 or 1023 or 0 value) How did you resolve the issue?

Here's what my code looks like now :

4th revision of code as of 5/6/2015 8pm:

```
int NTC = A1; // thermistor
int switchPin = PB1; // push button
int LED = PB0;  // led

// button latch
byte ButtonState;
byte lastState = LOW;
byte count = 0;

 //brightness level of each different mode
int low = 50;
int med = 140;
int high = 255;
int dim = 0;

int ADCcount = 0;

void setup()
{

 pinMode(switchPin, OUTPUT);
 pinMode(LED, OUTPUT);

  }

 void loop()
 {

  ADCcount = analogRead(NTC);

delay(100);

  ButtonState = digitalRead(switchPin);

  if(ButtonState && ButtonState != lastState)  // button latch, no debounce      needed.
   {
      if(count < 4) // This will check to see if the count is within a range of  0 - 255
                 // anything over that, it will reset count back to 0. Of course
      count += 1;  // same as count = count + 5;
      else
      count == 0;
        }

    lastState = ButtonState;

   if (count == 0)
  {analogWrite(LED,0);}
    else if (count == 1) { if(ADCcount < 500) {analogWrite(LED,high);}
      else{ if(ADCcount > 525){analogWrite(LED,low);}
       }
          }
      else if (count == 2 ){analogWrite(LED,med);}
      else if (count == 3) {analogWrite(LED,low);}
      if(count >=4) {count = 0;}
      delay(50);
 }

```

---

simulate this circuit – Schematic created using CircuitLab

# Answer
The improper bush-button event handling is likely to cause the problem. One way to properly react to the external environment signals could be constant polling or using interrupts. With constant polling, all the time is spent on the checking the status of the button. With interrupts, the program is executed as it should, and only if interrupt happens - the execution jumps to the interrupt subroutine, executes it, and goes back to the main code where it left off.

In your case, you can use pin 7, for example, for push button signal. It can have a function of *INT0*. Read *Section 9. Interrupts* of the datasheet - it is straight forward.

I do not completely understand what your program should do, but I will try to convey the general approach of using subroutines:

```
volatile bool pressed = false;
int main(void)
   {
   MCUCR |= (1<<ISC01 |1<<ISC00);       // set INT0 to interrupt on rising edge of pin7
   sei();                               // enable global interrupts

   while(1){
      if (pressed) then do something; //You can disable interrupts here so your code is not interrupted by cli();
      pressed = false; // reset the state
      else do something else;
   // you can re-enable your interrupts here by sei();
   }
}

// only happens when the change on pin 7 is from LOW to HI
ISR(INT0_vect){
pressed = true; // update the pressed status
}

```

If you want to use pin6 for push button, you should enable the PCINT1 instead of INT0 and change the ISR to handle the PCINT1 interrupt. In this case, pin 6 will react on voltage toggle (from HI to LOW, or the other way) and you can not discriminate rizing/falling edges. In that way, you must read pin6 within the instruction subroutine to know if it is hi or low.

**EDIT:**

I would suggest to stop the calculations in the *Temp()* function after the

```
  average = SERIESRESISTOR / average;

```

line due to the fact that you have only three operating modes for the LED. Thus you can, back calculate the *average* value that makes your *steinhart* value to be, for example \>30. This way, all other values greather/smaller than that value will also fall under the same condition depending on whether average/steinhart are directly/inversely proportional.

When you determine the three ranges of raw *average* values you can use them directly in the *Mode()* function. Eventually, you can optimize you code even further, by performing monotonic read instead of burst reads. If you keep a buffer, you do only one addition of the most recent sample and subtracting the oldest sample. For this you will need two pointers and one memory for to store *sum*, but you will not need to do nSamples additions:

```
read (newSample);
sum += newSample;
sum -= oldestSample;
average = sum/numSamples;
update pointers to the memory for oldest sample and for the feature sample;

```
> 1 votes

---
Tags: attiny
---


# Question
Title: Use Adafruit 16-Channel 12-bit PWM/Servo Shield to switch relays
I'm wondering if using the Adafruit 16-Channel 12-bit PWM/Servo Shield is it possible to switch relays, such as use that shield as a multiplexer and use digital output without PWM.

Is it possible? example code?

# Answer
That will work. Just make sure you are not using Servo part of the library, but only the PWM part, and set the duty cycle to 100%. The relay should still work, even if the duty cycle is slightly lower, as the magnetic field takes a bit of time to collapse. Just make sure you don't forget to add a (flyback) diode to the relay.

Looking at the datasheet I think you need to use the following code

```
pwm.setPWMFreq(1000);//put this in setup()
...
// enable relay at channel 15
pwm.setPWM(15, 1, 0);
...
// disable relay at channel 15
pwm.setPWM(15, 1, 1);

```
> 1 votes

# Answer
Using the adafruit PWM servo shield seems like overkill, you are paying for a lot facilities (PWM) that you won't be using. If you want to use the shield to reduce the number of pins used on your arduino board, consider a pair of shift out registers (74HC595 for example). The relays need a logic 1 or a logic 0 to change state. You send a bit pattern to the shiftout register that sets the output pins of the shift register to 1 or 0. I found this page helpful.
> 0 votes

---
Tags: pwm, adafruit, multiplexer
---


title: Arduino YUN real time control

text:
# Question
Title: Arduino YUN real time control
I have a very specific problem, exactly with real time control. For example I try to write an application where I can edit min or max temperature that after reaching it , I will receive SMS with message. I'm wondering how to edit variables "on-the-fly" because, as I know Arduino IDE use it own libraries not this from C/C++, and I don't know how to get to SD card in Arduino too. Can someone help ?

Thanks

# Answer
the SD card is at /mnt/sd/ . you should consider reading the yun tutorials here before going further, the ability to send and receive data is at the heart of the yun design.
> 1 votes

---
Tags: arduino-yun
---


title: Programming question for Time Arduino

text:
# Question
Title: Programming question for Time Arduino
Can you program a sketch so that if the time is between 1m and 10m then it will reset itself? Reset I found already, it is the if that I don't know.

# Answer
> 2 votes
You can use the timer interrupts. For example:

```
#define F_CPU   16000000UL
#include <avr/delay.h>
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
...
ISR(TIMER1_COMPA_vect)
{

  //do something every seconds when interrupt is raised.

}
void setup()
{
/*the following code will setup timer register to generate interrupt
  when 15624 is reached, at a clock frequency of 16 MHz and 1024 prescaler. This means that     every second an interrupt is generated
*/
  cli();          // disable global interrupts
  TCCR1A = 0;     // set entire TCCR1A register to 0
  TCCR1B = 0;     // same for TCCR1B

  // set compare match register to desired timer count:
  OCR1A = 15624;
  // turn on CTC mode:
  TCCR1B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR1B |= (1 << CS10);
  TCCR1B |= (1 << CS12);
  // enable timer compare interrupt:
  TIMSK1 |= (1 << OCIE1A);
  sei();          // enable global interrupts
}

```

The code works on Arduino Uno. You should calculate the value of OCR1A for your frequency.

---
Tags: arduino-uno, programming, time
---


title: Multithreading Leds and Joystick

text:
# Question
Title: Multithreading Leds and Joystick
I'm trying to made a program that turn on and turn off leds with an input and send the coordinates of joystick, but, in the loop, the arduino makes one at a time, and i want make this in the same time. How can i make that?

# Answer
One way to do this is to use the millis() function.

millis() returns the current value of a timer that is incremented once per millisecond (hence the function name). You can compare the value of millis() at some past time with the current value to determine how many milliseconds have passed. By having multiple compare registers you can have multiple independent delays operating. (There is also micros() which increments at the 1 uS rate (with a "granularity" of 4uS on some processors).

This code is an example only. It MAY run but has not been tested and probably contains silly mistakes which do not affect its example purposes.

A function ToggleLED(n) is assumed which toggles the specified LED n from 1-\>0 or 0-\>1 as required.

LED1 will flash 200 mS on, 200 mS off, ...
LED2 will flash 333 mS on, 333 mS off, ...

The two loops are essentially independent.

---

```
unsigned long delay1; delay2;

void setup(){

int FlashTime1 = 200; / LED 1 will have a 200 on 200 off cycle
int FlashTime2 = 333; / LED 2 will have a 333 on 333 off cycle

delay1 = millis() + FlashTime1;  / Init LED timers
delay2 = millis() + Flashtime2;
}

void loop()
{
  if (millis() == delay1){ / Not until delay expired.

    ToggleLED(1);
    delay1= millis() + FlashTime1; / Reinit flash timer}

  if (millis() == delay2){

       ToggleLED(2);
       delay2= millis() + FlashTime2;}

}

```
> 1 votes

# Answer
> the loop is something like this:
>
> ```
> loop() {
> controlleds();
> joystickevent();
> }
>
> ```
>
> but he runs, controlleds first, and joystickevent next, i want at the same time.

There are typically two ways to read a simple potentiometer joystick: Connect it in a voltage divider and measure the analog voltage; and connect it in an R-C circuit and measure the time for the capacitor to charge.

The first way is faster and you should not be able to notice the time difference between controlling the LEDs and reading the joystick.

The second way takes longer and you might be able to notice. If this is how your joystick controller works, you would need to separately start the joystick reading, continue to poll the buttons control the LEDs, and check whether the joystick reading is ready yet. The joystick routine must not delay, waiting for the measurement to finish.
> 0 votes

---
Tags: arduino-uno, led, shields, ethernet, threads
---


# Question
Title: Arduino Stepper Motor Standing Desk help!
I currently have a standing desk at work, and I thought a fun way to learn Arduino would be to automate it, as it currently uses a hand crank.

I would love some help determining what I would need for this task.

What kind of motor should I use? -Stepper motor? -High/low rpm? -High/low torque?

What sort of power would I need?

Looking forward to hearing people's suggestions!

# Answer
I think this might end up being more of a fun way to electrocute yourself, but let's find out...

Energy required to lift an object with mass "m" an upward distance of "h" in the Earth's gravitational field, on the surface... E = mgh = m(9.8)h

So, to lift a 50kg desk one meter, we will need 50 x 9.8 x 1 = 490 Joules

How fast do you want to lift it? Let's say we want it to take 10 seconds - that will give us the power level we need. Power is in watts (Joules per second) - so if we want to lift the desk in 10 seconds we need 49 watts - let's call it 50.

Now, to produce 50 watts with a 12-volt battery, that would be 4.2 Amps. This is do-able, and it's not the high power level I expected for lifting a desk. Even if we throw in some efficiency losses, we're well within the safety zone and won't have to get out the high voltage equipment. So, I'm glad I did the math - my initial impression of this task was the joke at the beginning of the post.

So, you need a 50 watt motor... that's easy to find. Hell, why not go way over that and get a 100-watt motor... google that...

http://www.electricscooterparts.com/motors24volt.html \- bang! Scooter motors! Nice!

So, that's an example of how you might figure out what parts to get - it all starts with basic physics and ends with Google (or Bing if you're one of *those* people). I simplified a lot, but you get the idea.

The other part of this task is to figure out the control system. I would probably not use Arduino to do this. I would have three switches - one "directional" switch to run the motor, and two sensor switches to disconnect the directions of the motor at each end of the track. I think that's how automatic power windows in cars used to work, which explains why if you didn't hold the button down long enough, it would immediately instead of continuing to the other end - it was still sitting on the sensor.

Sticking an Arduino in the mix and having it read the sensors would just waste power all day long, but you could do it that way. It's the same idea - just mount sensors on the track, which get tripped when the desk rolls up to that spot. Coding wouldn't be that tricky - when the user activates the "change button" or whatever, check which sensor is currently active, and move the desk the other way until the other sensor activates.

You're going to need a good power supply for that motor - a 24-volt **2**00-watt power supply if you like to over-engineer like I do. You'll need a relay to control the motor - it needs to handle 24 volts/200 watts. Then you'll need some kind of activation button, and two sensors. You want some kind of sensor that is definitely going to be activated when the desk is in position, or you risk over-running your target, binding the mechanics, and burning the motor, and possibly the office as well. So, I would choose some kind of mechanical sensor, not a light sensor or something like that.

This should get you started on finding those parts... https://www.sparkfun.com/categories/145 \- these are all kinds of buttons and switches - you should be able to find something that you can mount to the track which will activate when the desk runs into it. Search on this site for the other parts - they have the relays and stuff too.

Final warning though - this may be too complicated and dangerous for a first project. At 24 volts and 100 watts, we are getting into dangerous power levels. But, these are common power levels in consumer equipment. So, if you know what you're doing you should be safe. If you don't, I strongly suggest getting an experienced electrical engineer to look at your designs. Also, you probably can't install this device in an office - there is an insurance reason that it hand-cranks, your company isn't just being cheap.

What happens if someone bumps the desk and it becomes active when you're not around? What happens when the power goes out? What happens when the power comes back on? Do we have enough fuses in the right places to shut this system down before it catches fire? You need to consider all that.
> 4 votes

# Answer
For initial playing, and possibly for a final solution, battery powered electric drills with external powering are an excellent source of reasonable wattage well geared down motors. Drills are often discarded when the batteries die and may be available free or at lo cost.

For relatively low duty cycle use 9V drills operate OK on a small 12V battery and drills rated at up to 18V usually operate well enough on 12V.

Use of a 12V lead acid battery charged by a trickle charger makes high current peaks easy to accommodate. Almot any condition battery will do - one which is too dead for eg motorcyle use probably works well enough here. Floating 12V lead acid batteries at 13.7 V allows them to be permanenetly connected to the "charger". A power pack can be used without a battery if enough current is provided.

Battery powered drills typically have a two stage epicyclic gearbox giving typically hundreds of RPM output speed. If desired you can use the supplied switching which has a DPDT mechanical reversing switch. If you remove the mechanical reversing switch you can feed voltage directly to the motor. Changing polarity changes direction.

Dismantling the gearbox can be educational but may be a one way journey. Beware a flood of ball bearings.
> 2 votes

---
Tags: motor
---


title: Set start time for arduino uno clock

text:
# Question
Title: Set start time for arduino uno clock
I'm programming an arduino uno with attached screen to be a clock and have the code below. It counts up from zero the milliseconds, seconds, minutes and hours and when it hits 24 hours it starts again from zero. Does anyone know how I can set the start time that it automatically starts at when it is reset? It will be a one off thing and I don't want it to interfere with the clock resetting to 0 hours after it hits 24. Thanks

```
#include <Wire.h>
#include <LiquidCrystal.h>

#define MILLIS_OVERFLOW 34359738

/**
 * Clock Variables
 */
unsigned long currentMillis, previousMillis, elapsedMillis;
int seconds, minutes, hours;

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup()
{
    lcd.begin( 16, 2 );

}

void loop()
{
    setClock();
    /**
     * After set clock now you have 3 int variables with the current time
     */
     //seconds
     //minutes
     //hours
     lcd.setCursor ( 0, 1);
     lcd.print(hours);
     lcd.print(":");
     lcd.print(minutes);
     lcd.print(":");
     lcd.print(seconds);
     lcd.print(":");
     lcd.print(elapsedMillis);

}

void setClock()
{
    currentMillis = millis();
    /**
     * The only moment when currentMillis will be smaller than previousMillis
 * will be when millis() oveflows
 */
if (currentMillis < previousMillis){
    elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
} else {
    elapsedMillis += currentMillis - previousMillis;
}

/**
 * If we use equals 1000 its possible that because of the mentioned loop limitation
 * you check the difference when its value is (999) and on the next loop its value is (1001)
 */
if (elapsedMillis > 999){
    seconds++;
    elapsedMillis = elapsedMillis - 1000;
}

if (seconds == 60){
    minutes++;
    seconds = 0;
}
if (minutes == 60){
    hours++;
    minutes = 0;
}
if (hours == 24){
    hours = 0;
}

previousMillis = currentMillis;
}

```

# Answer
Assume you want the clock to start at 08:42:21, change

```
int seconds, minutes, hours;

```

to

```
int seconds = 21, minutes = 42, hours = 8;

```

Note that you should always also initialize (as in the second case above), and not only declare (as in the first case) all variables before you first read their values. Otherwise, for local variables you cannot be sure what their initial value is. (Global variables are implicitly initialized to zero if not explicitly initialized.)
> 3 votes

---
Tags: arduino-uno, time
---


# Question
Title: Control external device using Java Web Servlet -> Pi -> Arduino -> Device
I'm new to the world of Arduino & PI, so far it's been a fantastic experience but I'm now looking to build something a bit more practical.

My plan is for the PI to host a JSP Servlet website. I'd like to go to a certain page of this site: 'powerCycleDevice' for example where it would pass a parameter in '?=on' or something similar. This would then be picked up by the Arduino which in turn would then power said device.

It's also be nice to just use it as a monitoring station. If I have several Arduinos hooked up (and I plan to - think Wallace & Gromit :)) then it'd be nice to view the statistics of each of the sensors.

My problem is not knowing if a: it's possible (I'm certain it is) and b: where to start.

If anyone can lend any advice, hints or tips on where to get started it would be fantastic. A noob guide or tutorial would be great as I'd then use the info and expand upon it.

Thanks in advance.

# Answer
> 1 votes
You can use Ardulink. It's a java open source project of mine. It can control an Arduino boad. So you have just to write a servlet that call my library. That's it.

See this post to understand how install ardulink in a PI: http://www.ardulink.org/how-to-install-arduino-pc-link-on-raspberry-pi/

You can read a sample code that sends some messages to Arduino you can read this post: http://www.ardulink.org/how-to-blink-a-led/

The most important statement is **Link link = Link.getDefaultInstance();**

**Link** is the Ardulink class you need to send (and receive) messages.

---
Tags: arduino-uno, serial, web-server, home-automation
---


# Question
Title: What are possible issues when moving Arduino to another microcontroller?
When Arduino was conceived AVR was very much the best 8-bit controller available. But we're 10 years on now, and still using the AVR, despite lots of better microcontrollers available, notably ARMs. In particular M0 and M0+ cores are a lot cheaper, yet are a lot faster and have many more features than AVR.
For instance the NXP LPC824 has more serial buses, more A/D channels and higher A/D resolution, is almost twice as fast as the AVR, yet costs 30% less. (Granted, it doesn't have EEPROM, but you can have that for 20 cents.)

So I was wondering if there are particular issues which prevent the use of more modern microcontrollers on Arduino.
One difference may be Vcc, which is 5V for AVR and 3.3V for ARM. But given that more peripherals work at 3.3V this seems more to be an AVR issue than an ARM issue.

PS: I'm aware of Arduino Due, but that one costs twice as much as a Uno. I'm talking about controllers which price-wise can compete with AVR.

# Answer
There is NO *best* 8 bit or 16 or whatever bit uC (micro controller).
There always have been "better" ones and there always will be and better changes with your need as well as with time.

If you want or need a faster or more capable processor, use one.
For many tasks the existing AVR processors are very fine indeed.

A number of people are making Arduino-like uC's using ARM right now.
You can buy them 'off the shelf'.

Running "Arduino" code is where issues arise:
If you are willing to run 100% standard Arduino code applications will usually run well on the new uC.
If applications use precompiled libraries and you wish to use eg an ARM it will not run.
If you recompile the libraries and they are written in a compatible language flavor (C or whatever) then they MAY work for your new processor.
If they use assembler then they will not work in essentially all cases.

But, existing 'Arduino' hardware can use the high level language of your choice. A new processor with a compatible compiler will compile eg C code that runs on Arduino hardware BUT port locations, register control methods etc need to be correctly allowed for.

It gets harder and harder as you try to fit the new giants into the old not-so-giant framework. Somewhere along the way it is easier to give up the attempt and use the Arduino for what it is good for and the 'new' processor where necessary.

**Whatever the Arduino did well when new it still does well.**

In most cases the speed, peripherals and memory capabilities are entirely fine for tasks that people who wish to use it wish to do.
The main issue is that an Arduino is not something it is not, just as a small family car is not a bus or a sportscar. Use the car where it is useful and use a bus or sportscar when necessary.
> 2 votes

---
Tags: arduino-uno
---


title: Arduino: Put Data in Other File

text:
# Question
Title: Arduino: Put Data in Other File
The below code starts off with lots of data in the beginning, distracting the reader from the actual code. What is the best practice to clean this up:

```
#include <Wire.h>
// For LED Backpack
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
// For LCD Shield
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

// For pixel Units, such as hero
#include <Unit.h>

Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

Unit *hero;
boolean doesNeedRedraw = true;
boolean textNeedsRedraw = true;
int8_t lastButtonPress = 0;
int8_t frame = 0;

void setup() {
  /* Important Setup Routine */
}

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 },
  walls_bmp[] =
  { B10100000,
    B10110000,
    B10010000,
    B11011100,
    B01000100,
    B01110100,
    B00010100,
    B00011100 };

void loop() {
  /* Important Main Loop Routine */
}

```

# Answer
One way to clean that up is to create a "Globals.inc" file and cut and paste all of your globals into there. After that's done, simply include the globals file from your main .ino file with `#include "Globals.inc"`

(Main.ino)

```
#include <Wire.h>
// For LED Backpack
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"
// For LCD Shield
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

// For pixel Units, such as hero
#include <Unit.h>

#include "Globals.inc"

void setup() {
  /* Important Setup Routine */
}

void loop() {
  /* Important Main Loop Routine */
}

```

(Globals.inc)

```
Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

Unit *hero;
boolean doesNeedRedraw = true;
boolean textNeedsRedraw = true;
int8_t lastButtonPress = 0;
// 0-255
uint8_t frame = 0;

static const uint8_t PROGMEM
  smile_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10100101,
    B10011001,
    B01000010,
    B00111100 },
  neutral_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10111101,
    B10000001,
    B01000010,
    B00111100 },
  frown_bmp[] =
  { B00111100,
    B01000010,
    B10100101,
    B10000001,
    B10011001,
    B10100101,
    B01000010,
    B00111100 },
  walls_bmp[] =
  { B10100000,
    B10110000,
    B10010000,
    B11011100,
    B01000100,
    B01110100,
    B00010100,
    B00011100 };

```
> 3 votes

# Answer
There is actually not a lot wrong with the way the code is. You are writing / using embedded code. It is not expected to be some planned out UML model, and does not need to look like it is.

If you just want less lines, start by converting your binary data to hex. Otherwise the answer of a global.h is valid (and I would still convert binary to hex). You could easily shrink 24 lines down to 3.

If you could use a real IDE navigation would be unimportant, but since Arduino chose not to use a standard build process it takes extra effort (but still worth it). You could also switch to native AVR (and easily use a real IDE), which is what I plan to do as soon as the proof of concept is finished.
> 2 votes

---
Tags: programming
---


title: cannot convert error with pointers

text:
# Question
Title: cannot convert error with pointers
I write a code to store patterns for LED blinking, but I got this error:

```
led_basics:39: error: cannot convert 'char (*)[17][2]' to 'char*' in initialization

led_basics:39: error: cannot convert 'char (*)[16][2]' to 'char*' in initialization

led_basics:39: error: cannot convert 'char (*)[13][2]' to 'char*' in initialization

```

and so on for all pattern. How can I fix it? Here is the code:

```
char nulla[17][2]={{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

char egy[16][2]={{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

char ketto[13][2]={{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}};

char harom[17][2]={{0,34},{7,35},{8,33},{10,41},{14,9},{17,73},{21,72},{24,74},{27,78},{30,70},{32,68},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

char negy[17][2]={{0,7},{7,6},{8,4},{9,0},{10,8},{21,9},{24,11},{27,15},{28,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

char ot[14][2]={{0,39},{8,37},{9,33},{10,41},{14,9},{17,73},{28,72},{30,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

char hat[17][2]={{0,62},{7,63},{8,61},{9,57},{12,41},{14,9},{17,73},{21,72},{24,74},{30,66},{32,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

char het[15][2]={{0,7},{8,5},{9,1},{24,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

char nyolc[15][2] = {{0,127},{8,125},{9,121},{12,105},{14,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

char kilenc[13][2] = {{0,79},{8,77},{9,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

char kettospont[6][2] = {{0,0},{9,4},{12,20},{18,16},{24,0},{68,0}};

char *karakterek[11]={&nulla,&egy,&ketto,&harom,&negy,&ot,&hat,&het,&nyolc,&kilenc,&kettospont};

```

# Answer
karakterek is an array of char pointers. It cannot be used to store pointers to char arrays.

I'm not sure it would be possible to store pointers to your 2 dimensional arrays since they are all of different dimensions. Someone else might know a way to do that.

Here's how I would do it (using as similar as possible a structure):

```
char nulla[]={0,127,8,125,9,121,10,113,12,97,14,65,24,67,27,71,28,70,30,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

char egy[]={0,0,9,4,16,6,18,2,21,3,27,7,28,6,30,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

char ketto[]={0,98,7,99,8,97,12,113,14,81,20,89,21,88,24,74,27,78,30,70,32,68,36,64,68,0};

char harom[]={0,34,7,35,8,33,10,41,14,9,17,73,21,72,24,74,27,78,30,70,32,68,36,80,42,112,48,96,51,32,56,0,68,0};

char negy[]={0,7,7,6,8,4,9,0,10,8,21,9,24,11,27,15,28,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

char ot[]={0,39,8,37,9,33,10,41,14,9,17,73,28,72,30,64,36,80,42,112,48,96,51,32,56,0,68,0};

char hat[]={0,62,7,63,8,61,9,57,12,41,14,9,17,73,21,72,24,74,30,66,32,64,36,80,42,112,48,96,51,32,56,0,68,0};

char het[]={0,7,8,5,9,1,24,3,27,7,28,6,30,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

char nyolc[] = {0,127,8,125,9,121,12,105,14,73,24,75,27,79,28,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

char kilenc[] = {0,79,8,77,9,73,24,75,27,79,28,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

char kettospont[] = {0,0,9,4,12,20,18,16,24,0,68,0};

char* karakterek[]={nulla,egy,ketto,harom,negy,ot,hat,het,nyolc,kilenc,kettospont};

```

For starters, I'd make the char arrays single dimension. Since the 2nd dimension is always a size of 2, you could index through your values reading index 0 into x0, index 1 to y0, index 2 to x1 and index 3 to y1 (I'm assuming these are x y co-ordinate pairs).

Secondly, I'd lose the hard-coded sizes for the arrays. If you want to add or remove entries, you don't have to keep updating the sizes.

Finally, I'd lose the '&' from your array of array pointers. Referring to an array simply by its name gives you a pointer to it. I think '&' gives you a pointer to the pointer, but I could be wrong.
> 1 votes

# Answer
As the second dimension is always 2, you can do this:

```
typedef char Tuple[2];

Tuple nulla[17] = {{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};
Tuple egy[16]   = {{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};
Tuple ketto[13] = {{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}};
// etc.

Tuple* karakterek[3] = {nulla, egy, ketto}; // etc.

```

(The `typedef` makes it easier.)
> 1 votes

---
Tags: arduino-uno, c, pointer
---


# Question
Title: Programming bluetooth module JY-MCU v1.06
I have a popular bluetooth module JY-MCU version 1.06 (picture below). Before i insert it to my arduino project I want to configure the name, bound speed and the pass code using usb-to-serial link. But I am facing a problem where the device does not respond to commands. Please let me explain.

I send the module to programming mode by applying +5V on 'key'

Then I send commands using CoolTerm program:

```
AT+NAMEmyArduinoProject
> OKyour set name

```

Ok. setting the name works as expected. But that is the only thing that worked for me. Other commands give no response:

```
AT

AT+BAUD2

AT+VERSION

AT+VERSION?

```

Maybe you had this happen to you? I am I sending wrong commands or doing something wrong? Please help me to figure out how to control this module.

# Answer
OK, I figured it out. It looks like CoolTerm was sending wrong line endings. Thus the only command that worked was name change as it interpreted the extra symbols as part of the name specification. Now I am using in built Arduino serial communication and it works like a charm!
> 1 votes

# Answer
The protocol is peculiar.

You are to send the command unterminated within one second.

For example the AT command comprises the two characters AT and nothing more, no line ending at all. And the command must be completed within one second.

So,
AT\[cr\]\[lf\] will just be ignored.
> 0 votes

---
Tags: serial, bluetooth
---


title: Different Arduino packages on Raspbian

text:
# Question
Title: Different Arduino packages on Raspbian
I'm working on using my Raspberry Pi (Raspbian) to upload sketches. However, I'm not sure which package is appropriate for command line usage (like described here on Github).

It seems like `sudo apt-get install arduino` would install the whole IDE, not just the command line. It seems like `arduino-core` would be more fitted for this purpose. However, the repository has a note online to use a package called `arduino-mk` for a CLI, which is what I want. However, this concerns me in the repository's page:

> This package will install a **Makefile** to allow for CLI programming of the Arduino platform.

(Emphasis mine)

What exactly does this mean? What are the differences between the three packages available?

# Answer
> 1 votes
I have not actually interacted with the debian packages, but If I'm reading this right, this how they are organized:

**arduino**: The whole java IDE and avr code libraries

**arduino-core**: the libraries and code that comes with arduino to be compiled for avr

**arduino-mk**: a makefile for compiling arduino code without the IDE (but no code)

The normal arduino package has a command line interface, but the code for this is (currently) very closely tied to the java GUI code and cannot be used without the whole thing being installed. To make using the raw atmel avr tools easier, the makefile is available; However, the makefile does not include all of the cpp libraries that come packaged with the arduino installation that a normal arduino sketch would reference (Arduino.h, Servo, SPI, etc). The arduino-core package exists to bring in all this supporting code.

I imagine it is done with these three packages so if you already have arduino installed, the makefile will not bring a second copy of all the libraries with it.

The makefile is a configuration for the gnu make software. There is some information on the specific usage of the arduino makefile on its github page here

# Answer
> 1 votes
Previous versions of arduino-mk had a dependency on arduino, which was everything, but with the split out of arduino-core, which both of the other packages now depend, arduino only includes the ide, everything else is in core so that you do not need the ide to develop, compile and load standard projects to your Arduino. I have only used the ide for less than 15 minutes And do all my work using vi and the command line. the makefile allows you to compile ino files with a make just by linking it into your project directory, it also has options for uploading using make.

---
Tags: arduino-ide
---


# Question
Title: Sending data from txt file over serial connection
I'm trying to send data saved on a txt file to arduino over serial connection. I wrote this simple sketch

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

void loop(){
  while (Serial.available() > 0) {
    Serial.write(Serial.read());
  }
}

```

When I try to send serial data from bash by typing `cat input.txt >> /dev/cu.wchusbserial1a1340` while the Arduino's serial connection window is open. It gives an error message "resource busy: /dev/cu.wchusbserial1a1340". Then I tried `cat input.txt >> /dev/tty.wchusbserial1a1340`. Now it hangs. Bash is busy, and it is not possible close Arduino IDE or serial connection window. What is wrong here?

# Answer
I don't know the details of why the hang is occurring. However, the problem stems from serial ports being available to one process at a time. When the Arduino-environment's serial-port-monitor opens a serial port, that port becomes unavailable to bash. (To close the hung Arduino IDE process and the SPM, say `ps aux |grep arduino` and `kill` *n*, where *n* is the PID shown by the `ps` and `grep`.)

Here is a python program you can run, that sends and receives data:

```
#!/usr/bin/env python
# Send data to an Arduino and report responses.
from time import time, sleep, asctime, localtime
from serial import Serial
print 'Opening serial port'
ser = Serial('/dev/ttyACM0', 9600, timeout=3)
sleep(1)                      # Let board initialize
while 1:
    txt = 'It is about ' + asctime(localtime()) + ' now'
    print 'Sending  "{}"'.format(txt)
    ser.write(txt)
    s = ser.readline()          # Get result from arduino
    print 'Readback "{}" at {}'.format(s, asctime(localtime()))
    sleep(1)

```

Here is some sample output from it, with your sketch runing in a Mega2650. (I'm not sure why the readback is taking so long as it apparently is.)

```
Opening serial port
Sending  "It is about Fri May  8 16:48:41 2015 now"
Readback "It is about Fri May  8 16:48:41 2015 now" at Fri May  8 16:48:44 2015
Sending  "It is about Fri May  8 16:48:45 2015 now"
Readback "It is about Fri May  8 16:48:45 2015 now" at Fri May  8 16:48:48 2015
Sending  "It is about Fri May  8 16:48:49 2015 now"
Readback "It is about Fri May  8 16:48:49 2015 now" at Fri May  8 16:48:52 2015
Sending  "It is about Fri May  8 16:48:53 2015 now"
Readback "It is about Fri May  8 16:48:53 2015 now" at Fri May  8 16:48:56 2015

```
> 3 votes

# Answer
As noted by jwpat7 the port can be accessed by one application at a time, so when the serial monitor is open no other application can access it.

The hang might happen because when first connecting to an arduino port the arduino gets reset and waits for a second or so for programming data (that's how a new sketch is updated). I don't know for sure, but this might mess up with `cat` and make it to hang up.

Best option might be to make a script like jwpat7's that would wait a second after opening the port and then send the file contents in.
> 1 votes

---
Tags: serial, communication, terminal
---


# Question
Title: How to transfer data from Arduino to some software in computer?
My arduino gets some data from sensors and save it into EEPROM. Now, I want that when I connect my arduino to PC there should be a software(like sketch) which can fetch data from arduino's EEPROM processes it and saves it into a file in PC. I am willing to create such a software but how will I then communicate with arduino like Sketch does?

# Answer
Just use serial communication. Make sure you know which port your Arduino is recognized in your system, make a sketch to send data through Arduino's serial communication and try making a simple Node.js application using **serialport** package which will receive your data. There is a code sample where you can start from. Just set the port and start receiving data. And that's good, using Node.js you are really close to web tools, so it's easy to migrate your application to web.

It's really simple and you can get it done in a few minutes, even if you have not been introduced to node.

These kind of embedded applications have been accepted by Node.js and there are plenty of robotics projects which use node on the web.

```
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM0", {
  baudrate: 57600
});

```

Usually Arduino is recognized as ttyACM0 on Unix-based systems. With this line of code you establish a serial communication with your board.

Going further you can register events like data, which is fired when data comes from Arduino:

```
// it opens the connection and register an event 'data'
serialPort.on("open", function () {
  console.log('Communication is on!');

  // when your app receives data, this event is fired
  // so you can capture the data and do what you need
  serialPort.on('data', function(data) {
    console.log('data received: ' + data);
  });
});

```

In this example your app just receives data and log it to your terminal.
> 5 votes

# Answer
The options that I see:

* Via serial - this can either be done wirelessly via Bluetooth serial adapter, or via the standard USB connector. Your program will have to have a way of sending the data - some way to indicate that you want to download the data.
* Transfer via ICSP - these are the 2x3 grid of pins on your Arduino. You can download the data, without having to write any code. You will need something like a USBASP - they're cheap. You can download the entire EEPROM, and dissect it once you have it on your computer.

I have a vague recollection that EEPROM may be overwritten when you upload a sketch, so if you want to use serial (the first option), make sure your sketch already knows how to transfer the data before you collect it. This is not a limitation for ICSP.
> 0 votes

# Answer
You should specify what programming language/compiler/IDE you want to use for the part on your pc.

I would suggest using "Processing" - https://processing.org/ it's a similiar IDE as the arduino IDE and the coding is also a bit similiar. You can use a serial library to receive data from USB/COM port.

Processing has the ability to create a window with graphics. You could read the position of something with your arduino, then send it to 'processing' and it will draw the object on the screen (after a bit of coding).

Guide: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing
> 0 votes

---
Tags: serial
---


# Question
Title: Sensing concentration of methane with MQ-4 methane sensor?
I'm on a project to sense any amounts of methane in the home. I have bought the popular MQ-4 methane sensor from SparkFun: https://www.sparkfun.com/products/9404

I've looked online for any sample code, but I am confused as to whether the input from the sensor is already given in parts per million, or it is just a voltage. To be specific, here is the sample code the data sheet for the sensor gives:

```
int sensorValue;

void setup()
{
  Serial.begin(9600);      // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println(sensorValue, DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

```

I have also used a breakout board for these sensors: https://www.pololu.com/product/1479 The sensor is soldered on it, along with a 20K ohm load resistor, like how the spec. sheet specifies. However, I am confused on the readings I am getting. It's always something that ranges between 259 and 261. Is this ppm of methane in my home? If it is, shouldn't the normal level be 0? I currently have no methane based heating. Or is the 259 - 261 voltage?

Thanks for any help.

# Answer
> 2 votes
Actually, you are getting raw data from the sensor. A little bit of math should be done in order to calibrate it and based on the chart in datasheet, measure the real value in PPM.

The calibration basically helps you find R0, which is an internal resistance (along with RS form a voltage divider) that could be derived by doing calibration in a clean environment. After that, you use R0 to calculate a ratio and then look at the datasheet's chart to measure whatever gas you want since there is a curve describing it.

Please refer to this tutorial for more information. I have developed a similar application using MQ-4 before.

It is related to MQ-2, you may have noticed that all theses sensors have similar features and principle applications.

# Answer
> 2 votes
The values you're reading relate to the voltage measured by the AD converter, that is, the voltage over the load resistor. Arduino's AD converters have 10 bit resolution and measure against a 5V reference, so you can use the following line to convert it to millivolts:

`VRL = map(sensorValue, 0, 1023, 0, 5000);`

Once you have the voltage, you can compute the resistance of the sensor using the formula

Rs=(Vc/VRL-1)×RL

with Vc the circuit voltage (5V), VRL the voltage over the load resistor, and RL the resistance of the load resistor in Ohms.

The tricky part is to convert this to a concentration in ppm CH4. The curve in the datasheet gives you a starting point, but the values it gives are not absolute, but relative to the reference of 1000 ppm. The value of that reference depends on various factors, like temperature, humidity, other gases in the environment and how long the sensor has been running (the longer, the more reliable are the results).

If you really need exact ppm values, you'll need to calibrate your setup in an environment where you can exactly control the CH4 concentration. You'll also have to measure temperature and humidity along with the sensor readings.

Otherwise you'll get only a qualitative estimate of CH4 concentration, which is actually sufficient for many use cases.

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


# Question
Title: Running Pro Mini Continuous on 12v w/o Damaging Regulator
A Pro Mini needs to be placed in a 100mmx50mmx25mm, no holes but not air tight ABS plastic enclosure, with a 12v power supply connected to the raw input. It will be consuming max 40mA, ambient temperature 30-32C, and needs to be run 24/7. Upon prototyping in open air, I tried to touch the regulator MIC5205, after 30 seconds upon powering on with my bare fingers and it was too hot to touch. The rest of the components were cool to touch. I would use a buck converter to step down to 5v, however there isn't space for it in the current setup.

I used to run a Mega 24/7 on 12v, consuming much more current about 700mA, the onboard regulator malfunctioned after 1 year of use, which I believe was due to the excessive heat, as the PCB around the regulator turned a little brownish.

Despite being hot to touch, I understand that electronics run in heat all the time like computers, routers, etc for 24/7. Therefore, I would like to know if 12vx0.04A=0.48w will be too much heat/feasible to run in the above mentioned setup, without damaging the regulator in the long run?

# Answer
> 1 votes
**Summary:**

**Simple, effective, low cost solution - choose any 3:**
A series resistor in the regulator input, of properly designed resistance and wattage will greatly reduce regulator temperature and increase overall reliability. Reason and design details given below.

**Detail:**

Assuming a 5V processor dissiaption in the regulator is
(Vsupply - Vregulator\_out) x Current
= (12-5)x 0.040 = 280 mW - usefully less than the 480 mW if you are dissipating all the power in the regulator.
For a 3V3 processor dissipation is (12-3.3)\* 0.040 ~= 350 mW

"Too hot to touch" is a minimum of 55C and probably hotter - say 70C for now.
At 30C ambient delta T = (70-30) = 40 C.
Thermal resistanc = dT/Watts =40/0.280 = 140 C/W or 114 C/W at 3V3.

Both of those thermal resistances are very high. You do not describe what heatsinking is on the regulator but that suggests PCB copper only and not much of it. Even adding a very rudimentary heat sink should help immensely. If there is no obvious way to add a formal heat sink then adding a 'flag' of copper or brass by soldering should be doable.

Using Mark William's 220C/Watt figure (see datasheet for conditions).
Say 300 mW (see above).
Delta t = 220 C/W x 0.3 W = 66 C rise.
Ambient is 30-32 so allow 35 for very minor safety factor.
66 C rise + 35 C ~= 101C - water boils.
And temperature inbox will rise mildly from energy dissipated so hotter again.
BUIT a series resistor inside the box or external will make an immense difference.

**An easy and effective solution:**

The regulator needs some "headroom" - some voltage above the Vout value to allow some dropacross the internal switch. Check the data sheet, but a modern LDO probably allows as little as 1V headroom. So, for 5V out you need 6V in. The extra 6v from 12V to 6V is not "needed" by the regulator. So, it can be dissipated in a low cost high reliability resistor.
Determine

* Vsupply\_minimum - the absolute lowest value supply will assume.
* Vreg\_in\_minimum I'll use 6V to start.
* I\_load\_maximum - you said 40 ma. This must be abs\_max or if of very short duration must be able to be supported by capacitors.

Then

Rmax = V/I = (V\_supply\_min-Vregin\_nax) / Imax
= (12 - 6 )/.040 = 150 Ohm.
This is the absolute maximum resistor that meets the specification. A slightly smaller value will be safer. Say 120 R in this case.
Then
Pmax in R = I^2R = .04^2 x 120 = 192 mW.
A 500 mW resistor would be "safe enough" and a 1 watt one very safe.
Pregulator max = (6-5) x 0.040 = 40 mW, 14% of the 280 mW initially. A W resistor with adequate cooling will be very safe. Safest is probably a purpose built air cooled wire wound.

Note that the dissipated energy will raise internal ambient. A resistor is still an effective solution.

Place a suitable decoupling capacitor at the regulator input. Even if not normally used here it is needed due to the series input resistor raising the supply resistance.

.\_______________________________________

**Temperature rise inside box due to heat dissipation.**

**Summary:** Using pessimistic assumptions for box thickness, available area and power dissipation an internal temperature rise of under 15 degrees C can be expected. As the regulator is now dissipating under 15% of the original dissipation due to the series resistor it will have a far longer operating lifetime.

Notes:

Temperature rise (assuming no air transfer occurs) is limited by heat transfer through the plastic. This is controlled by the thermal conductivity of th e plastic, its thickness and its area. Obviously:
\- Thicker plastic leads to higher temperature rise.

* More surface area leads to lower temperature rise.
* Higher thermal conductivity of the plastic leads to lower temperature rise

So given Thermal conductivity = Ktc

* **Delta T = Watts x thickness / (Ktc x area)**

So Ktc = Watts x thickness /(Delta\_Tx area)
So units of Ktc must be Watts/metre/degree\_C
Which is indeed how Ktc is usually expressed.

This table of **Thermal properties of plastic materials** lists Ktc for ABS as 0.17 W/m/K
This means that 170 mW will cause a 1 degree K (or C) rise when plastic ratio of thickness to area is 1.

Assume thickness of box = 5mm = much higher than is likely.
Box area for a box L x W x D = 2 x (LW + WD + DL)
Here = L D W = 100mm x 50mm 25 mm or 0.1 x 0.05 x 0.025m Area = 0.0175 m^2.
Use a smaller more pessimistic area of 0.01 m^2
Use a pessimistic heat dissipation of 0.5 Watts

Using the formula - **Delta T = Watts x thickness / (Ktc x area)** from above

**Temperature rise = 0.5 x 0.05 / (0.17 x 0.01) ~= 15 degrees C (or K)**
This is based on a thicker than likely box, smaller than actual area, and higher than expected energy dissipation. A 15C rise is bearable and actual is lower, and as the regulator now dissipates under 20% of original it will survive very well.

---
Tags: arduino-pro-mini
---


title: Overview of compiled code size

text:
# Question
Title: Overview of compiled code size
When I compile my code, the Arduino IDE returns the binary sketch size in byte.

Is there a good way to find out (approximately) what function or what part of my code takes up how much memory in flash, so that I get a feeling what feature takes most of precious flash memory or where I may be wasting flash and should start optimizing?

# Answer
One approach is to look at the assembly listing of the program.

1. After compiling the program (via the Verify or Download button) locate the directory where the .cpp, .hex, and .elf files for the program have been stored. (If you have trouble finding them, briefly turn on verbose compile options in the arduino IDE and look at the directory names in the output.)
2. In that directory, run `avr-objdump -S` *fn.cpp.elf* `> listing.txt` where *fn.cpp.elf* is the name of your sketch with `.ino` taken off and `.cpp.elf` added on at the end. For example, with sketch `serialecho.ino`:

avr-objdump -S serialecho.cpp.elf \> listing.txt
3. View the `listing.txt` file, and subtract each function's starting address from its ending address, using hex arithmetic. For example, with `setup` code

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

in the listing we will see

```
00000144 <setup>:
...(6 lines snipped)...
 144:   26 e0           ldi     r18, 0x06       ; 6
 146:   40 e8           ldi     r20, 0x80       ; 128
 148:   55 e2           ldi     r21, 0x25       ; 37
 14a:   60 e0           ldi     r22, 0x00       ; 0
 14c:   70 e0           ldi     r23, 0x00       ; 0
 14e:   80 e1           ldi     r24, 0x10       ; 16
 150:   92 e0           ldi     r25, 0x02       ; 2
 152:   db c1           rjmp    .+950           ; 0x50a <_ZN14HardwareSerial5beginEmh>

00000154 <loop>:

```

The calculation 0x154–0x144 = 0x10 shows this portion of `setup` is 16 bytes long.

These examples were generated on a linux system. I think the approach is the same on a MSWindows system except you may need to say `avr-objdump.exe` instead of `avr-objdump`, and may need to specify its path. See, eg, the Assemler results, where? thread at forum.arduino.cc.
> 6 votes

---
Tags: debugging, memory-usage, code-optimization
---


# Question
Title: Improve sampling speed while using a multiplexer
I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).

However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks. In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()

Is there any tricks I could use to improve my sampling rate faster ? Thanks...

Here is my multiplexer class :

```
class MUX {
public:
//mux control pins:
int s0 = 22;
int s1 = 24;
int s2 = 26;
int s3 = 28;

//SIG pin (not necessary WHEN sig is connect to 5V)
//int SIG_pin = 0;

//array to store channel :: muxChannel[channel numbers ][4 digit channel representation]
int muxChannel[16][4] = {
  {0, 0, 0, 0}, //channel 0
  {1, 0, 0, 0}, //channel 1
  {0, 1, 0, 0}, //channel 2
  {1, 1, 0, 0}, //channel 3
  {0, 0, 1, 0}, //channel 4
  {1, 0, 1, 0}, //channel 5
  {0, 1, 1, 0}, //channel 6
  {1, 1, 1, 0}, //channel 7
  {0, 0, 0, 1}, //channel 8
  {1, 0, 0, 1}, //channel 9
  {0, 1, 0, 1}, //channel 10
  {1, 1, 0, 1}, //channel 11
  {0, 0, 1, 1}, //channel 12
  {1, 0, 1, 1}, //channel 13
  {0, 1, 1, 1}, //channel 14
  {1, 1, 1, 1} //channel 15
};

void setupMux() {
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  Serial.println(F("Multiplexer initialized"));
}

void selectChannel(int channel) {
  int controlPin[] = {s0, s1, s2, s3};
  for (int i = 0; i < 4; i++) {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }
}

```

# Answer
> 2 votes
It's hard to offer much more than speculation without knowing more about the sensors and your current code, but here is one possibility:

If the bulk of your loop time is the sum of the conversion times, is it possible to cycle through the sensors twice, once to start each conversion (so they will convert nearly simultaneously), wait one conversion-time (or for the first sensor to complete), then cycle through them again to read back each converted value?

```
for each sensor,
  setup mux;
  send start conversion command;
end

for each sensor,
  setup mux;
  while conversion not done,
    ;  // wait
  read and store value;
end

```

For 16 sensors and assuming the conversion time the majority of the time spent, that could speed your sample rate to ~100Hz. Expect maybe half of that, since mux-setup and communication times are probably not negligible.

# Answer
> 1 votes
The technique suggested by @JRobert (starting all the conversions in one loop, then running another loop to wait for completions and read results) looks reasonable.

Here are a couple of ways to shorten the code shown in the question:

First, instead of four `int` declarations to set the value of `s0 ... s3`, use an `enum`. An `enum` is used to declare integer constants.

```
enum { s0 = 22, s1 = 24, s2 = 26, s3 = 28};

```

Second, don't bother with the lengthy, tedious, and unnecessary `muxChannel` array. Delete the declaration of `muxChannel` and replace `selectChannel` with the following:

```
void selectChannel(int channel) {
  int controlPin[] = {s0, s1, s2, s3};
  for (int i = 0; i < 4; i++) {
    digitalWrite(controlPin[i], channel & 1);
    channel /= 2;
  }
}

```

The expression `channel & 1` picks off the least-significant-bit of `channel`. The statement `channel /= 2;` divides `channel` by 2, which moves the next bit of `channel` into place for output. You could instead say `channel >>= 1;` or `channel = channel/2;`, etc. if you prefer.

You might also look closely at your sensor boards to see if there is any way to add jumpers to get another bit or two of I2C device addressing, allowing you to avoid multiplexing.

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


# Question
Title: Why doesn't my code work in a function, yet works inline?
I'm trying to write a faster `shiftOut` function, which does not use the slow `digitalWrite`. In my code I have the original `shiftOut`, the new shiftOutFast, and the same as shiftOutFast, but inline. The three blocks are separated by delays to tell them apart on my scope. Here's the code:

```
#define CLR(x,y) (x &= (~(1 << y)) )
#define SET(x,y) (x |= (1 << y) )

void shiftOutFast(uint8_t dataPort, uint8_t dataBit, uint8_t clkPort,
                  uint8_t clkBit, uint8_t bitOrder, uint8_t val) {
  for (uint8_t i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST) {
      if (val & 0x01) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val >>= 1;
    } else {
      if (val & 0x80) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val <<= 1;
    }

    CLR(clkPort, clkBit);
    SET(clkPort, clkBit);
  }
}

#define dataPin 4
#define clockPin 5
#define dataPort PORTD
#define dataBit PORTD4
#define clockPort PORTD
#define clockBit PORTD5

void setup() {
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
}

void loop() {
  shiftOut(dataPin, clockPin, LSBFIRST, 0x55);
  delay(1);

  shiftOutFast(dataPort, dataBit, clockPort, clockBit, LSBFIRST, 0x5C);
  delay(1);

  bool bitOrder = LSBFIRST;
  uint8_t val = 0x5C;

  for (uint8_t i = 0; i < 8; i++)  {
    if (bitOrder == LSBFIRST) {
      if (val & 0x01) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val >>= 1;
    } else {
      if (val & 0x80) {
        SET(dataPort, dataBit);
      } else {
        CLR(dataPort, dataBit);
      }
      val <<= 1;
    }

    CLR(clockPort, clockBit);
    SET(clockPort, clockBit);
  }
  delay(1);
}

```

The problem is that calling `shiftOutFast` doesn't do zilch. Absolutely nothing. It doesn't seem to be the logic, because when I do the same inline it works. Any ideas?

# Answer
> 11 votes
The problem is that you are passing the value of the ports to the function, not the address of the ports.

You need to either pass "by reference" or as a pointer, so that modifying the port variable modifies the *actual* port variable not the copy of the value that you pass.

The simplest way is to modify your function to be:

```
void shiftOutFast(volatile uint8_t &dataPort, uint8_t dataBit,
                  volatile uint8_t &clkPort, uint8_t clkBit,
                  uint8_t bitOrder, uint8_t val) {
....
}

```

That way, instead of passing whatever is in the port at the time to the function (pass by value) it instead creates a new variable which is located at the same address as the variable that you are passing (pass by reference) so modifications of one variable modifies the other.

Note that only the "port" variables need to be passed by reference, all the others remain as pass by value. Also they should be, as Edgar says, flagged as *volatile*.

# Answer
> 5 votes
You should declare `volatile` the port parameters of your function. Otherwise, to the compiler, their write accesses seem useless, and they get optimized out.

---
Tags: programming, c
---


title: Arduino IR not returning data

text:
# Question
Title: Arduino IR not returning data
**THIS QUESTION ISN'T IN USE ANYMORE**

> Solved by using an other remote that is supported by the libary

**====NEW CODE====**

```
    #include <IRremote.h>

    int RECV_PIN = 11;
    int relay1 = 2;
    int relay2 = 3;
    int relay3 = 4;

    int on = 1;
    int on1 = 1;
    int on2 = 1;

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      digitalWrite(relay3, HIGH);
      pinMode(relay3, OUTPUT);
      digitalWrite(relay2, HIGH);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, HIGH);
      pinMode(relay1, OUTPUT);
      pinMode(13, OUTPUT);
      irrecv.blink13(true);
      irrecv.enableIRIn();
    }

    unsigned long last = millis();

    void loop() {
      if (irrecv.decode(&results)){
        if (results.value == 0x36167A85) {
          if (millis() - last > 250) {
            on = !on;
            digitalWrite(relay1, on ? HIGH : LOW);
          }
          last = millis();
        } else if (results.value == 0x36161AE5) {
          if (millis() - last > 250) {
            on1 = !on1;
            digitalWrite(relay2, on1 ? HIGH : LOW);
          }
             last = millis();
        } else if (results.value == 0x3616FA05) {
         if (millis() - last > 250) {
            on2 = !on2;
            digitalWrite(relay3, on2 ? HIGH : LOW);
          }
            last = millis();
        }
        irrecv.resume();
      }
    }

```

**================**

I'm working on this bit of arduino code for a while now but i can't get it to work. My circuit is wired up correctly, but it isn't returning any data in the serial prompt. Here is my code:

```
#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

int main = 0;
int left = 0;
int right = 0;

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

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch (results.value) {
      case 0x2E3A06C0:
        main = 1;
        Serial.println("MAIN: on");
        break;
      case 0x8C2921D6:
        left = 1;
        Serial.println("LEFT: on");
        break;
      case 0x226270DA:
        right = 1;
        Serial.println("RIGHT: on");
        break;
      case 0x4AC6E6A:
        main = 0;
        Serial.println("MAIN: off");
        break;
      case 0xDD5E26EF:
        left = 0;
        Serial.println("LEFT: off");
        break;
      case 0x3E5BEF99:
        right = 0;
        Serial.println("RIGHT: off");
        break;
    }
    irrecv.resume();
  }

  delay(100);
}

```

I'm using the libary Arduino-IRremote. When I try the demo "IRrecvDemo", it works fine. I have the hex codes from this demo. So can someone help me get this code working? It would be nice!

# Answer
Try to put Quotation mark like this:

```
switch (results.value) {
  case "0x2E3A06C0":
    main = 1;
    Serial.println("MAIN: on");
    break;
  case "0x8C2921D6":
    left = 1;
    Serial.println("LEFT: on");
    break;
  case "0x226270DA":
    right = 1;
    Serial.println("RIGHT: on");
    break;
  case "0x4AC6E6A":
    main = 0;
    Serial.println("MAIN: off");
    break;

```

If this doesn't work too, maybe you've got a hardware problem
> 0 votes

# Answer
Did you try removing the 0x indicator? If I remember correctly the incoming signals are raw, e.g. 2E3A06C0, even though the script requires the 0x indicator on the send routines.

Alternatively, you'd need to rewrite, but you could try this IR Library and code, which I found has much better documentation and data analysis options on the receiving side: https://github.com/cyborg5/IRLib/
> 0 votes

# Answer
Well, found the problem but I don't know why. It was your variable declarations. The following code with "main, right, and left" integer variables commented out ran, the original didn't:

```
 #include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;
//int main = 0;
//int left = 0;
//int right = 0;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
        switch (results.value) {
      case 0xB9F56762:
        Serial.println("MARNIX IS RIGHT");
        break;
        case 0x8C2921D6:
//        left = 1;
        Serial.println("LEFT: on");
        break;
      case 0x226270DA:
//        right = 1;
        Serial.println("RIGHT: on");
        break;
    }
    irrecv.resume();

  }
   delay(100);
}

```
> 0 votes

# Answer
**THIS QUESTION ISN'T IN USE ANYMORE**

> Solved by using an other remote that is supported by the libary and tweaking the code.

**====NEW CODE====**

```
    #include <IRremote.h>

    int RECV_PIN = 11;
    int relay1 = 2;
    int relay2 = 3;
    int relay3 = 4;

    int on = 1;
    int on1 = 1;
    int on2 = 1;

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      digitalWrite(relay3, HIGH);
      pinMode(relay3, OUTPUT);
      digitalWrite(relay2, HIGH);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, HIGH);
      pinMode(relay1, OUTPUT);
      pinMode(13, OUTPUT);
      irrecv.blink13(true);
      irrecv.enableIRIn();
    }

    unsigned long last = millis();

    void loop() {
      if (irrecv.decode(&results)){
        if (results.value == 0x36167A85) {
          if (millis() - last > 250) {
            on = !on;
            digitalWrite(relay1, on ? HIGH : LOW);
          }
          last = millis();
        } else if (results.value == 0x36161AE5) {
          if (millis() - last > 250) {
            on1 = !on1;
            digitalWrite(relay2, on1 ? HIGH : LOW);
          }
             last = millis();
        } else if (results.value == 0x3616FA05) {
         if (millis() - last > 250) {
            on2 = !on2;
            digitalWrite(relay3, on2 ? HIGH : LOW);
          }
            last = millis();
        }
        irrecv.resume();
      }
    }

```

**================**
> 0 votes

---
Tags: serial, c++, arduino-nano, ir
---


# Question
Title: Arduino Mini Pro not working with my Neopixel project
my project involves 9 Neopixel LEDs. I have tested my code with my Arduino Uno board successfully. I'm using a mix of breadboard, jumper wires, and solder to connect everything. Powering the strip of 9 LEDs with 4 AA NiMh rechargable batteries, showing 5.2v on the meter. I've put a capacitor (1000mF 25v) in the circuit, right at the power source.

But when I upload the same code to my Mini (5v/16MHz) and swap it in in place of the Uno, I get nothing. No matter how much I jiggle wires or provide a good ground (which helped me get good results from my Uno). Every now and then by messing with wires, or as a few minutes go by, the first few lights *might* light up, but not in the right colors and no animation.

Just to test the Mini board I uploaded the sample program "blink" and the mini runs that one properly. So I'm certain my code is getting on there. My program is definitely bigger and involves some quick changes (I'm making an "ebbing" glow of supernatural eyes). Connecting the Mini to the Neopixel strip I soldered a wire with a female jumper onto the board, and my strip of lights has a wire soldered on with a male jumper. As a side note, it takes a little physical handling to get the project to work with the Uno (like pressing a little bit on the data wire in it's plug on the Uno or using a jumper wire in the breadboard clamped in a metal measuring tool and my hand to ground out the circuit). So maybe I'm just experiencing some of the shortcomings of the Mini, but I was under the impression that it would do just about anything the Uno could do. Especially in terms of just providing a data line for the LEDs.

I'm new to Neopixel. This is my first project in fact. So it is entirely possible I'm doing something wrong or there's something I just missed completely, or maybe my luck just sucks and I have some piece of faulty hardware... No idea.

Any suggestions would be most appreciated!

# Answer
As I was playing around today I found a solution. Powering the board through the FTDI adapter, which in turn was being powered by a USB juicepack charger, wasn't supplying enough juice and/or ground. It was enough for the Uno to work, so that's what was confusing me. I soldered in a 9V battery and clamped down on the pins with a wrench to ground it out. That made the board happy and it kicked into gear and lit my project up perfectly. It's pretty ghetto but it works! Yeah! :D
> 1 votes

---
Tags: arduino-uno, led, arduino-mini
---