# Question
Title: Do external battery packs need to connect to ground on the arduino?
I am going to be controlling 2 servo motors with an arduino. I will use an external battery pack for power. Do I need to connect the negative of the battery to ground on the arduino? If I just use the battery pack to power an LED, it works without connecting it to ground. Can someone please explain the logic behind this in simple wording? Thank you

# Answer
Ground is merely a label. It is a logical point in the circuit relative to which you measure all other voltages against.

For instance the 5V pin on the Arduino is actually 5V *relative to the ground pin*.

A 12V battery's `+` terminal is 12V *relative to the `-` terminal*. In this situation the `-` pin can be labelled Ground.

Electricity only ever flows when there is a circuit. That is, current can only flow when it has some way of flowing back to where it came from.

A battery with an LED and resistor attached has a circuit: *Battery -\> LED -\> Resistor -\> Battery*. An Arduino itself is a circuit: *Power -\> Arduino -\> Internal Gubbins -\> Power*

By the rule above, electricity can only ever flow out of an I/O pin if it has some way of getting back to where it came from. That route back is the Ground pin of the Arduino. Interfacing some external device with the Arduino, whether it has its own power supply or not, requires that connection back to the Arduino's ground in order for the signal you send from the Arduino to have a complete circuit.
> 4 votes

# Answer
I like the Majenko's answer, but I'm going to explain it with a different approach. You know that there are some quantities that are measurable in an absolute way (mass, lenght, weight) and other that need a starting point to refer. Think about the **distance**: you cannot say "New York" is distant 10km.. the question that obviously would come in mind is: 10km from what? So you have to decide a point in the world, from which you can measure the distance of every city.

The voltage measure the potential, that is the energy that a single charge would have. Now the question is: is the potential energy an absolute value? Of course not, i have to define a point where it is zero, and measure everything from it. In a circuit this point is called Ground, evry potential measured in the circuit is calculated to the ground.

The last step is to know that charges goes from the points at higher pot to the lowest one (the ground), usually preferring the path with lower resistsnce (but that's another story). **A wire has the same potential all along it** and in order to compare the voltage of arduino and the battery pack they must refer to the same ground.
> 3 votes

# Answer
> so because the arduino is sending a signal to one of the pins on the servo, the servo needs to be connected to Arduino's ground.

Here is typically how you might wire a servo:

Note the shared ground. The Arduino provides the control signal (data) via the orange wire. The battery provides the motor power via the red wire. The grounds must be shared or the voltages on each wire are meaningless.
> 2 votes

---
Tags: servo
---


# Question
Title: How to remote control Arduino using an old 2.4Ghz toy remote controller?
I have been wondering how to remote control my arduino robot using an old 2.4ghz car toy transmitter which has 4 buttons, up down left and right. I have the nRF24L01(+) 2.4GHz transceiver to use it as a receiver.

Is there anyway to detect the signals going out from the remote controller and use them to make my arduino works, I am a newbie so i am sorry if any mistake.

Thanks guys!

# Answer
> 3 votes
You have two options:

1. Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
2. Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.

---
Tags: nrf24l01+
---


title: How to connect GPS to IMU?

text:
# Question
Title: How to connect GPS to IMU?
I'm planning to connect GPS to IMU, Is't possible ? I tried my best to find an article that can help solving my curiosity. How can i connect GPS and MPU to arduino uno?

# Answer
> 3 votes
Is not really connecting GPS to IMU, is more like you read GPS values, read IMU values and after apply what is called a sensor fusion algorithm.

One of the most common used sensor fusion algorithms is called Kalman filter (the Extended Kalman Filter more likelly). However, if you do not have some basis on control theory you may have more trouble in applying it.

here is a good example of use of this kind of sensors and fusion algorithms. It is also very commonly used in drones or autonomous vehicles.

The implementation will be specific to what you are trying to do.

---
Tags: arduino-uno, mpu6050, tinygps
---


title: How to set Delay on GSM shield?

text:
# Question
Title: How to set Delay on GSM shield?
I bought a Gsm module recently(not official arduino shield) and i connect it to Arduino uno. The problem (I guess) is , i can't set delay properly, the terminal send it too fast that i missed it or too slow even i set its baud rate to 4800 (I have tried it with many baud from 4800-to-115200).

I uploaded the code to Git ,with this address.

More details: For example when i enter `d` in terminal it act like this message came up : `+CMTI: "SM",3` and it want to save it but it miss plus at first of it and it save `CMTI: "SM",3`,

After that it perform this : `AT+CMGR=3` the terminal show the message in half size : `+CMGR: "REC UNREAD","+9*********2","H/E.3D/1","16/02/28,00:27:02+14"` which totally missed body part.

The weird thing is when i put some println on the program it miss more characters , and second weird thing is it missed more character in second run or i push d again.

I have tried to change the delays but no success.How can i fix it ? any help would be appreciated.

**Edit**:

If i make it simpler, when i use these code i get half message :

```
#include <SoftwareSerial.h>
SoftwareSerial serialGPRS(7, 8);
void setup()
{
  Serial.begin(19200);
  serialGPRS.begin(19200);
}
void loop()
{
  serialGPRS.println("AT+CMGR=1");
  delay(1000);
  while(serialGPRS.available()!=0)
    Serial.write(serialGPRS.read());
}

```

like: `+CMGR: "REC READ","+9*******",".H/E.3D/1`

# Answer
> 2 votes
The `SoftwareSerial` receive buffer is getting filled up and discarding characters. You are not reading fast enough from the buffer. Adding `Serial.println()` will slow down your `read`ing even more. The simplest solution to this is to increase the size of the `SoftwareSerial` buffer from its default size of 64 bytes to 256 bytes (or smaller, depending on what works for you).

On a Windows PC, go to `C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial`. Open `SoftwareSerial.h` and change the line:

```
#define _SS_MAX_RX_BUFF 64 // RX buffer size

```

to

```
#define _SS_MAX_RX_BUFF 256 // RX buffer size

```

Save the file and try your sketch again.

---
Tags: gsm
---


# Question
Title: Are there any constants for default SPI port pins defined?
I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...

# Answer
> 5 votes
Yes there are. They are defined in pins\_arduino.h Below the pins for the yun.

```
// Map SPI port to 'new' pins D14..D17
static const uint8_t SS   = 17;
static const uint8_t MOSI = 16;
static const uint8_t MISO = 14;
static const uint8_t SCK  = 15;

```

Use SS MOSI MISO and SCK in your code

# Answer
> 1 votes
This is defined in the platform variant specific file `pins_arduino.h` in the variants folder (\hardware\arduino\avr\variants). Each platform variant (standard, mega, leonardo etc) gets their pin definitions set here. For instance the mega:

```
static const uint8_t SS   = 53;
static const uint8_t MOSI = 51;
static const uint8_t MISO = 50;
static const uint8_t SCK  = 52;

```

---
Tags: library, spi
---


title: Water heater coding problem

text:
# Question
Title: Water heater coding problem
I need help with my coding. I'm still learning on how to use interval `millis()`.

Currently I'm working on a water heater with a safety feature. This means that you can only pour water out when you activate the child-lock feature. The child-lock feature will turn on for 5 seconds and within that 5 seconds if you pour the water out, the timer will pause until you finish pouring your water and the 5 second timer will start again and the system goes off after that.

If the child lock feature on for 5 second without any action, it will turn off the system again. My lecturer does not allow me to use the `delay()` function so I already did my coding using `millis()`.

This is my code so far:

```
const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval1 =0;
const long interval2 = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();
unsigned long currentMillis2 = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval2){
  previousMillis = currentMillis;
  if(buttonState1 == HIGH){
   // if(currentMillis2 - previousMillis2 >=interval2){
     if (yellowLedState == LOW) {
          yellowLedState = HIGH;
}
digitalWrite(yellowLed, yellowLedState);
  } else{
  digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
}

}

```

Now, I'm able to pour out water when child lock feature activated, but the problem is the timer (interval) still ticking.

Is there any solution on how can I pause the interval whenever I'm pouring water (button2) and the interval starts back 5 sec when I release button2 (pouring water)?

I would glad if someone can help me. Ask me anything about my code.

# Answer
> 2 votes
Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :

```
const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
  digitalWrite(yellowLed,HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
  if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}
}
}

```

---
Tags: arduino-uno
---


# Question
Title: How to use a Bi-color matrix led 8x8 with 24 pins?
I've just buy this 8x8 LED matrix WLG M20088A/BEG and I'm trying to light all the LEDs in one single color (green) but I don't understand how the 24 pins work for this specific model.

I know that every manufacturer makes different models. Does anyone have any experience with this particular model?

# Answer
Take a closer look at the device schematic diagram, which I copy below. It will tell you how each of the LEDs are wired. For example, the green LED on the upper-left corner (which I marked with a green circle) has its anode (positive terminal) wired to pin 5, while its cathode (negative terminal) is wired to pin 1. Can you see that?

To light up that LED (**green** LED on the upper-left corner), you must apply voltage (with limited current), to pins 1 (-) and 5 (+). If you wanted to light up the **red** LED at the same position instead, you should apply voltage to pins 1 (-) and 20 (+).

To light up all LEDs of a given color, you'll have to connect pins 1, 2, 3, 4, 21, 22, 23 and 24 to the negative terminal of your power supply. These are the LED common anodes. They are called common because they are shared among each pair of red and green LEDs. If you choose to use the red LEDs, you'll also have to wire pins 13 through 20 to your positive supply. On the other hand, if you pick green, you'll wire pins 5 through 12. These are the LED cathodes.

Don't forget to wire a current limiting resistor in series with each LED.
> 4 votes

# Answer
It seems to be:

Row 1 - 8 --\> common cathode pins per row.

To light up a whole row, you must connect row X pin to Gnd and all green or red columns to High (Vcc). Do not forget to add a resistance in series!
> 1 votes

---
Tags: led, arduino-nano
---


title: Start timer when pins connected

text:
# Question
Title: Start timer when pins connected
I have switch is a line connected to Digital pins 1,2,3,4,5 . When pins 1 connects, I need a timer to start. as the rest connect i need it to mark the time in the console output of each one and End on the timer on connection to pin 5. ex

```
START:
0.00
1.43
2.12
2.94
3.89
END

```

Also is there a way to Save the data to a log (.txt or whatever) If not its fine but I need to record results.

(This is for a school project) THANKS!

# Answer
> 2 votes
I will not give you code, only clues on how to write the code yourself.

The way to tackle this is to (at first) remove the Arduino from the equation. Replace it, instead, with you.

Imagine you are doing the timing yourself. How would *you* go about doing it?

This is how I would set about the task:

1. When the first button gets pressed I would look at the clock and jot down the current time.
2. When the second button gets pressed I would again look at the clock, and subtract the first time from the current time to find out how much time has elapsed. I would jot that down.
3. When the third button is pressed I would do the same again - look at the clock, subtract the start time, and jot down the difference.
4. And I would keep going until I had run out of buttons.

So now you need to find the right code to read what buttons are doing, get the current time, and finally send the times somewhere useful.

For all those there are many many many examples on the web.

# Answer
> 2 votes
Are you familiar with interrupts? The best/most efficient way to do this is with pin interrupts on each input pin (and make sure your switches are wired correctly and debounced).

Unfortunately, within the Arduino libraries, there are only two pin interrupts (0 and 1), which correspond to pins 2 and 3.

You have two options:

Use a polling solution. Use one pin with an interrupt to start the timer (save the value of `millis()`) and then poll the other switches in a loop, capturing the `millis()` value at each switch closure.

Alternatively, the ATmega can fire an interrupt when *any* pin in a port changes, but IIRC this isn't built into the Arduino libraries and requires direct register manipulation.

---
Tags: arduino-uno, timers, time, wires, digital
---


title: questions about sketch

text:
# Question
Title: questions about sketch
```
int k ;
int q ;
int f;//pot

void setup() {
  pinMode(k, OUTPUT);
  pinMode(q, OUTPUT);
  pinMode(f, INPUT);
}
void loop() {
  zzf();
}

void gf()
{
  int a = f;//test the conditions of f and store in new variable int a
  if (a == 80)//if a reads 80 then increment a by 1
  {
    ei();//run the ei() function
  }
}

void ei() {
  int k = 3;
  int a = Serial.read();
  {
    digitalWrite(k, a);
  }
}

void zzf() {
  for (f = 0; f < 80; f++) {
    analogWrite(q, f);
  }
}

```

# Answer
Lean the proper C syntax. This is completely wrong:

```
void gf()
int a = f;//test the conditions of f and store in new variable int a
{

```

And this is just as wrong for the same reasons:

```
void ei()
int k = 3
int a = Serial.read();
{digitalWrite(k, a);}

```
> 5 votes

---
Tags: sketch
---


# Question
Title: Need help figuring out the pinout of a seven segmented display
A friend of mine gave me a 2in. 4 digit seven segment display. But when I sat down and looked at it, I found it has 7 pins on one side and 5 on the other and no indicators of its pinout on it. The only information I could gleam from it was the (presumably its model number) which said "PARA LIGHT A-5V4G-12-U1 H H0615". I searched online for it but only found ambiguous information that didn't help me. I have a feeling this is a fairly easy question, if so: sorry I am a noob.

# Answer
> 7 votes
Without an image of the display, I'll have to guess. With 12 pins in total, what you most likely have is: 8 pins for 7 segments and the decimal point, and 4 COMMON anodes or cathodes, a detail you will have to discover yourself. This process requires a power source that can safely light LEDs. A multimeter in diode test mode will do since theres usually about 2 V across the probes and some internal resistance, enough to light up the LEDs in the display, though they wont be very bright. I will try to list the minimum number of steps needed to determine the pinout using this method.

* Using a multimeter set to diode test mode, place the red probe on any pin (though its good to start at the edges). Now lazily run (i.e. make contact) the black probe through the remaining pins. If the display is a *common anode* display, you should see the all the segments of a **particular** digit (not **different** digits) light up in sequence.
* Else, keep running the black probe through the pins until any segment at all lights up. Hold the black probe on that pin that caused the segment to turn on. Now run the red probe through the other pins. If all the segments of a particular digit light up in sequence, this indicates a *common cathode* display.
* Another possibility is that no segment lights up at all, despite steps 1 & 2. Substitute the red probe, where it is held steady, for the black probe. Run the red probe through the remaining pins. If all the segments of a particular digit light up, then the display is a *common cathode* display.
* On the other hand, if no digit's segments light up sequentially while running the red probe through the pins, but at least one segment of any digit lights up, then hold the red probe steady on its current pin, and run the black probe instead through the other pins. If all the segments of a digit light up in sequence, then you have a *common anode* display.

Take note of the pin that was held constant, in any of the cases above.

Now that you know what kind of display you have, you now need to discover the pinout for the segments and common anodes/cathodes. Get paper and pen so you can label each pin with its function. Create a table with pin numbers in one column (pin 1 - 12) and the pin functions (which you will find out) in the second column.

* This image shows the segment labels. During the testing above, one probe (PROBE A) was held steady on one pin while the other (PROBE B) was run through the other pins. This caused all the segments of a digit to turn on. The pin connected steadily to PROBE A is the COMMON pin for the digit whose segments lit up. So in your table, **Pin xx = COMMON for Digit yy**.
* To get the COMMON for other digits, move PROBE A to another pin and run PROBE B through the other pins until another digit has all its segments turned on in sequence. The pin connected to PROBE A is the COMMON for that digit. Include this in your table. Repeat until you have identified the COMMON for each digit.
* Finally to get the segment pins A - G and DP, place PROBE A on any of the COMMONs you have in your table and run PROBE B through the other pins. Each time a segment lights up, the pin connected to PROBE B should be associated with that segment's label in your table. E.g. if segment C lights up when PROBE B is on pin 10, then the table should have something like **pin 10 = C**. Keep going until you have all the segment pins identified.

---
Tags: electronics
---


# Question
Title: Cannot find Arduino under /dev Directory
I have the Arduino board connected to a USB port of my machine. But I cannot find it under /dev/ directory in my Ubuntu. Does anyone know how to deal with this issue? By the way, "lsusb"'s output proves that it has been recognized. Here is the output of this command:

```
Bus 002 Device 002: ID 8087:8000 Intel Corp.
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 8087:8008 Intel Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 003 Device 007: ID 413c:2105 Dell Computer Corp. Model L100 Keyboard
Bus 003 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

```

Here is the output of ls -l /dev/ttyACM\*

```
ls: cannot access /dev/ttyACM*: No such file or directory

```

and the dmesg output when disconnect and reconnect the device:

```
[1653809.002715] usb 3-11: USB disconnect, device number 13
[1653832.188835] usb 3-11: new full-speed USB device number 14 using xhci_hcd
[1653832.211392] usb 3-11: New USB device found, idVendor=2341, idProduct=0043
[1653832.218400] usb 3-11: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[1653832.226003] usb 3-11: Manufacturer: Arduino (www.arduino.cc)
[1653832.231859] usb 3-11: SerialNumber: 85235353137351708191
[1653832.237468] usb 3-11: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes

```

# Answer
> 1 votes
Note that lsusb does not guarantee the drives are loaded (See https://superuser.com/questions/165733/will-lsusb-and-lspci-list-devices-for-which-the-system-has-no-drivers)

Per the https://stackoverflow.com/a/14586884/1653571 answer, try an 'lsmod' and see whether you have a 'cdc\_acm' module loaded.

---
Tags: arduino-uno, ubuntu
---


# Question
Title: Error opening serial port 'COM1'. (Port busy)
Im using the arduino Micro pro to read the data out of a temperature sensor (lm35). The program is compiling and NOT uploading, but when I try and open the serial monitor is says: Error opening serial port 'COM1'. (Port busy)

# Answer
> 3 votes
I've got an idea. Your board isn't being recognized. Try unplugging the arduino and see if Com 1 is still there. Sometimes it can recognize mice and other devices as Com 1 or 2 instead of your arduino.

On some of my development machines after everything settled out my devices will show up on Com 4 and 5 when I am working on two at a time.

If this is not the case go into the device manager and see if you can see the board listed.

I would also wonder if you have your sensor hooked to digital pins 0 and 1. These pins are used for your serial line on usb. So if you have anything such as a sensor hooked to them it may be generating data keeping the line busy instead of it being able to negotiate.

I had this happen when setting up hc-05 for the first time. I realized I had to keep the chip off while flashing or I would end up with errors or Com busy.

Please provide your pinout and basic information about the Com ports available on the ide. Also consider that you will need to specify the correct board as it will default to an uno.

Programmer not in sync issues generally occur because the board is recognized but cannot be written to for one reason or another.

* the board has something plugged into digital 1 and 0 which are serial i/o pins
* the board programmer is busy running your last batch of code
* usb error

So

* try a different cord
* try unplugging potential wiring issues and see if it can be written to without anything on it
* try holding down reset on the board until the board when you try to write to it until just after it finishes compiling to clear any potential programing issues

In my experience mega have a tendency to suffer from the last one.

# Answer
> 0 votes
Simple solution:

Close the arduino application and start again.

if still the issue persist restart your system. :)

# Answer
> 0 votes
I had a similar issue (port busy, RN42+Win 8.1) and find a solution by changing the usb bluetooth dongle of the computer.

The one which finally works for me was the Adafruit Bluetooth 4.0 USB Module (v2.1 Back-Compatible).

---
Tags: arduino-pro-micro
---


# Question
Title: Clock drift - is the precision of the crystal the only culprit?
I've a wall clock (sorry, code's a mess, look for `updateClockVars`) which makes use of the Timezone library (and ultimately Time). Nothing fancy, call millis() every loop; turn to Hrs, Mins, Secs; display on LEDs.

The magnitude of the drift I am seeing on my 2 Arduino Pro Mini - compatible boards - up to ~8% lag, not a typo - blows my mind. Replacing the 16MHz quartz with one bought at a local retailer didn't help much (~33% improvement). Is something else at play here?

# Answer
The problem is the interaction between the interrupt handler that updates the value for the millis() function and the neopixels show() function.

To maintain the counter for the millis() function a interrupt is triggered approximately every 1.024 ms.

When the show() function is called all interrupts are disabled to get the precise timing needed to send the data to the neopixels. For a 60 led strip this takes about 1800 microseconds (60 leds * 24 bits * 1.25 us per bit) so at least one interrupt is skipped each time you update the display.

This page has details about how the millis() function works.
> 6 votes

# Answer
TL;DR You're doing it wrong. Use RTC.

Ok, longer explaination is required here. `millis()` is not accurate and here is why.

First, grab official Arduino source code from their Github repo. The file `Arduino-master/hardware/arduino/avr/cores/arduino/Arduino.h` contains few interesting macros (I'm pasting `grep` output here):

```
Arduino.h:#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
Arduino.h:#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
Arduino.h:#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

```

At 16MHz `clockCyclesPerMicrosecond()` will evaluate to `16`. Keep this number in memory.

Those macros are used in `Arduino-master/hardware/arduino/avr/cores/arduino/wiring.c`:

```
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

// the whole number of milliseconds per timer0 overflow
#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)

```

`MICROSECONDS_PER_TIMER0_OVERFLOW` macro is evaluated as `(64 * 256)/16` \- a dodgy looking **1024**. Look how they round it down to calcuate `MILLIS_INC`.

Let's assume that you run your Arduino with **ideal** main clock signal. At 16MHz main clock, the timer frequency is 1.024kHz, not 1kHz. This results in 2.4% inaccuracy. You can get away with that in most cases, but **not when you're building a clock**.

This 2.4% error is best case. Your main oscillator is not 16MHz - it has it's own inaccuracy, that is unknown and it sums up.

You should use an external, accurate time reference provided by RTC module. When assembled properly, they guarante low time drift, temperature compensation and other goodies. Be smart - use RTC. :)

If you are scared of I2C RTC modules, you may find my tutorial and another tutorial on MCP7940N RTC module. Know-how is applicable with other RTCs as well.
> 3 votes

# Answer
Expanding on my previous comment...

As I said before, I suspect the NeoPixel library to be blocking interrupts for too long when you `strip.show()`. If a timer interrupt fires while interrupts are blocked... it's not a big deal: the interrupt request is put on hold and serviced as soon as interrupts are enabled again. If **two** timer interrupts fire while interrupts are blocked... you have a problem: the interrupt service routine will be called only once, and your clock will miss a tick.

Craig has worked out the timings in his answer: the timer interrupt fires every 1.024 ms, and NeoPixel blocks interrupts for 1.8 ms. So it is perfectly expected that, from time to time, you will have two timer interrupts within this 1.8 ms window.

Here is a quick hack that could solve your problem: if you `strip.show()` *right after* a timer interrupt is serviced, then only one more interrupt should fire during the subsequent 1.8 ms window, and you should be fine. So you could simply add this *right before* `strip.show()`:

```
/* Wait for a timer interrupt to be serviced. */
uint32_t lastMillis = millis();
while (millis() == lastMillis) /* wait */;

```

A possibly better solution would be to avoid blocking interrupts for so long. NeoPixel blocks them in order to comply with the very tight timing requirements of the WS2812 LEDs. But it turns out the WS2812s are not nearly as picky about timings as their datasheet suggests. You can drive them in a more relaxed way, with interrupts enabled except for 1-bit durations, and they still work fine. For a detailed explanation and sample code, see NeoPixels Revealed: How to (not need to) generate precisely timed signals.

A third solution would be to follow the general advice given here and grab an RTC. However, although it certainly is a good and clean solution, I have to admit I completely agree with your comment “*I still didn't catch WHY that is better – it's a quartz either way*”.
> 3 votes

---
Tags: time
---


# Question
Title: How to serially transfer/read an image to Arduino
I am using Arduino Uno and the image size is 12.7 kb. I want to read a jpeg image from computer and convert into bitmap in arduino. Later on it will be implemented using SD card.Is it possible to read a .jpeg image from computer to Arduino using serial communication? If yes, then how?

# Answer
You can send anything you like through the serial port. It is just 8-bit raw data. The onus is on you, however, to implement a suitable high level protocol with which to transfer the data.

One important thing to bear in mind though: JPEG is a highly compressed complex image format. I am not aware that anyone has ever managed to squeeze JPEG decompression into a lowly Arduino. Instead you will need to use a decompressed image format such as BMP, or do the decompression on the computer before-hand and send the raw RGB image data over the serial instead.
> 4 votes

# Answer
Of course you can, but as stated in the comments and in the other answer JPEG use a complex algorithm to compress the images, and most computers have a dedicated hardware to perform the cosens discrete transform. Anyway the answer to your question is yes, and it's not hard.

You just have to split the image into bytes, send them through the serial port and make Arduino read and save them into an array. To avoid errors create a protocol that can decode what are you doing.

For example: 0b1111000 for 3 times = Start sending 0b00011000 = new line and so on..

The first thing that come in my mind is to use the pySerial library, that can automate the process. Python is perfect for prototyping: open the image (maybe using the numpy library instead of using lists) and with a for loop send every byte over the serial port in according to the protocol you created.

On the Arduino just code the protocol to understand every bite and save the image in an array.
> 0 votes

---
Tags: serial
---


# Question
Title: Arduino Yun & nRF24L01+ -> Linino crashing
I'm trying to hook up a nRF24L01+ wireless transmitter to an Arduino Yun Mini on SPI, but I'm having a hard time. After a few minutes Linino crashes and becomes completetly inaccessible - until I upload a new sketch to the Arduino.

I connected the SPI pins (MOSI, MISO and SCK) to the corrensponding pins of the Yun. I connected CE to pin 3 and CSN to pin 2. I'm using the RF24 library found here: https://github.com/TMRh20/RF24

The following little code is enough to make Linino crash:

```
#include <SPI.h>
#include "RF24.h"

RF24 radio(3,2);

void setup() {
  radio.begin();
}

void loop() {

}

```

What am I doing wrong here? Any ideas? Any help is greatly appreciated!

# Answer
I finally managed to get it running. It really seems to be a problem with radio interference. I failed to hook up an external WLAN antenna to the Arduino Yun mini but I found a very useful workaround with a usb adapter here: http://www.lucadentella.it/en/2014/11/08/yun-adattatore-wifi-usb/

This workaround is possible with an Arduino Yun mini as well but you'll need the Arduino Yun Linux OS from here: https://www.arduino.cc/en/Main/Software

because the necessary packages are not available for the Linino system that comes with the Yun mini. Then, you can connect the WiFi adapter to USB+, USB-, 5V and GND of the Yun mini and you're good to go.
> 0 votes

---
Tags: arduino-yun, nrf24l01+
---


title: Photoresistor Switch

text:
# Question
Title: Photoresistor Switch
How would I use a photoresistor like a switch. My issue is it is always bleeding out a little bit of power and always on. Is there a way to connect it to a digital pin and when a resistance of xxx is ment, set another digital pin to On?

# Answer
> 1 votes
To turn an analog signal into a digital signal, at some sort of threshold xxx, you need to either condition it in electronic circuitry, with something like an amplifier or a comparator, or read the analog signal directly and apply the threshold in software.

You likely need to connect the photoresistor as half of a voltage divider, as in Why do you need a second resistor when using a photoresistor/LDR?

---
Tags: arduino-uno, relay, digital, resistor, photoresistor
---


# Question
Title: Unable to connect Ethernet shield W5100 to localhost
I have an Arduino Uno and a W5100 Ethernet Shield. I am trying to post some data from the Arduino board to the WAMP server running on my computer. I do not have a router so I have directly connected my Ethernet shield stacked onto the Arduino Uno to the laptop's Ethernet port via an Ethernet cable. I have also assigned the Ethernet connection a static IP address 192.168.0.1 and my localhost page opens when I put this address in my browser.

In my Arduino sketch I have assigned the Arduino shield an IP address 192.168.0.4, i.e. on the same IP segment. When I try to do client.connect to the server (192.168.0.1), i.e. localhost, I get "Connection failed".

```
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x6F, 0xED };
IPAddress ip(192,168,0,4);
byte server[]={192,168,0,1};

int value=9;
EthernetClient client;

void setup() {
  // Serial.begin starts the serial connection between computer and Arduino
  Serial.begin(9600);
  // start the Ethernet connection
  Ethernet.begin(mac,ip);
}

void loop() {
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    client.print("GET /Ethernet/getData.php?"); // This
    client.print("value="); // This
    client.print(value); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.1");
    client.println("Connection: close");
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server
  }

  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  delay(10000);
}

```

Now when I upload the sketch onto the board and run the serial monitor, I get this output:

My Ethernet connection detail screenshot is as follows:

Please tell me any changes that I must make and also are there any WAMP settings which I should change to allow the connection to get established?

Please consider the fact that I don't have a router anywhere in this connection - just my laptop and Ethernet shield connection.

# Answer
After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.

Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.
> 1 votes

# Answer
Well, the problem has been solved. The Ethernet shield was not properly stacked onto the Arduino board which caused connection to fail.
> 1 votes

---
Tags: arduino-uno, ethernet
---


# Question
Title: how to count blinking LED flashes using arduino uno boards and LDR?
i want to know code for counting the flashes of LEDs and display no. of flashes in particular time given.by using LDR. basically i tried it with interrupts but i'm not getting it,so please help in this regard.

# Answer
> 0 votes
An hardware solution could be achieved by putting a photodiode or a photoresistance near the flashing LED. Connect it to a pin that supports external interrupt and you're done. With a bit more circuitry you can ensure that the value on the pin doesn't oscillate: put a Schmit Trigger after the photodiode or resitance with its output on the input pin.

# Answer
> 1 votes
LDRs only give an analog output, proportional to the amount of light.

To make it give a HIGH and LOW value, you have to tweak the other resistor used in the voltage divider.

Alternatively you could use `analogRead` and add a threshold value in your code.

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


title: Nick Gammon's Hex Converter Error

text:
# Question
Title: Nick Gammon's Hex Converter Error
I'm trying to add a bootloader hex to Nick Gammon's Atmega Board Programmer sketch, and I can't seem to get a hex file to convert.

I need to convert "Arduino-usbserial-atmega16u2-Uno-Rev3.hex", but that wasn't working so I thought I'd try converting one that's already used in the sketch, "Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex", but that's not working either. I've followed the instructions from http://www.gammon.com.au/bootloader

I've tried it using Wine and Paralells. Clicking the copy button when using Wine causes the program to stop responding.

Here is a screenshot of the error:

Thank you

# Answer
~~I can't reproduce that.~~

My apologies - I couldn't quite read the error message in the screen dump. What you got was:

```
Don't know end address for 0
Please add to table: end_addresses
Run-time error
World: smaug2
Immediate execution
[string "Immediate"]:96: Cannot continue
stack traceback:
        [C]: in function 'error'
        [string "Immediate"]:96: in function 'process'
        [string "Immediate"]:134: in main chunk

```

The relevant error is the first line. That file has code for address 0 - which is not part of the bootloader. It tries to detect bootloader addresses, and zero is not one of them. Looking at the start of the file I see this:

```
:1000000090C00000A9C00000A7C00000A5C000006B
:10001000A3C00000A1C000009FC000009DC0000060
:100020009BC0000099C0000097C0000048C40000B9
:100030000CC4000091C000008FC000008DC0000003
:100040008BC0000089C0000087C0000085C0000090
:1000500083C0000081C000007FC0000002C100001A
:100060007BC0000079C0000077C0000075C00000B0
:1000700073C0000071C000006FC000006DC00000C0
:100080006BC0000069C0000067C0000065C00000D0
:1000900063C0000061C000001201100102000008EE
:1000A0004123430001000102DC0109023E0002017C
:1000B00000C0320904000001020201000524000111
:1000C0001004240206052406000107058203080027
:1000D000FF09040100020A000000070504024000B5
:1000E00001070583024000010403090432034100B3
:1000F00072006400750069006E006F002000280027
:100100007700770077002E006100720064007500B0
:1001100069006E006F002E0063006300290000007C
:10012000000011241FBECFEFD2E0DEBFCDBF11E033
:10013000A0E0B1E0ECEAFFE002C005900D92A6312C

```

In particular the format is:

```
 :10 0000 00 90C00000A9C00000A7C00000A5C00000 6B
  ^  ^^^^ ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^
len  addr TT   data                          sumcheck

```

So this file includes code for the Atmega16U2 *as well as* the bootloader.

My sketch is not designed to program non-bootloaders (it is a bootloader programmer after all).

---

Scroll down that page for how to reprogram the Atmega16U2 chip.

The bootloader programmer sketch (as published) will put the **bootloader** onto the Atmega16U2. Then follow the instructions on that page, or on this page, below, for entering DFU mode and uploading the main part of the code (not the bootloader part).

---

## Entering DFU mode

If you have just flashed the bootloader using the bootloader programmer sketch then it should enter DFU mode, visible because the pin 13 LED flashes rapidly.

If not, enter DFU mode by shorting together Reset and Ground briefly with a screwdriver or similar. They are the two left-most pins visible in the image above, nearest to the Reset button and below the hole on the board.

(Don't keep them shorted, just a brief touch should do it).

Once in DFU mode, you should see it appear as an Atmel USB device, if you type `lsusb` (on Linux):

```
$ lsusb
...
Bus 003 Device 092: ID 03eb:2fef Atmel Corp.
...

```

A Uno which is not in USB mode might look like this:

```
$ lsusb
...
Bus 003 Device 090: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
...

```

(or not appear at all if there is no firmware on it).

If you are using Ubuntu or similar you can obtain the DFU programmer as follows:

```
 sudo apt-get install dfu-programmer

```

You can obtain the code for the firmware from here:

http://gammon.com.au/Arduino/Arduino-atmega16u2-Uno-firmware-Rev3.hex

(RH-click and "save as" to put a copy on your hard disk).

Assuming you place that firmware in the current directory of your terminal window, you can now flash the code as follows:

```
sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

```

You should see a message like:

```
Validating...
4034 bytes used (32.83%)

```

Now you can unplug the USB cable, plug it back in, and the USB interface should be back to factory settings.

For other operating systems, such as Windows, you should be able to get a copy of the DFU programmer from:
> 1 votes

---
Tags: arduino-uno, bootloader
---


# Question
Title: Arduino controlled light dimmer software
I found this software:

```
/*

AC Voltage dimmer with Zero cross detection
Author: Charith Fernanado <a href="http://www.inmojo.com">  http://www.inmojo.com

</a>
Adapted by DIY_bloke
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table
(the Pin numbers are digital pins, NOT physical pins:
digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)
check: <a href="http://arduino.cc/en/Reference/attachInterrupt">  http://www.inmojo.com

</a>

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All -But it is INT1 on the Leonardo
3      |  1            |  All -But it is INT0 on the Leonardo
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only
0      |  0            |  Leonardo
1      |  3            |  Leonardo
7      |  4            |  Leonardo
The Arduino Due has no standard interrupt pins as an iterrupt can be attached to almosty any pin.

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay
                 // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  for (int i=5; i <= 128; i++){
    dimming=i;
    delay(10);
   }
}

```

But don't uderstand this part:

> (10000us - 10us) / 128 = 75 (Approx) For 60Hz =\>65

I know 10000us is 10ms, and we need to wait less then 10ms to dim light.

But don't understand why here we has -10us and /128.

Anyone know why is that?

# Answer
> 3 votes
-10uS because of the 10uS delay at the end of the loop, and /128 because he has decided there will be 128 possible dimming levels.

---
Tags: voltage
---


# Question
Title: How to wire and use a B10K linear LED potentiometer?
I've bought some nice looking LED potentiometers from Ebay. They look like this. I'm very new to low level electronics/hardware and I don't know how to wire it. It has 4+2 pins. Also, how to use it in the Arduino?

# Answer
The Taiwan Alpha spec sheet page 2 for this type of pot shows a little information about the pinout. Refer to the second “P.C.B. MOUNTING HOLE DETAIL” diagram, which apparently shows the top side PCB layout. The LED's anode is at lower right, marked B; its cathode is lower left, marked E. It doesn't say what L (the pin next to E) is. The three numbered pins most probably are: 1 and 3, ends of the resistive element. 2, wiper.

If that is correct, you could attach pin 1 to 5V, pin 3 to ground, and pin 2 to an analog input. Before hooking it up like that, however, take ohmmeter readings from pin 1 to pin 2 as you move the slider from one end to the other and see if readings change proportionately to position.

Note, the phrase “Center Dent” on the ebay page probably should instead be “Center Detent” or “Center Click”.
> 2 votes

---
Tags: led, analogread, potentiometer
---


# Question
Title: How to stop uno from running program when powered on?
Does anyone know how to prevent the Uno from running the last program when it's powered on?

Many times I have changed hardware and wiring without clearing the program first. Then when I power it on to upload the new program it will run the old program until it's uploaded. This has many potential unwanted effects when the old program is running with the new hardware installed.

# Answer
> 13 votes
The simplest thing is to upload the new program before connecting the hardware.

If this isn't practical, connect a jumper wire from the Reset pin to ground (Gnd) before powering it on. This will hold in a reset state, and the program won't run.

Then, compile and upload your program. As it starts to upload remove the reset wire. That should upload it without running any existing program.

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


title: Arduino documentation on PCIFR and PINC

text:
# Question
Title: Arduino documentation on PCIFR and PINC
I was reading this thread:

Read RC receiver channels using Interrupt instead of PulseIn

and I have been trying to understand the code provided within.

While I was able to udnerstand most of it, I am still unable to find proper documentation on Arduino PCIFR and PINC?

Could someone please point me in the right direction?

Thanks in advance.

# Answer
Welcome to Arduino.SE. The documentation that you seek on `PCIFR` and `PINC` would not be documented under Arduino, this is as these are directly related to the ATMega328 (AVR Atmel micrcontroller) which is on the Arduino, they are registers which are inside the microcontroller and `PCIFR` and `PINC` are mnemonics.

For the ATMega328 you will find the documentation to these registers in the datasheet (a good read with coffee), or in tutorials written by others explaining this information in an easy to grasp way.

The `PCIFR` register is the Pin Change interrupt flag register(description on pg 73 of linked datasheet), this holds the flag bit to tell the microcontroller that there was an interrupt and runs the `ISR()` routine that one has set out. Read this post by Nick Gammon on Pin Change Interrupts, and then read all of the post to get a better idea of interrupts in general.

The register `PINC` is for the inputs to the microcontroller, when one uses `staus = digitalRead(A0);` they are in effect using a wrapped up version of bitwise math and bit manipulation when simplified to `status = PINC & (1 << PC0);` thus `PINx` (x is for the register name ABCD) represents the state of the pin, either *HIGH(1, 5V, true)* or *LOW(0, 0V, False)*. Borrowing from the below linked tutorial:

Another nice description of the input ports in this tutorial.

From the image you see that moving a bit to a position and then bitwise `&` that with `PINx` you will have a value returned if there is a 1 in **that** position.

```
 PINC      0b00001001
(1 << PC0) 0b00000001
         & __________
status  =  0b00000001

```

The above shows how you only get the state of the first input and how the 4th input is ignored as it was not needed. Also worth noting PIN is the register description and is not the same as a physical pin that sticks out the IC's body.
> 3 votes

---
Tags: arduino-uno
---


# Question
Title: Return value of 0 if value is less than zero
Background: I am using an analog pressure sensor with a range from 0-100PSI returning voltage values .44v to 4.44v. It's open air (or 0 PSI) voltage on the signal pin is .47 volts. I have a function that subtracts that .47v (to make zero) and then multiplies it by 25 (25 PSI per volt). Due to signal noise or other factors, sometimes my function returns a negative number, which wreaks havoc on my math. I would like to return a value of 0 when my offset math returns a negative number, but I'm having a problem with it.

The code that I wrote that doesn't work:

```
double EngineOilPressure() {
    //insert oil pressure code here
    int reading = analogRead(sensorPin3);
    float voltage = reading * 5.0;
    voltage /=1024.0;

    Serial.print(voltage); Serial.println(" volts");

    if (voltage-.47 < 0)
    {
        float voltadj = 0;
    }
    else
    {
        float voltadj = (voltage-.47);
    }

    float pressureP = voltadj * 25;
    return PSIToPascal(pressureP);
}

```

The error that I get is

```
dynamic_engine.pde: In function 'double EngineOilPressure()':
dynamic_engine.pde:41:23: error: 'voltadj' was not declared in this scope
Error compiling.

```

The code that works but sometimes returns a very wrong value:

```
double EngineOilPressure() {
    int reading = analogRead(sensorPin3);
    float voltage = reading * 5.0;
    voltage /=1024.0;

    Serial.print(voltage); Serial.println(" volts");

    float pressureP = (voltage - .47) * 25;
    return PSIToPascal(pressureP);
}

```

# Answer
The scope of each of the two different and unrelated `voltadj` variables that your code (as below) declares is limited to within its enclosing set of braces.

```
if (voltage-.47 < 0)
{
    float voltadj = 0;
}
else
{
    float voltadj = (voltage-.47);
}

```

Instead perhaps say

```
float voltadj = voltage-.47;
if (voltadj < 0) voltadj = 0;

```

or perhaps

```
float voltadj = voltage < .47? 0 : voltage-.47;

```

or

```
float voltadj = constrain(voltage-0.47, 0.0, 5.0);

```

or

```
float voltadj = max(0.0, voltage-0.47);

```

Also see max() and constrain() reference pages at arduino.cc.
> 5 votes

# Answer
Another method, though one that is quite cryptic to understand, would be:

```
float pressureP = voltage > 0.47 ? (voltage - 0.47) * 25 : 0;

```

That is known (by me at least) as an *inline conditional*. The `?` acts as an `if` operator, and the `:` as an else. Basically it's saying:

```
Voltage is greater than 0.47
Is that true?
    then subtract 0.47 and multiply by 25 and assign it
otherwise:
    assign 0

```

The format is simply:

```
value = {condition} ? {true value or expression} : {false value or expression};

```

If can be quite useful when you want to conditionally calculate or assign something. @jwpat7 makes mention of a `max()` function above. That `max()` function can itself be written with this inline conditional format:

```
maxval = a > b ? a : b;

```

Or: If `a` is greater than `b` then assign `a` otherwise assign `b`.
> 1 votes

# Answer
The Arduino way is to use constrain

```
float pressureP = constrain ((voltage - 0.47) * 25 , 0 [The Maximum your code can handle]);

```

This will return the value ((voltage - 0.47) * 25) but never less than 0 and never more than The maximum you provide.
> 1 votes

---
Tags: programming, sensors
---


title: Fritzing PCB design review/questions

text:
# Question
Title: Fritzing PCB design review/questions
I've designed an PCB and due tot the delivery times, I kinda want to order it right now. I don't yet have the components, so I haven't actually tried it on a breadboard.

Now I'm unsure if the PCB would work, as this also is my first try in PCB design.

It's a single-sided PCB. All parts (should be) through hole. I would be using SoftwareSerial since the ATTiny does not have serial (Rx/Tx).

\[TL:DR\] Would this PCB work?

Some points of which I'm unsure, or might be a problem:

1. Is the spacing of the board/lines to other components/side big enough?
2. Should I use a copper/ground fill? Which and why?
3. Are the rounded-off traces actually better as sharp edges?
4. It says: 36mm by 15mm isn't this too small to fit all those components?
5. Can I actually use the RESET pin as other functions (without changing fuse bits)?
6. Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

**Breadboard**

**Schematic**

**Layout**

**File**

If someone needs the file: It's opensource, no restrictions. Would be nice to give me some credits/donation, but you can freely use it for even commercial projects. Download below:

https://www.dropbox.com/s/lggjg5fxd6s3kqc/ATTINY485.fzz?dl=0

Some credits to Nick Gammon, I've used his schematics as a reference (especially on the TX enable pin, which was quite smart, using only 1 pin).

**Version2!**

Changes: \- replaced the "V" shape. \- pull-up on the reset pin. \- decoupling capacitors

EDIT: It's better not to use a pull-up resistor on the reset line. The ATtiny85 has this internally.

# Answer
> Would this PCB work?

Possibly, sometimes, under some conditions. See below.

> Is the spacing of the board/lines to other components/side big enough?

Plenty.

> Should I use a copper/ground fill? Which and why?

For your circuit there is no real electrical reason to use a ground plane. However, many fab houses like you to use at least a copper fill in the empty areas since it means less copper has to be etched off the board, and so their etchant lasts longer before it needs to be replaced.

> Are the rounded-off traces actually better as sharp edges?

Yes. Always try to avoid right-angles. Sharp corners radiate EMI noise, mitred corners radiate a lot less.

> It says: 36mm by 15mm isn't this too small to fit all those components?

Not in the slightest.

> Can I actually use the RESET pin as other functions (without changing fuse bits)?

You can only disable the RESET functionality of the RESET pin using the fuse bits - and then it becomes somewhat difficult to program: you need a HVSP (High Voltage Serial Programmer) to get it back into programming mode again. This blog post details how it is done.

> Doesn't it need any resistors? I've seen some on the RS485 breakout boards.

Your circuit isn't complete. There are a couple of things missing that you need to add, and some that you might want to add.

The things that are missing:

* Decoupling capacitors (100nF) on the power pins of both chips
* You should have one larger (10µF typical) reservoir capacitor at the power entry to the board
* (Assuming RESET is enabled) Pullup resistor on the RESET pin

The things you might want to add:

* RS-485 bus termination resistors

The latter are optional depending on where in the bus your module is. You need termination resistors at both ends, so it is common to have them on the boards but with jumpers to enable/disable them.
> 2 votes

# Answer
> Is the spacing of the board/lines to other components/side big enough?

Looks ok. You might be able to squeeze it a few mm smaller each way, although since the board already is small, that probably would make little difference in cost.

> Should I use a copper/ground fill? Which and why?

Copper/ground fill on a single-sided board won't make much difference for this circuit. It would be reasonable, however, to make the ground traces two or three times as wide as they are.

> Are the rounded-off traces actually better as sharp edges?

If you mean, make square corners rather than the 45° turns as shown, either way will make little difference for this circuit. The 45° turns are ok.

Note, sharp V-notches, like the one inside the traces at pin 2 of the Tiny85, are undesirable; I think they etch less accurately than more-open junctions do.

> It says: 36mm by 15mm isn't this too small to fit all those components?

Looks like there's room to spare and the board could be made slightly smaller.

For homemade boards that are drilled using a hand-cranked XY table, keeping drilled holes on the intersections of a .1"x.1" grid is a good idea. For commercially-made boards, it's less important but can help with assembly.

*Edit:* Regarding “Making ground traces bigger makes sense, but does that also mean 5V traces should be bigger?”, yes, both ground and power traces typically should be large, if board layout allows. It's desirable that those traces have low inductance and it's ok to have high capacitance between ground and power traces.

Regarding how long it takes to get your PCB back from a manufacturer: The PCBshopper.com website makes it easy to compare time vs cost across a range of manufacturers. For small circuits like yours, OSHpark is an inexpensive choice (you would get three double-sided boards for under $5, in about 15 days). If you need up to about 10 medium-size boards, Maker Studio is quite economical but standard delivery may be slow (2-3 weeks). If you are in a hurry and need a larger number of boards, consider (eg) PCBway. By paying $25 for DHL shipping, you can have a batch of boards in 9 or 10 days – about three days for manufacture and a week for delivery. The pictures below show an example of PCBway's order tracking, the left side at about two days after the order was placed, the right side 11 hours later. This order for 50 each 36 mm x 56 mm two-layer boards with silk both sides cost $27 for manufacture and $25 for delivery.
> 2 votes

---
Tags: pcb-design
---


# Question
Title: Neopixel Ring - How to breathe in a circle motion?
I'm trying to get an effect like (https://vine.co/v/Mwwbi5a1BFK) using a neopixel ring. I can get the neopixels to turn on and off in a circle motion and I can get the neopixels to fade all at once. What I can't get working is combining the two together. Any help would be much appreciated!

*EDIT* Tried making fade with the circle motion

```
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  ledTrail(50, 100, 100,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
}

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
const byte extra = 4;  // how many ahead, and behind, to light up

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, int steps, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  int tmpR, tmpG, tmpB;         // Temp values
  // Fade up
  for (int s=1; s<=steps; s++) {
    tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (Gf * s) / steps;
    tmpB = (Bf * s) / steps;

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

    // now go "extra" pixels ahead and behind
    for (int s = 1; s < extra + 1; s++)
      {
      tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
      tmpG = (Gf * (extra - s)) / extra;
      tmpB = (Bf * (extra - s)) / extra;
      myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
      myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
      }

        // Fade down
  for (int s=steps; s>0; s--) {
    tmpR = (Rf * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (Gf * s) / steps;
    tmpB = (Bf * s) / steps;
  }

    myNeoPixels.show();
    delay(pause);
  }
   }
}

```

*LED TRAIN CODE*

```
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  ledTrail(100, 255,255,255, 0,0,0);       // Pause; R,G,B foreground; R,G,B background
}

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);
    myNeoPixels.show();
    delay(pause);
  }

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rb,Gb,Bb);
    myNeoPixels.show();
    delay(pause);
  }
}

```

*BREATHING CODE*

```
#include <Adafruit_NeoPixel.h>          // Library for NeoPixels

#define pinPix 6                       // Pin driving NeoPixel Ring or String
#define numPix 8                       // Number of NeoPixels in the Ring or Strip

// Setup NeoPixel Ring
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number driving the strip
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel myNeoPixels = Adafruit_NeoPixel(numPix, pinPix, NEO_GRB + NEO_KHZ800);

void setup() {
  myNeoPixels.begin();   // Initialize the NeoPixel array in the Arduino's memory,
  myNeoPixels.show();    // turn all pixels off, and upload to ring or string

}

void loop() {
  breathe(20, 100, 255,255,255);       // Pause; Number of steps; Full-on R,G,B values
}

// Pause = delay between transitions
// Steps = number of steps
// R, G, B = Full-on RGB values
void breathe(int pause, int steps, byte R, byte G, byte B) {

  int tmpR, tmpG, tmpB;         // Temp values

  // Fade up
  for (int s=1; s<=steps; s++) {
    tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (G * s) / steps;
    tmpB = (B * s) / steps;

    for (int i=0; i<numPix; i++) {
      myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
    }
    myNeoPixels.show();
    delay(pause);
  }

  // Fade down
  for (int s=steps; s>0; s--) {
    tmpR = (R * s) / steps;     // Multiply first to avoid truncation errors
    tmpG = (G * s) / steps;
    tmpB = (B * s) / steps;

    for (int i=0; i<numPix; i++) {
      myNeoPixels.setPixelColor(i,tmpR,tmpG,tmpB);
    }
    myNeoPixels.show();
    delay(pause);
  }

  delay(pause * 30);
}

```

# Answer
I don't have any NeoPixels to try it with (yet) however this should do it. Replace the ledTrail function by this:

```
const byte extra = 4;  // how many ahead, and behind, to light up

// Pause = delay between transitions
// Rf, Gf, Bf = RGB "Foreground" values
// Rb, Gb, Bb = RGB "Background" values
void ledTrail(int pause, byte Rf, byte Gf, byte Bf, byte Rb, byte Gb, byte Bb) {

  int tmpR, tmpG, tmpB;         // Temp values

  for (int i=0; i<numPix; i++) {
    myNeoPixels.setPixelColor(i,Rf,Gf,Bf);

    // now go "extra" pixels ahead and behind
    for (int s = 1; s < extra + 1; s++)
      {
      tmpR = (Rf * (extra - s)) / extra;     // Multiply first to avoid truncation errors
      tmpG = (Gf * (extra - s)) / extra;
      tmpB = (Bf * (extra - s)) / extra;
      myNeoPixels.setPixelColor((i + s) % numPix,tmpR,tmpG,tmpB);
      myNeoPixels.setPixelColor((i + numPix - s) % numPix,tmpR,tmpG,tmpB);
      }

    myNeoPixels.show();
    delay(pause);
  }
}

```

What this is doing is having an inner loop that "looks ahead" and behind another `extra` pixels and makes them brighter/darker. Debugging code (since removed) shows the effect:

```
i = 4, R = 255, G = 255, B = 255   <-- original code
i = 5, R = 191, G = 191, B = 191   <-- one ahead  (darker)
i = 3, R = 191, G = 191, B = 191   <-- one behind (darker)
i = 6, R = 127, G = 127, B = 127   <-- two ahead  (darker still)
i = 2, R = 127, G = 127, B = 127   <-- two behind (darker still)
i = 7, R = 63, G = 63, B = 63      <-- and so on
i = 1, R = 63, G = 63, B = 63
i = 8, R = 0, G = 0, B = 0
i = 0, R = 0, G = 0, B = 0

```
> 1 votes

---
Tags: arduino-uno, led, neopixel
---


# Question
Title: Reading Arduino serial stream in Java using jSerialComm
I'm having issues reading the actual double values from my Arduino `Serial.println()` in my Java app. I've tried following usage examples found here but get what I guess is a hex value. The serial monitor within the Arduino program is displaying the correct values.

This is the code: I'm fairly new to this and would appreciate any comments regarding style/problems/inefficiencies within my code!

```
import com.fazecast.jSerialComm.*;
import java.util.*;
import java.io.*;

public class PortRead {
  public static SerialPort userPort;
  static InputStream in;

  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    /*
     This returns an array of commport addresses, not useful for the client
     but useful for iterating through to get an actual list of com parts available
    */
    SerialPort ports[] = SerialPort.getCommPorts();
    int i = 1;
    //User port selection
    System.out.println("COM Ports available on machine");
    for (SerialPort port : ports) {
      //iterator to pass through port array
      System.out.println(i++ + ": " + port.getSystemPortName()); //print windows com ports
    }
    System.out.println("Please select COM PORT: 'COM#'");
    SerialPort userPort = SerialPort.getCommPort(input.nextLine());

    //Initializing port
    userPort.openPort();
    if (userPort.isOpen()) {
    System.out.println("Port initialized!");
    //timeout not needed for event based reading
    //userPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
    } else {
    System.out.println("Port not available");
    return;
    }

    userPort.addDataListener(new SerialPortDataListener() {
      @Override
      public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
      }
      public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
        return;
        byte[] newData = new byte[userPort.bytesAvailable()];
        int numRead = userPort.readBytes(newData, newData.length);
        System.out.println("Read " + numRead + " bytes.");
      }
    });
  }
}

```

# Answer
> 0 votes
Since you are reading received data into array `newData`, you should replace `System.out.println("Read " + numRead + " bytes.");` with `System.out.print(newData);` (not sure about the syntax, since I dont know Java) if you want to print the actual data received and not just the number of bytes received.

---
Tags: serial, communication
---


# Question
Title: How do I adjust the scale/calibration of a photoresistor?
This photoresistor has a min/max of 0-1023.

I'm trying to scale the brightness of a cathode RGB LED based on the sensor's value, but based on my current lighting, the min/max readings I generally am getting are 100-700.

So how can I scale the sensor reading so that 100 = no light on the LED and 700 = max brightness?

# Answer
You can easily scale in Arduino code with the map() function.

e.g.:

```
const int MIN_LIGHT 100;
const int MAX_LIGHT 700;

int light_reading = analogRead(A0);

// Convert MIN reading (100) -> MAX reading (700) to a range 0->100.
int percentage_bright = map(light_reading, MIN_LIGHT, MAX_LIGHT, 0, 100);

```

But you may need some calibration of your system to handle different ambient light situations. What reading do you get in direct sunlight for example?

So then I assume you're using PWM (Pulse Width Modulation) to drive the LED. This requires a value between 0 & 255. Once again we can use the map() function.

```
// Convert light-value % (0-100) to PWM speed (0-255)
int led_brightness = map(percentage_bright, 0, 100, 0, 255);
analogWrite(LED_PIN_RED, led_brightness);

```

Obviously these bits of code can be reduced down to a single line - mapping directly from the reading to the desired result.
> 2 votes

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


# Question
Title: Arduino vs Raspberry, Advantages And Disadvantes
I have done extensive research into the differences and here are the questions i have:

1. What is a micro controller and what differs it from the raspberry pi system
2. Why buy the Arduino when it is less powerful than the raspberry pi
3. What projects would either system be better for
4. Does Arduino run a full OS
5. Where is the best place to buy arduino and raspberry pi
6. What is the difference in the ad dons
7. Which has the most tutorials
8. What is the different's in power supply and usages
9. I know i'm asking this on a forum with arduino fans (There is no arduino vs raspberry pi forum) but opinions aside which is the best for beginners (I can program C++ and python as well as building hardware components)
10. What is the general price different overall including buying extra ad dons/shields

Thank you for your answers :)

# Answer
1) Here is a great article about microcontrollers and how they differ from a full computer: http://electronics.howstuffworks.com/microcontroller1.htm tl;dr: A Raspberry Pi runs a full desktop OS (often Linux) and as such, can do most of the things a "typical" computer can do, such as browse the internet or install different programs. An Arduino, however, cannot do that. An Arduino can run one piece of software that you program to it (called a sketch in the Arduino world) and repeat that same program over and over.

2) They have different purposes. A Raspberry Pi is designed as a low-cost desktop computer that you can put anywhere, and also as a platform that is easy to put into different projects. An Arduino is better suited for attaching sensors to, controlling motors, etc.

3) see #2 Also, a Raspberry Pi is typically used when a GUI is wanted, or when more computing power is required. An Arduino is typically used for more real time things such as reading sensors or controlling LED's.

4) No, it does not. Arduino's run C++ compiled as machine code object files.

5) For the Raspberry Pi, Here is the list of official resellers: https://www.raspberrypi.org/products/model-b-plus/ For the arduino, it depends on what kind you're buying and where you live, there are many different styles.

6) As a general rule, Arduino's have more shields. But, a raspberry pi typically needs a screen, mouse, keyboard, etc. Everything a standard computer needs.

7) Entirely depends on what you're trying to do.

8) Both take a 5V input voltage. An Arduino can take up to a 20v input (again, depending on the model) whereas the Raspberry Pi can just be powered with 5v over USB.

9) Again, depends on what you're trying to do. A Raspberry Pi is "easier" to use, as it's a full computer.
> 1 votes

---
Tags: programming, power, raspberrypi
---


# Question
Title: Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller
I recently bought this linear actuator and motor controller from Pololu:

There are several steps that I have to follow in order to set this thing up before I can test it. These instructions can be found here: Pololu JRK USB Motor Controller User’s Guide » Setting Up Your System

I would like to program this using PWM method because I would like to keep the Serial RX for other sensors. From my little experiment, by using a potentiometer, I noticed this pattern:

Position: Voltage

1. Fully extended : 0 V
2. At Rest : 2.35V
3. Fully Retracted : 4.77V.

For this system, I will be controlling it using a PS2 controller. So, by using only the Y\_axis of the analog joystick of a PS2 Controller (Up: 0, Rest: 128 and Down: 255), I program it as follows:

```
//Move Linear Actuator with PS2 on JRK21v3 Controller

#define pwm 6           //red wire
#define dir 7           //yellow wire

//PS2 controller
#include <SoftwareSerial.h>
#include <Cytron_PS2Shield.h>

Cytron_PS2Shield ps2(10, 11); // SoftwareSerial: Rx and Tx pin

void setup()
{
  pinMode(pwm,OUTPUT);

  ps2.begin(9600);
  Serial.begin(9600);
}

void loop()
{
  int Y_axis = ps2.readButton(PS2_JOYSTICK_RIGHT_Y_AXIS);  // 0 - 255
  Serial.print("Y_axis:");
  Serial.println(Y_axis);

  analogWrite(pwm, Y_axis);
}

```

When I tested it, the linear actuator jitters/vibrates when it is at rest position. What could possibly cause this? Is it the duty cycle due to the PWM? How can I fix this or are there any other better methods?

# Answer
The Pololu jrk 21v3 motor controller supports four input modalities: via USB, via TTL-level serial, via RC / pulse width control, and via the mode you are trying to use, an analog 0-5V input.

It appears you are trying to use a PWM output to produce an analog signal control mode. A PWM signal is a pulsed digital output rather than an analog signal. The 21v3 may be jittering its control setpoint back and forth between 0V and 5V at a high frequency, which will make the linear actuator jitter.

Try adding an RC low-pass filter to the PWM output, ie between your PWM pin 6 and the input to the 21v3. (Note, it might make more sense to use a software-serial output to control the 21v3, instead of using a PWM output with a low-pass filter, which may still allow use of hardware serial for your other sensors...)

To verify if an RC filter will work, try at first with large R (eg 5KΩ to 10KΩ) and large C (eg 5μF to 10μF) to see if the jitter goes away. If so, you then can tune the filter to find how small you can make R or C and still avoid jitter. A filter with smaller RC will allow higher-frequency control than will one with larger RC, but may be more prone to jitter. R should be somewhat less than the input impedance of the 21v3's analog input. To determine that value, look at the data sheet of whatever chip that input goes into.
> 0 votes

# Answer
I got this working using the Servo library.

* You set the input method to PWM.
* Connect your RX on the motor controller and hook it up to the servo pin.
* Connect the ground of the Arduino to the ground of the JRK 21v3.
* Then use the knob servo sample by hooking up a pot to a Arduino.
* The calibrate the JRK 21v3 by selecting learn.

Now you can use the actuator as a servo.
> 2 votes

---
Tags: arduino-mega, motor, pwm, robotics
---


# Question
Title: How do I install the latest Arduino IDE on Ubuntu 14.04LTS?
What I've tried:

* I downloaded the package for 1.6.7 on Ubuntu 14.04 LTS but when I open it no matter what I try it will not start.
* I installed 1.0.5 from the Ubuntu Software Center. I tried to update it but found no solution.

UPDATE: I found my answer in talamaki's answer on that other question linked above.

# Answer
Follow the following step to download, install and run Arduino IDE on Ubuntu

1. First Download the Tar (tar-bal) from this link http://arduino.cc/en/Main/Software (download the correct 32 / 64 bit linux version ) depends upon your Ubuntu version.
2. Then goto download folder using terminal (shell) or the folder where you downloaded the tar and unpacked that tar using the following commands like cd /Downloads tar -zxvf arduino-1.6.7-linux32.tgz where 1.6.7 is the version of ide
3. you also need java runtime environment for arduino IDE download and install it using the following command sudo apt-get install openjdk-7-jre
4. you also need to provide the UART permissions for your hardware using following commands sudo chmod a+rw /dev/ttyACM0 where ACM0 is the port number if you are using multiple or many arduinos just give permissions using the above commands by replacing the ACM0 to ACM1 to ACMN

5. then create a shortcut of arduino ide from the folder where you extract the tar cd ~/Desktop ln -s /Downloads/arduino-1.6.7/arduino

and then double click the shortcut to run arduino if it gives permission error then right click the shortcut and in file preferences gives permissions to the shortcut
> 0 votes

---
Tags: arduino-ide, ubuntu, installation
---


title: Configure HC-05

text:
# Question
Title: Configure HC-05
I am trying to send/receive data from Android to my Arduino (via a HC-05) and later from Arduino to Android. I have configured my HC-05 as slave, and the UART=9600,0,0.... To send data from Android to Arduino I don´t have problem but to send data Arduino to Android I can not...

This is my sketch:

```
char data;
int a=1;
int v=1;
#include SoftwareSerial connection(10,11);//RX|TX
void setup()
{
 pinMode(7,OUTPUT);
 connection.begin(9600);
 digitalWrite(7,LOW);
}

void loop()
{
 if(connection.available()>0)
 {
  data=connection.read();
   if(data=='1')
   {
    digitalWrite(7,HIGH);
    connection.write(data);
    delay(200);
   }
   //connection.write(data);
  }
 }

```

MY HANDLER IN THE MAIN:

```
       mhandler=new Handler()        {
        public void handleMessage(android.os.Message msg)            {
            switch (msg.what)
            {
                case MENSSAGESEND:
                    msg = new DriveData((BluetoothSocket)msg.obj);    //DriveData msg = new DriveData((BluetoothSocket)msg.obj);
                    break;
                case MESSAGEREADING:
                    byte[] bufferget = (byte[])msg.obj;
                    String men = new String(bufferget,0,msg.arg1);
                    sb.append(men);
                    int endline=sb.indexOf("\n");
                    if(endline>0)
                    {
                        String print=sb.substring(0,endline);
                        sb.delete(0, sb.length());
                        Toast.makeText(getApplicationContext(),"menssage"+" "+print,Toast.LENGTH_LONG).show();
                        txtData.setText(print);
                    }
                    break;

            }
        };
    };

```

MY METHOD FOR RECEIVER AND SEND DATA

```
  public void run()
    {
        byte[] wait=new byte[1024];
        int bytesReceived;
        while (true) {
            try {
                 bytesReceived=entrydata.read(wait);//entrydata is my inputstream
                mhandler.obtainMessage(MESSAGEREADING,bytesReceived,-1,wait).sendToTarget();
            }catch (IOException e){
                break;
            }
        }
    }

```

# Answer
> 2 votes
You are missing the line termination you must send '\n' after your data in order to receive the data or use conexion.println(entrada) rather then conexion.write(entrada)

---
Tags: arduino-uno, bluetooth, android, hc-05
---


# Question
Title: Why isn't there bus contention on the MISO line during SPI-based programming?
Consider this image from sparkfun:

Let's say I have this setup, a master and *n* slaves, plus a programmer connected to the SPI lines.

When I program the master (Arduino), the Arduino is reset. This means that all the data pins go low.

Since SS is active low, all the SS pins on the slaves go active.

I believe this means that all the slaves start driving the same MISO line (blue arrow from slaves to master), either high or low.

Doesn't this result in bus contention on that line? If not, what's the mechanism that prevents bus contention from happening?

# Answer
Yes, you *can* get SPI bus contention when using multiple SPI slave devices. It is up to you, the designer, to ensure that each SPI slave device has its chip select (CS or SS) asserted only when no other devices are driving MISO. Normally that is achieved by:

* initialize all of the CS pins high (inactive) during setup
* in the code that accesses SPI device #1,
    + assert SPI device #1 CS1 low (active)
    + perform SPI transfers on SPI device #1
    + release SPI device #1 CS1 high (inactive)
* in the code that accesses SPI device #2,
    + assert SPI device #2 CS2 low (active)
    + perform SPI transfers on SPI device #1
    + release SPI device #2 CS2 high (inactive)

SPI bus contention can also occur during device programming (loading the bootloader or firmware image), if there is an attached SPI slave device, and its chip select (SS) is not pulled inactive by a pullup resistor.

I had a problem with this on one of my designs a few weeks ago. I was trying to burn the bootloader into some blank ATmega328-AU chips post-assembly, and my device programmer wasn't able to successfully program the chips because my one slave device had its chip select connected only to an ATmega328 pin.

I had previously breadboarded this design using an Arduino Pro Mini board, and it was working fine; but when I moved to first prototype PCB there was bus contention on MISO -- the blank ATmega328 wasn't driving the slave device's chip select high or low, but it floated low (active), causing MISO contention.

My solution (workaround) was temporarily contacting the chip-select to VDD 3.3V through a 10kohm resistor. This made my SPI slave device inactive, allowing the device programmer to successfully load the bootloader.

I think there would be no harm in leaving the pullup resistor on chip select (since it's an active-low signal), but it was only really necessary when using the device programmer. After I had the prototype boards initialized with the bootloader image, I was subsequently able to load firmware images as usual.

*(One minor unrelated issue was that my assembler purchased ATmega328-AU when I had specified ATmega328P-AU -- they are almost the same, and it doesn't make a difference for my application, but it was annoying that I had to use a slightly different command line argument than then one I used with the Arduino Pro Mini board.)*
> 3 votes

---
Tags: spi
---


title: Integration of signal

text:
# Question
Title: Integration of signal
In my house, I have a low voltage AC signal (0-10V) that is proportional to the amount of current that is drawn at any moment (or as it is presented: kW) (europe, 50Hz). Presently, it is just shown as a dial in my kitchen, of course I would to log this. I want to rectify and integrate this singnal over an appropriate time span (maybe on minute) As far as I can see, I basically have two ways of doing this:

1. The pure arduino approach: Using a voltage divider to get it down to 0-5 V (after rectification) (and maybe throw in a zener diode as an extra protection) Then using an adc in the arduino and measure the voltage directly. The problem I foresee with this approach is that I will need a pretty high sampling rate to make sure I get the peak values. If I managed to sample at exactly the same frequency as my mains,I could just calibrate the measured value (unless I managed to hit the cross overs) but I do not think that would be feasible So I think I need to maybe sample on approx 500 Hz and pick out the highest value from each 1/50 second.
2. Using an opamp, a few resistors and a capasitor to set up an analog integration circuit, then use the arduino to read out and reset that at appropriate times. Setting up the integration circuit is no problem for me, but I need some feedback on the reset circuit. I have been looking around a bit, but I have not found any standard way to reset an integrator circuit, it seems like the idea is that it should be integrating for as long as it is running.. As far as I can see, as long as it running on \<= 5V, I could use an input on the arduino to drain it? - I would then need to make the dimensions such that the low current the arduino input draws will allow the integrator to be reset fast enough.

Any comments? Have I overlooked something? is there a third approach that I have not been thinking about? Is the 1st approach easier that what I think?

# Answer
Sorry, but.. Why integration? Just use a peak detector like this one:

The output will "float" to the peak value of the input signal, minus the voltage drop across the diode:

The output oscillates between 9.7V and 9.2V, which is a 5% maximum error. If you want to reduce it, sample with a sample rate not multiple of 50Hz and average the measures.

The RC constant is 500ms. This means that it will require less than a second to pass from a value to a lower one:

Here in almost 500ms it will go from 10V to 5V.

If you want to reduce the diode effect (9.7V instead of 10V) use a schottky diode. This, however, will not reduce the 9.2V effect.

You should divide by 2 the voltage; you can either

1. divide it before the diode (but then the diode effect will be more evident - you can however correct it in software
2. divide it after the circuit (In this case, replace the 500k resistor with two 250k resistors and take the voltage in the middle)

Of course 500k and 250k are not standard values, but you can use any nearby value without affecting the behavior
> 3 votes

# Answer
With an Arduino Uno, you can get 9615 samples per second from an analog input, and do the data processing at the same time. That's more than enough to reliably detect a peak. For this, you have to set the ADC to "free running mode" and do the processing in the ADC interrupt service routine. Se this answer for a detailed explanation and code.

Oh, and instead of peak detection, you could just integrate your signal. That should be simpler, and simple is good for interrupt-driven data processing.
> 1 votes

# Answer
I'm not quite clear on the 'peak' detection - this would mean your reading would be changing several times a second potentially. Does the current in your house vary that much per second? I don't think your electricity meter is that clever anyway (there must be a smoothing effect, I reckon). For example, if you turned on your electric kettle for 1/50th of a second, would your domestic meter accurately record that (or the 0-10V signal vary)? I personally doubt it but I'm no meter designer! Anyway, you also mention that you want to log over a minute? I'm unclear on the exact requirements here.

Anyway, if you are reading the 'max' current (so you can accurately calculate bills, for example) I think your first approach would work - after all a 50Hz sampling rate is very low for an Arduino. You won't need a 500Hz sample rate as the data doesn't change *that* frequently anyway, does it?

Perhaps you could trigger the sampling activity by synchronising to the mains frequency (which you sort of allude to) and then do the reading? Use an analog input to detect the rising LV mains cycle and then do the reading? Or use a Schmidt trigger to trigger the Arduino (sounds a bit of overkill, I think the Arduino could do it all).

Experimentation is called for to see what works and what doesn't but your first approach seems eminently feasible to me.
> 0 votes

---
Tags: adc, analog-sampling
---


title: Communication between Arduino and XBee

text:
# Question
Title: Communication between Arduino and XBee
I have two XBee Pro S2Bs: one is plugged in to a USB explorer, and; the other is plugged into an Arduino Wireless Protoshield, which is connected to an Arduino Uno.

My XBee connected to the explorer is configured as the *coordinator* in AT mode, and the XBee connected to the Arduino is configured as a *router* in AT mode. As a side note, I tested the network with a second USB explorer, and I was able to communicate between both XBees.

I uploaded the following code to the Arduino (which is just a sample I pulled off the internet somewhere):

```
char rx_byte;

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

void loop()
{
    if (Serial.available() > 0)
    {
        rx_byte = Serial.read();
        Serial.print("You Typed: ");
        Serial.println(rx_byte);
    }
}

```

Once I upload the code and turn on the serial monitor for the Arduino (using either the Arduino IDE or Visual Micro, with the Arduino plugged in via USB), and turn on the serial monitor on for the XBee connected to the USB explorer (using the serial monitor in XCTU), I get the following results:

* If the wireless proto shield has its switch set to USB mode, then I can send data from the Arduino serial monitor to the serial monitor in XCTU, but the Arduino serial monitor doesn't receive data that is typed into the XCTU serial monitor.
* If the wireless proto shield has its switch set to Micro mode, then I get mostly the opposite result. I can send data from XCTU serial monitor to the Arduino serial monitor, which the result is returned to the XCTU serial monitor, e.g., if I type "X" in XCTU serial monitor, both serial monitors say "You Typed: X". However, if I try to send data through the Arduino's serial monitor, neither serial monitor displays anything.

What I would like to do is be able to type in either serial monitor and have the data displayed in both serial monitors, like you would expect in a simple chat program.

Can someone see where I have gone wrong and/or how to get to the correct result?

# Answer
> 2 votes
Check out https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test Essentially you need to set up Software Serial for your xbee to communicate on a couple of digital pins, instead of using hardware serial. When using hardware serial (the RX and TX pins) only one device works on it at a time, hence why you can't use the xbee and the serial monitor at the same time.

---
Tags: arduino-uno, serial, xbee
---