# Question
Title: Question different ways of connecting L298N motor driver board to arduino and motors and powering them
I read few posts and tutorials on this topic but none of them kind of answered my questions. I bought this L298N motor board and i have two motors that are rated 3V

Now i am trying to understand how to connect it to arduino and power the motors.
For example i have a 12V (8x 1.5v AA batteries) I can connect to VCC and GND then enable ENA with a jumper and connect PWN port from arduino to INA. This way i can control the voltage that is coming out from OUTA and OUTB I can bring down the 12V to 3V.
Now the question is can i use the +5 (regulated voltage) on the driver board and connect it to arduino Vin and GND to ground to power the arduino? Is that viable solution. I actually tried it and it works. I am worried that it is not enough voltage to properly power the arduino. It's suggested to connect 7v - 12v to Vin. I am also going to connect a red lab ble shield on top of arduino that is powered by 5v

Another question is if i use 12 volts battery and step it down to 3v with PWN is that going to heat up the L298N chip?

Another option is connecting 9V battery to arduino and then using Vin and GND to power the motor shield and the motors. The problem there if motor draws more then 1Amp that wouldn't be good for the arduino. Also if i would switch to 9v+ motors then it wouldn't work.

The third option is to have two separate power sources. 9V for arduino and 5v+ for powering the motors. Does it make sense to use two power sources?

This project seems like a good way to learn about arduino and electronics

Update

NEOMART Brand New Original High Quality Chips L298N http://www.amazon.com/gp/product/B00E58EA90/ref=oh\_aui\_detailpage\_o04\_s00?ie=UTF8&psc=1 Product Details 1. driver chip: L298N Dual H-Bridge Motor Driver IC

2. drive section terminal supply area Vs: +5V ~ +35V; such as the need to take power within the board, the supply area Vs: +7V ~ +35V
3. drive section peak current Io: 2A
4. logical part of the terminal supply area Vss: +5V ~ +7V(can take power within the board +5V)
5. logical part of the operating current range: 0 ~ 36mA
6. Control signal input voltage range: Low:-0.3V ≤ Vin ≤ 1.5V High: 2.3V ≤ Vin ≤ Vss
7. enable signal input voltage range: Low: -0.3 ≤ Vin ≤ 1.5V (control signal is invalid) High: 2.3V ≤ Vin ≤ Vss (control signal active)
8. Maximum power consumption: 20W (when the temperature T = 75℃)
9. Storage temperature: -25℃ ~ +130℃
10. Driver Board Size: 48mm\*43mm\*33mm (with fixed copper pillar and the heat sink height)
11. Other Extensions: control of direction indicators, the logic part of the plate to take power interface.

Update 2:

I wanted to clarify regarding using 12 volt battery and having 2 motors that I think max voltage is 3 volts. If i use PWN and step down the voltage to 3 volts will L298N produce a lot more heat to step the voltage down?
Probably in this case would be the best just to get two separate power supplies 9 volts for arduino and 4.5 volts for the motor drive to supply 3 volts for each motor. Unless i get better motors that support 6v - 9v then i can use the 12 volts battery for both arduino and motors.

As far as the motor drivers, I thought they are used to prevent the noise and power spikes from motors? I guess you still have to consider it either way.

Thanks in advance!

# Answer
> 5 votes
Here is a link to a robotoid page which describes a way to use it.
Here is a link to funnyrobotics which explains how to use it.

I am confident that you could use a search engine to find more examples.

One trick is to use image search. Then look for pictures which look like your photo, and which have extra writing on them. Most people who add labels and writing to the photo are writing to help beginners understand how to use something.

Edit: That L298N board claims to have a 5V regulator for powering the Arduino, in which case you could use a single power supply, and let the motor board feed the Arduino.

There are two schools of thought on powering the Arduino and motors:

1. Use two separate power supplies, one for the motor and one for the Arduino.
2. Use one supply for both the motor, and Arduino.

Using one supply is simple overall. One concern is electric motors can create a lot of electrical noise. If this is not adequately filtered, it might get injected into the Arduino and maybe cause the microcontroller to reset, or become temporarily unstable. The single supply advocates say the power supply to the Arduino should be properly filtered using capacitors and a proper voltage regulator usually, and the problem is solved.

I agree in principle. However, I have seen situations where the transient failure was so brief it looked 'mysterious'. It took time and effort to track it down. Sometimes it was because the motor power supply was underpowered. When the motor 'stalled', for example when changing direction, taking maximum current, the power supply voltage might dip enough to cause the Arduino supply to dip, and reset the chip.

Summary, if you are going to use a single power source for both motor and Arduino, ensure it has plenty of electrical noise filtering, and is a bit over-engineered to cope with the motor stalling. Specifically, it should be able to supply the motors stall current without dipping too low for the Arduino. The 'professional' approach is to have the Arduino monitor the main power supply, and detect that voltage dip. However, that is more complexity, and I suggest you avoid that.

Edit: If you are concerned you might have weird, hard to trace problems, using a single supply, try to design the system so that the Arduino can be 'unplugged' and given its own supply. That should be easy to do with that L298N board as the connections are screw terminals.

Using two separate power supplies should *reduce* the chances of electrical noise from the motors getting into the Arduino. In some circumstances is it useful to be able to change the motor power supply, or switch it off, without powering the Arduino off.

When the motor voltage is a lot higher than the 5V needed by the arduino, simple techniques to step down the voltage (linear regulators, like the part on that L298N board) convert the excess power to heat, which is quite inefficient. Much above, about, 18V it can generate enough heat to reach quite a high temperature (i.e. 100C) unless it has a good heatsink.

In that case, a simple, cheap solution is to use a second small power supply for the Arduino. An Arduino is likely using under 100mA, so a PP3 would be okay for, maybe, a few hours. A longer term approach is to step the motor voltage down efficiently.

If you use two power supplies, connect the two 'ground' (i.e. or most negative battery connections) together so that they have a common 'ground' reference. That way the Arduino signals will control the motor driver reliably.

Edit: PWM does not step down voltage. It gives the illusion of less power because the full voltage is only applied for a fraction of each millisecond. When it is on, it is providing (very close to) the full 'motor' voltage. If the 'motor voltage' connected to that L298N board is 12V, then the motor will see 12V.

However, even if the motor is rated at only 3volts, it is unlikely to break only because 12V is applied across it. A 3V motor is as likely to break because it gets too hot, or spun too fast (e.g. the bearings get damaged).

It will likely get too hot under load, or spin too fast if the PWM signal is on for more than, WAG 50% of the time (but there is no warranty with WAG = Wild-A$$-Guess).

If, and only if, your software doesn't run PWM more than 50%, then those motors may be okay. That is a risk I might be prepared to take if the motors are cheap, and replacements easy to get.

Skimming the datasheet, the L298N needs an absolute *minimum* motor supply of 2.3V+2.5V = 4.8V.
Also, the output switches which control the motor appear to 'drop' a minimum of 1.8volts.
So I think it would be okay with 6V or 7.2V (maybe upto 9V) motor voltage.

IIRC the arduino will work okay with 7.2V upwards, i.e. 6 x NiMh batteries. A higher voltage is just converted to heat by the on-board voltage regulator. I might be tempted to experiment with the L298N boards 5V output, unless you have seen complaints about it.

I am assuming the motors are brushed DC motors (and not steppers or something exotic)

The motor driver will handle switching the current that the motor needs. However, each time the current is switched on or off, the motor will draw current, or generate current (remember it is a motor and also a generator). That could cause the power rail to dip, or even feed current into power or ground. There are diodes on the board to prevent those spikes doing anything awful to the chip, but there is still current flowing through wires.

Further, every rev of the motor, the brushes will break one connection, and make a different connection with the commutator, typically 6 times. (The commutator is the mechanical system that directs the current to flow the correct way round in the motors spinning electromagnet). That creates electrical noise. In some cases so much that you can hear it on an old fashioned radio receiver or analogue TV.

So noise may be a problem. People typically put a 10nF-100nF, relatively high voltage (say 50V), capacitor directly across the motors power connections, at the motor end.

If things get bad, I did a quick search and this blog looked okay, it illustrates ways to use capacitors and inductors to reduce motor noise.

I wouldn't worry too much. Put 10nF-100nF across the motor wires, and see what happens.

---
Tags: motor, arduino-motor-shield
---


# Question
Title: Using multiple laptop battery packs to power everything
I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.

I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.

Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?

Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?

(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)

I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.

# Answer
In case you didn't know it already you can hook any batteries in parallel by adding a diode on every battery to avoid current from any other battery flowing back to it. Like this:

```
 battery
      |+  diode
+----||--->|---+
|     |        |
|              |
|     |+       |
+----||--->|---+----o V++
|     |
|
_
V GND

```

**The drawback** is that you have a small drop of voltage on the diodes and of course a small power loss too. If for example you're drawing 0.5 Amp from the batteries and you're using an 1N4001 diode which has a voltage drop of about 0.7 Volts then expect 0.350 Watts of power loss (0.5A x 0.7V). So choose the diode with the lowest voltage drop that can handle the current you need. There are solutions to lower the power that is wasted but they're more complex.
> 2 votes

# Answer
I'd be cautious about hooking them in parallel. According to ADAfruit power leakage between batteries *is* a problem.

> \[multipack parallel\] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one *will* try to charge an old worn battery to its own fresh voltage.
> 3 votes

---
Tags: power, battery
---


# Question
Title: Controlling Floppy Disk Drive with Arduino
I am having problems controlling a 3.5" Floppy Disk Drive with an Arduino Uno.

I have the floppy disk drive powered with a computer power supply that is switched on, and the Arduino powered by my computer's USB. I have cut apart the ribbon of a 34-pin IDC connector to be able to route the pins to my Arduino. I am able to turn the floppy disk motor on and move the read/write head back and forth, but I am never able to read any pulses from the Track-0 or Index pins.

I have pins 7, 15, 17, 19, and 25 from the floppy all grounded to my Arduino, and I have pins 8, 16, 18, 20, and 26 from the floppy connected to my arduino as output pins so I can control the drive.

I am expecting the Index to pulse when the disk motor makes a rotation, and for Track 0 to change when I am at the outside of the disk, but they are both always LOW. Am I missing something?

**Here is the spec I found for the back of the floppy disk unit**

```
    2   /REDWC  Input Density Select
    4   n/c N/A Reserved
    6   n/c N/A Reserved
    8   /INDEX  Output Index
    10  /MOTEA  Input Motor Enable A
    12  /DRVSB  Input Drive Sel B
    14  /DRVSA  Input Drive Sel A
    16  /MOTEB  Input Motor Enable B
    18  /DIR    Input Direction
    20  /STEP   Input Step
    22  /WDATE  Input Write Data
    24  /WGATE  Input Floppy Write Enable
    26  /TRK00  Output Track 0
    28  /WPT    Output Write Protect
    30  /RDATA  Output Read Data
    32  /SIDE1  Input  Head Select
    34  /DSKCHG Output Disk Change/Ready

```

**Here a schematic of what I have hooked up** ***(The breadboard in this circuit diagram represents the IDC connector that is plugged into the 3.5" floppy drive.)***

**Here is a photo of the IDC Connector and I labelled which wires are connected to the Arduino.**

**Here's the code I am running.**

```
//constants
static const int IN = LOW;
static const int OUT = HIGH;
static const int pulseDelayTime = 6;

//pins
int indexPin = 2; //8 on the drive INDEX
int track0Pin = 3; //26 on the drive. TRACK 0
int dirPin = 6; //18 on the drive. DIRECTION
int stepPin = 7; //20 on the drive. STEP
int motorEnableBPin = 9; //16 on the drive. MOTOR ENABLE B

unsigned long motorSpinTime = 1000UL; //in ms

void setup() {

  //initial delay
  delay(3000);

  //setup serial monitor
  Serial.begin(9600);

  //setup pins.
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(motorEnableBPin, OUTPUT);
  pinMode(indexPin, INPUT);
  pinMode(track0Pin, INPUT);

  //turn the motor off initially
  digitalWrite(motorEnableBPin, HIGH);

  //print state here.
  printState("Setup done.");

  //spin the disk some.
  printState("Begin to spin motor");
  spinMotorForThisManyMs(motorSpinTime);
  spinMotorForThisManyMs(motorSpinTime);
  printState("Done spinning motor");

  //step read/write head all the way in.
  stepAllTheWayIn();

  //spin the disk some more.
  printState("Begin to spin motor");
  spinMotorForThisManyMs(motorSpinTime);
  spinMotorForThisManyMs(motorSpinTime);
  printState("Done spinning motor");

  //step read/write head all the way out.
  stepAllTheWayOut();

  //spin the disk even more.
  printState("Begin to spin motor");
  spinMotorForThisManyMs(motorSpinTime);
  spinMotorForThisManyMs(motorSpinTime);
  printState("Done spinning motor");

  //never completes.
  waitForIndex();
}

void loop() {
}

//spins the disk motor for a number of ms and prints the state
void spinMotorForThisManyMs(unsigned long msToSpin) {

  //start spinning
  digitalWrite(motorEnableBPin,LOW);

  //delay.. keep printing the state
  unsigned long maxTimeMs = millis() + msToSpin;
  while(millis() < maxTimeMs ) {
    printState("Spinning");
  }

  //stop spinning
  digitalWrite(motorEnableBPin,HIGH);
}

//step the read/write head all the way to the center
void stepAllTheWayIn() {
  for(int i=0;i<100;i++) {
    printState("Stepping In");
    stepInALittle();
  }
}

//step the read/write head all the way to the outside
void stepAllTheWayOut() {
  for(int i=0;i<100;i++) {
    printState("Stepping Out");
    stepOutALittle();
  }
}

//print the state of the index and track
void printState(const char* charPrint) {
  Serial.print(" Index:");
  Serial.print(digitalRead(indexPin));
  Serial.print(" Track:");
  Serial.print(digitalRead(track0Pin));
  Serial.print(" ");
  Serial.println(charPrint);
}

//move the head towards the outside a little
void stepOutALittle() {
  digitalWrite(dirPin,HIGH);
  stepPulse();
}

//move the head towards the center a little
void stepInALittle() {
  digitalWrite(dirPin,LOW);
  stepPulse();
}

//pulse the step pin
void stepPulse() {
  digitalWrite(stepPin,LOW);
  delay(pulseDelayTime);
  digitalWrite(stepPin,HIGH);
}

//waits for the index to trigger. this never gets completed.
void waitForIndex() {

  printState("beginning to wait for index pin to pulse");

  //start spinning
  digitalWrite(motorEnableBPin,LOW);

  //wait for pulse
  while(digitalRead(indexPin));
  //wait for end of pulse 0
  while(!digitalRead(indexPin));

  printState("end of waiting for index pin to pulse");

  //stop spinning
  digitalWrite(motorEnableBPin,HIGH);
}

```

**Here is the output I am getting.**

```
 Index:0 Track:0 Setup done.
 Index:0 Track:0 Begin to spin motor
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Done spinning motor
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Stepping In
 Index:0 Track:0 Begin to spin motor
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Done spinning motor
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Stepping Out
 Index:0 Track:0 Begin to spin motor
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Spinning
 Index:0 Track:0 Done spinning motor
 Index:0 Track:0 beginning to wait for index pin to pulse

```

**UPDATE:** I am now receiving my expected results due to geometrikal's answer. While researching this problem I found a few code examples of Arduino to Floppy Drive. I noticed that they were setting their input pins to HIGH, but I never realized why they were doing this. After fixing my problem, I found this in some Arduino documentation (which made me realize the code examples I had were using an older version of the Arduino IDE):

"Prior to Arduino 1.0.1, it was possible to configure the internal pull-ups in the following manner:"

```
pinMode(pin, INPUT);           // set pin to input
digitalWrite(pin, HIGH);       // turn on pullup resistors`

```

In Arduino 1.0.1+ you can do it this way.

```
pinMode(pin, INPUT_PULLUP);

```

# Answer
> 11 votes
According to this (dead link):

http://bitsavers.trailing-edge.com/pdf/nec/FD1035\_Product\_Description\_Jul84.pdf

> *This is an archived copy of the FD1035 3.5" Floppy disk drive: Product Description July 1984 - PDF:*
>
> *https://archive.org/details/bitsavers\_necFD1035Pl84\_876629*

The outputs are open-collector, so a pull-up resistor is required. You can instead enable the Arduino internal pull-ups on those pins by

```
pinMode(indexPin, INPUT_PULLUP);
pinMode(track0Pin, INPUT_PULLUP);

```

# Answer
> 3 votes
You should replace `int` with `unsigned long` in all locations where you deal with time in milliseconds.

The point is that `millis()` returns an `unsigned long`, thus using `int` to store `millis()` value, you have a loss of information due to automatic cast performed by the compiler.

The changes you have to perform are:

```
unsigned long motorSpinTime = 1000UL; //in ms

```

and:

```
//spins the disk motor for a number of ms and prints the state
void spinMotorForThisManyMs(unsigned long msToSpin) {

  //start spinning
  digitalWrite(motorEnableBPin,LOW);

  //delay.. keep printing the state
  unsigned long maxTimeMs = millis() + msToSpin;
  while(millis() < maxTimeMs ) {
    printState("Spinning");
  }

  //stop spinning
  digitalWrite(motorEnableBPin,HIGH);
}

```

Note that I have also performed some optimization in the waiting loop by calculating the maximum time once and then compare `millis()` directly to that value. This is not mandatory but I just find it a bit more clean.

---
Tags: arduino-uno, hardware
---


title: Connecting a Arduino to FT232

text:
# Question
Title: Connecting a Arduino to FT232
I found this wonderful breakout board based on FT232. I wonder if I can use this board for connecting my arduino to a USB dongle for 3g/GPRS connection ?

From what I understand this board can be connected to the serial data pins of the arduino board. And if I connect the USB dongle to the FT232 board, I should be able to run AT commands from the arduino board.

# Answer
> 5 votes
Unfortunately, no, as the FT232 would have to act as a USB host device. A USB host shield might work if someone has written driver code to support 3G modems.

---
Tags: serial, gsm
---


# Question
Title: What electronics should I study to create something like a fridge temperature monitor?
I would like to be able to design an Arduino circuit for a fridge monitor that would have a temperature sensor, a small speaker to emit a sound when the temperature changes past a threshold and an LCD screen showing the current temperature.

I have found a few examples online, but I would like to know why components like capacitors and transistors are used in their circuits so I'd be able to design similar circuits myself.

I found this list of electronics topics:

* Basic Theory
* Basic Passive Components
* Passive Circuits
* Discrete Active Components
* Active Circuits
* Integrated Circuits
* Digital Logic
* Analog
* Signals
* Outputs
* Inputs
* Digital Electronics

Some of these things, like digital logic seem unnecessary in such a project, but obviously some others are useful, but I don't know which. I'd like to know what it would be useful to study so I can understand the reasons for the circuit design of something like a fridge monitor.

# Answer
A fridge temperature monitor (or any system that talks to world using some data) will include a sensor (temperature sensor like LM35), a controller (to do calculations, arduino ofcourse) and an output (display, like LCD). The topics you should be aware of, are digital electronics, basic passive components (working of resistor, capacitor etc). And a little arduino programming and lots of logic.
> 0 votes

---
Tags: electronics
---


# Question
Title: 'crash' when using pin change interrupts
I'm noticing a crash when testing out some interrupt code for a project I'm working on.

I've returned to the example provided with the library PciManager and I'm still experiencing the same issue. There doesn't appear to be any patten to when the crash appears, and on occasion I've been playing for several minutes and not seen a crash. NOTE I had to add a file (Task.h) from the developers other project (SoftTimer) to get it to compile.

here is the code:

```
#include <PciManager.h>
#include <PciListenerImp.h>

#define INPUT_PIN 3

PciListenerImp listener(INPUT_PIN, onPinChange);

int i = 0;

void setup() {
  Serial.begin(9600);
  PciManager.registerListener(INPUT_PIN, &listener);
  Serial.println("Ready.");

}

void onPinChange(byte changeKind) {
  i++;
  Serial.print("pci : ");
  Serial.print(i);
  Serial.print(" : ");
  Serial.println(changeKind);
}

void loop() { }

```

I have a wire connected to pin 3 and 3.3v which I'm pulling out and then connecting again. Some times when disconnected it continually interrupts, I was expecting this. Sometimes it doesn't which I found strange, the crash appears to happen more in the latter case.

Here is a trace from the serial monitor

```
Ready.
pci : 1 : 0
pci : 2 : 1
pci : 3 : 0
pci : 4 : 1
pci : 5 : 0
pci : 6 : 1
pci : 7 : 0
pci : 8 : 1
pci : 9 : 0
pci : 10 : 1
pci : 11 : 0
pci : 12 : 1
pci : 13 : 0
pci : 14 : 1
pci : 15 : 0
pci : 16 : 1
pci : 17 : 0
pci : 18 : 1
pci : 19 : 0
pci : 20 : 1
pci :

```

I've run this on a shrimp and on a freeduino diecimila compatible board both resulting in the same effect.

Anyway down to question; is the issue the way I'm interrupting? i.e. not stopping the floating pin? or is it a problem with the library, or is it a fundamental problem with pin change interrupts.

# Answer
Your `onPinChange()` function is called with interrupts disabled.

For you what it means is this function should:

* last **as short as possible** (because **NO** interrupts are handled during its execution, that includes timers that are used by several Arduino core libraries)
* not use `Serial` functions as these functions are slow and sometimes wait on interrupts (that could thus mean *wait forever*)

You can read further advice about these so-called *Interrupt Service Routines* (**ISR**) here and there.

If you want to trace all calls to `onPinChange()` then you will have to use some kind of circular buffer as a global `volatile` variable, which will be written into by `onPinChange()` and read from by `loop()`.

Accessing that buffer from `loop()` should be protected against concurrent write by ISR.

Here is sample code I have just written (disclaimer, I have not checked that it compiles but I think it should work correctly) that uses such a circular buffer as described above, and ensures all shared variables accesses are protected against concurrent write by ISR:

```
#include <PciManager.h>
#include <PciListenerImp.h>

// Structures and function to manage circular buffer of changes
struct Change {
    int i;
    byte kind;
};

// We allow max SIZE changes in the buffer; if onPinChange() is called more often
// than loop(), then at one time the buffer will be overwritten.
const int SIZE = 100;
volatile Change changes[SIZE];
volatile int start = 0;
volatile int end = 0;

// Get the next change recorded by onPinChange()
Change* nextChange() {
    static Change change;
    Change* result = 0;
    // Disable interrupts as we are accessing variables modified by onPinChange
    cli();
    if (start != end) {
        change = changes[start];
        start = (start + 1) % SIZE;
        result = &change;
    }
    // Re-enable interrupts before leaving the function
    sei();
    return result;
}

#define INPUT_PIN 3

PciListenerImp listener(INPUT_PIN, onPinChange);

// No change necessary in setup()
void setup() {
    Serial.begin(9600);
    PciManager.registerListener(INPUT_PIN, &listener);
    Serial.println(Ready.);
}

void loop() {
    // Get the next change recorded by onPinChange (if any)
    Change* change = nextChange();
    if (change != 0) {
        // One change occurred since last time, trace it to Serial
        Serial.print("pci : ");
        Serial.print(change->i);
        Serial.print(" : ");
        Serial.println(change->kind);
    }
}

void onPinChange(byte changeKind) {
    // i does not have to be visible outside this function
    static int i = 0;
    i++;
    // Write information to the end of the circular buffer
    Change& change = changes[end];
    change.i = i;
    change.kind = changeKind;
    // Prepare for the next call (write to the next item of the buffer)
    end = (end + 1) % SIZE;
}

```
> 5 votes

# Answer
I'm going to include this answer even though I think there's a very little chance that it is the problem because I just wasted ten hours on a project before finding it and it's an easy check so it won't take much time either way.

On AVR chips, if you have enabled interrupts and one occurs and you don't have an ISR for it, it will call the default ISR which resets the board. You can test if this is happening by redefining the default ISR by creating a function ISR(BADISR\_vect){}; I would put a serial print in there and run it again and see if it's happening. If you don't want to do serial (for obvious reasons) just toggle an LED.

I also agree it's probably a bad idea to be doing this on a floating pin. I'd use the internal pull-up resister to keep it high then connect a wire between that pin and ground to simulate a button.
> 5 votes

# Answer
Note that disconnecting a wire on an input pin is also not going to give you the results you expect. A disconnected input pin's value will float, and you'll get a semi-random mixture of 1s and 0s. You should either connect an external pull-up/pull-down resistor, or activate the internal pull-up resistor when you configure the pin (by setting the pin to INPUT\_PULLUP).

I prefer using INPUT\_PULLUP, since that saves wiring an external resistor. Use INPUT\_PULLUP, then wire the pin through a pushbutton switch to ground.

Then look for a high-to-low transition on the pin to signify a button press.
> 3 votes

---
Tags: interrupt
---


title: Nested For Loop

text:
# Question
Title: Nested For Loop
I'm not sure if I'm being really really stupid, but why doesn't this work?

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

void loop() {
  for (int x; x < 8; x++) {
    for (int y; y < 8; y++) {
      Serial.print(x);
      Serial.println(y);
      delay(100);
    }
  }
}

```

When this does:

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

void loop() {
  for (int x; x < 8; x++) {
    Serial.println(x);
    delay(100);
  }
}

```

The first produces no output over Serial, whereas the second one prints out the numbers 0 to 7 as expected. I'm using a Teensy 3.1.

# Answer
> 7 votes
You are not initializing x and y.

When a local variable isn't initialized, it will "inherit" the value contained in the register assigned to the variable by the compiler. The fact that your single loop example worked is pure luck - the assigned register happened to contain 0 at that point in execution.

Change your nested loop like this:

```
for (int x = 0; x < 8; x++) {
  for (int y = 0; y < 8; y++) {
    Serial.print(x);
    Serial.println(y);
    delay(100);
  }
}

```

And it will work.

Note: Global variables, on the other hand, are guaranteed by the c++ standard to be initialized to zero. The compiler will make sure to write zeros to those memory addresses before the main program code executes.

---
Tags: programming, teensy
---


# Question
Title: How to compile code for the Arduino Due?
I have set up Eclipse to compile for the Arduino Due using all the tools shipped with the Arduino IDE 1.5.6-r2. It compiles without errors, but when uploaded, the Arduino does nothing, and isn't recognized on the computer. It then has to be reset manually using the erase and reset buttons.

There is one static library (ArduinoDueCore) consisting of the Arduino library (`core`), and other code (Atmel found in `lib`). The other Eclipse project is the TestProject. It contains one file blinking an LED on pin 13. All the files from the Arduino library are there.

This is the output from Eclipse compiling the library itself: (excerpt of only one of each type of command)

```
18:31:36 **** Build of configuration Release for project ArduinoDueCore ****
make all
Building file: ../src/lib/variants/arduino_due_x/variant.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/variants/arduino_due_x/variant.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/lib/variants/arduino_due_x/variant.d" -MT"src/lib/variants/arduino_due_x/variant.d" -mcpu=cortex-m3 -mthumb -o "src/lib/variants/arduino_due_x/variant.o" "../src/lib/variants/arduino_due_x/variant.cpp"
Finished building: ../src/lib/variants/arduino_due_x/variant.cpp

Building file: ../src/lib/libsam/source/adc.c
Invoking: ARM Sourcery Linux GCC C Compiler
arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/libsam/source/adc.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/lib/libsam/source/adc.d" -MT"src/lib/libsam/source/adc.d" -mcpu=cortex-m3 -mthumb -o "src/lib/libsam/source/adc.o" "../src/lib/libsam/source/adc.c"
Finished building: ../src/lib/libsam/source/adc.c

Building file: ../src/core/USB/HID.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/USB/HID.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/core/USB/HID.d" -MT"src/core/USB/HID.d" -mcpu=cortex-m3 -mthumb -o "src/core/USB/HID.o" "../src/core/USB/HID.cpp"
Finished building: ../src/core/USB/HID.cpp

Building file: ../src/core/cortex_handlers.c
Invoking: ARM Sourcery Linux GCC C Compiler
arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/cortex_handlers.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/core/cortex_handlers.d" -MT"src/core/cortex_handlers.d" -mcpu=cortex-m3 -mthumb -o "src/core/cortex_handlers.o" "../src/core/cortex_handlers.c"
Finished building: ../src/core/cortex_handlers.c

18:31:39 Build Finished (took 2s.811ms)

```

Here is the project itself:

```
18:33:42 **** Build of configuration Release for project TestProject ****
make all
Building file: ../src/TestProject.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DARDUINO=156 -DUSB_PRODUCT="Arduino Due" -DARDUINO_SAM_DUE -D__SAM3X8E__ -DARDUINO_ARCH_SAM -Dprintf=iprintf -DF_CPU=84000000L -DUSB_MANUFACTURER="Unknown" -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/TestProject/src" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -Os -ffunction-sections -fdata-sections -Wall -fno-exceptions -fno-rtti -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -g -w -MMD -MP -MF"src/TestProject.d" -MT"src/TestProject.d" -mcpu=cortex-m3 -mthumb -o "src/TestProject.o" "../src/TestProject.cpp"
Finished building: ../src/TestProject.cpp

Building target: TestProject.elf
Invoking: ARM Sourcery Linux GCC C++ Linker
arm-none-eabi-g++ -T"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x/linker_scripts/gcc/flash.ld" -L"/home/kim/workspace_juno/ArduinoDueCore/Release" -Wl,-Map,TestProject.map -lm -lgcc  -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--gc-sections -mcpu=cortex-m3 -mthumb -o "TestProject.elf" -Wl,--start-group  ./src/TestProject.o   -lArduinoDueCore -Wl,--end-group
Finished building target: TestProject.elf

make --no-print-directory post-build
/home/kim/arduino-1.5.6-r2/hardware/tools/g++_arm_none_eabi/bin/arm-none-eabi-objcopy -O binary TestProject.elf TestProject.bin

Invoking: ARM Sourcery Linux GNU Create Listing
arm-none-eabi-objdump -h -S TestProject.elf > "TestProject.lst"
Finished building: TestProject.lst

Invoking: ARM Sourcery Linux GNU Print Size
arm-none-eabi-size  --format=berkeley TestProject.elf
   text    data     bss     dec     hex filename
  10396      24    1188   11608    2d58 TestProject.elf
Finished building: TestProject.siz

18:33:43 Build Finished (took 308ms)

```

Here is the upload command: (removed `readWord`, `go`, `write` and `writeWord` lines)

```
-i -d --port=ttyACM0 -U true -e -w -v -b ${project_loc}/Release/${project_name}.bin -R

Set binary mode
chipId=0x285e0a60
Connected at 921600 baud
Erase flash
Write 10420 bytes to flash

[                              ] 0% (0/41 pages)
[=======                       ] 24% (10/41 pages)
[==============                ] 48% (20/41 pages)
[=====================         ] 73% (30/41 pages)
[============================= ] 97% (40/41 pages)
[==============================] 100% (41/41 pages)
Verify 10420 bytes of flash

[                              ] 0% (0/41 pages)
[=======                       ] 24% (10/41 pages)
[==============                ] 48% (20/41 pages)
[=====================         ] 73% (30/41 pages)
[============================= ] 97% (40/41 pages)
[==============================] 100% (41/41 pages)
Verify successful
Set boot flash true
Device       : ATSAM3X8
Chip ID      : 285e0a60
version()=v1.1 Dec 15 2010 19:25:04
Version      : v1.1 Dec 15 2010 19:25:04
Address      : 524288
Pages        : 2048
Page Size    : 256 bytes
Total Size   : 512KB
Planes       : 2
Lock Regions : 32
Locked       : none
Security     : false
Boot Flash   : true
CPU reset.

```

TestProject.cpp:

```
#include "Arduino.h"

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

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

```

# Answer
Using 1.5.6-r2 with Eclipse cause the Due to hung in Default\_Handler function after entering main and polling a few times for the next SysTick gettin passed.

Some weak symbol declarations are done twice (i.e. the SysTick\_Handler function definitions). They appear to overwrite each others weak alias depending on the link time usage of the objects. All declarations (not only the failing SysTick\_Hanlder) from cortex\_handler.c are getting overwritten by weak symbol redeclaration inside startup\_sam3xa.c.

This commit seems to already address a weak symbol definition problem. https://github.com/arduino/Arduino/commit/65f00a69c74ca0def8d7f1d7597327945a04a33f

For now, to fix it. Just comment out the part in startup\_sam3xa.c with the weak symbol declaration regarding the vectors. Lines 53 to 129.

It should also work to just remove the file completely. The startup handler code and vector map should be provided by gcc arm built-in libraries instead.
> 2 votes

---
Tags: arduino-due, compile, eclipse
---


# Question
Title: Arduino: Hardware SPI hangs, bit-bang does not
I'm using FastLED with a custom board built around the ATMega32u4. When I set it to use Software SPI, everything works fine, but when I use hardware SPI it just hangs whenever it tries to write out the data (FastLED.show()).

I originally mocked this up on an Arduino Pro Micro and it worked fine there. That makes me think that it's a hardware issue but, as I mentioned, SPI output *does* work, but only when bit-banged. Which really doesn't make much sense.

I tested this by also just using the built in SPI classes and I get the same thing. No luck with hardware SPI.

Anyone else ever see something like this?

The schematic of my circuit is below.

# Answer
According to ATmega32u4 datasheet, section 17.2.1 (SPI / SS Pin Functionality / Master Mode:

> **If SS is configured as an input, it must be held high to ensure Master SPI operation.**

In your circuit, SS pin (#8 on package), also labeled as "**(SS/PCINT0) PB0**", is left unconnected.

Is it possible that PB0 is also configured as input somewhere in your program or libraries? In this case, it should be connected to Vcc.
> 5 votes

---
Tags: spi, atmega32u4
---


# Question
Title: How to process this XBee analog pins signal?
I'm new to XBee and a colleague setup a sender/receiver pair. I'm using an usb breakout and reading the values using this java XBee API in Processing/Java.

The issue I'm having is two of the pins(analog 3 and 4) seem to have a strange alternating pattern and this makes it harder to read the values. Here's what I mean:

a recording of the plot I'm drawing of the values:

and here are some values. I noticed there were duplicate entries, so I removed those:

```
654,28
65,28
65,366
52,366
52,263
607,263
607,23
45,23
45,554
164,554
164,138
393,138
393,14
33,14
33,677
432,677
432,64
77,64
24,237
24,345
659,345
659,29
61,29
74,378
74,226
455,226
455,16
42,16
42,592
225,592
225,107
348,107
348,13
27,13
27,700
515,700
515,56
60,56
60,392
372,392
372,70
98,70
98,141
12,141
12,456
663,456
663,30
64,30
74,349
74,224
554,224
554,20
41,20
41,600
256,600
256,96
127,96
127,87
13,87
13,502
659,502
659,37
75,37
75,251
20,251
20,364
631,364
631,25
55,25
55,436
128,436
128,165
447,165
447,16
38,16
38,618
224,618
224,107
251,14
25,14
25,700
535,700
535,54
67,54
69,323
69,235
568,235
568,21
49,21
49,503
182,503
330,128
330,12
13,12
13,498
665,498
665,35
76,35
76,247
47,247
47,277
313,277
313,12
22,12
22,691
513,691
513,56
157,56
157,53
18,53
18,640
169,640
103,48
103,105
12,105
12,389
209,389
209,30
65,30
65,353
19,353
19,282
200,282
200,18
21,18
21,681
152,681
152,54
123,54
123,47
14,47
14,526
654,526
654,37
74,37
74,260
17,260
17,387
655,387
655,29
61,29
61,375
74,375
74,249
512,249
512,18
32,18
32,678
255,678
255,92
270,92
270,11
25,11
25,319
557,319
557,53
61,53
61,165
115,165
115,133
195,133
195,18
20,18
20,317
594,317
594,48
126,48
126,41
14,41
14,281
653,281
653,40
80,40
80,96
35,96
35,189
623,189
623,25
55,25
55,191
139,191
139,123
468,123
468,16
31,16
31,306
622,306
622,45
82,45
82,90
24,90
24,345
207,345
207,32
66,32
66,347
22,347
22,247
201,247
201,18
41,18
41,616
82,616
82,82
93,82
93,147
12,147
12,472
206,472
206,33
73,33
73,287
18,287
18,274
204,274
204,19
49,19
49,526
64,526
64,103
182,103
182,14
27,14
27,701
457,701
457,61
225,61
225,19
19,19
19,654
592,654
592,48
105,48
105,125

```

Looking at the pattern I noticed the higher values occur every 3rd value but also the values seem to oscillate like on a sine wave. If I read only the 3rd value of each sensor that seems remove the 'gaps', but the sine wave pattern is still visible. When I physically get the two pots connected to analog pins 3 and 4 (index 2 and 3 in my plot) I can notice the maximum value either increases or decreases, but the sine pattern is still there.

I've also started going though the XBee manual and found this:

> Analog samples are returned as 10-bit values. The analog reading is scaled such that 0x0000 represents 0V, and 0x3FF = 1.2V. (The analog inputs on the module cannot read more than 1.2V.) Analog samples are returned in order starting with AIN0 and finishing with AIN3, and the supply voltage. Only enabled analog input channels return data as shown in the figure below. To convert the A/D reading to mV, do the following: AD(mV) = (A/D reading * 1200mV) / 1023

Unfortunately I'm not very experienced with electronics, but it looks like a linear mapping to me and I haven't found anything else pointing to this oscillation.

My naive approach would be to work out the period or this sine wave and see how much the amplitude changes when I physically turn the pots versus the 'default' position.

I've also started looking at signal processing and thought that potentially I could use a 'wavelet' to detect a pattern and then see difference between the expected one and the current signal, but that sounds a bit overkill.

Is my naive approach decent ? What's the simplest way to read values from a signal like this ?

# Answer
> 2 votes
Sounds like your pots are not connected correctly and you pick up noise. The waveform you are seeing could be from the mains, or another source. Stray magnetic fields from transformers etc. can couple and be picked up by your circuit and you will notice them if your input is of high impedance. The atmosphere is also full of electromagnetic radiation from human sources and from space, that you can also pick up. The longer wires that are connected to your high impedance input, the more noise you will pick up.

Your pots should be wired 1.2V-AIN-GND, with the 1.2V source being low impedance, coming from a power supply/regulator and not eg. a voltage divider. If your potentiometer is high impedance (say 100 kOhm), and it is connected with wires from eg. a breadboard, you might want to add a decoupling capacitor between AIN and GND. 0.1 uF would be a typical value. It will short out AC waveforms(noise) to ground.

# Answer
> 1 votes
Sounds familiar .

First i will test whether i am reading something or just picking up random noise due to poor connection or error in coding (data conversion arithmetic etc).

Connect 1 pin to ground and another to 1.2V.

You should read 1024 and 0 on e 2 pins . If not check circuit and code.

Anyway

```
Vadc = (ADC/1024) * Vref

```

Did you connect Vref ?

---
Tags: serial, xbee, signal-processing
---


title: LM386 module not working

text:
# Question
Title: LM386 module not working
I have arduino UNO hooked up with wtv020-sd-16p and it works fine, playing audio files - speaker is connected right to the WTV020's pin #4 and #5. However, volume is rather low. So I have ordered LM386 amplifier module. I have wired it's IN pin with WTV020's pin #2 AUDIO-L. But no sound comes out of speaker. I can hear only some scratches from the speaker while arduino is running.

LM386 is pretty easy, only VCC, IN and GND pins, so there is nothing much to screw up. I am wondering, what could be the problem ?

Thanks for any help or hints in advance.

EDIT: Only to note, when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis ?

# Answer
> 3 votes
> when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis

Indeed - what you are describing sounds like the DC component of the Arduino's output is outside the workable range of the amplifier, effectively cutting it off. When there is no output, the voltage is within range and little bits of noise are able to be amplified.

You should be able to fix the cutoff problem with a series capacitor to block the DC component of the input, allowing only the AC signal through - a common technique for coupling between stages in Audio and RF systems.

The value of the capacitor will depend on the impedance of the circuit it is driving. A bare input to many chips could use a quite small value, while a circuit with feedback or a voltage-divider volume control might require a larger or carefully chosen one.

---
Tags: arduino-uno
---


# Question
Title: Sensors and leds. This need resistors? and how?
I have a project with leds and sensors, this is my first project in Arduino and I want to know if it need resistors and how and where?

I use 16-Bit I/O Expander MCP23017 for leds and multiplexer CD4051 for sensors LM35

# Answer
> 3 votes
You will definitely need resistors for each LED connected to MCP23017 circuits.

This is necessary because without resistor the following is likely to happen:

* burn each LED that is lit on as it would be fed too much current
* burn the MCP23017 because it is rated for 125mA maximum (20mA per output pin)

The resistor to use normally depends on the color of each LED as those LEDs have different electrical charasteristics.

Typically one LED (3 or 5mm) needs no more than 20mA to be lit (lower current such as 10mA is generally provides enough light).

One other important LED characteristic is its **forward voltage**, which depends on the color.

This link will help you calculate the "ideal" resistor for each LED.

For the sensors part, I see no reason to use any resistor to connect them to 4051 circuits.

One last important point is related to the use of **I2C** bus by the MCP23017 circuits. I2C bus is "open drain" and thus requires pullup resistors for both **SCL** and **SDA** lines.

---
Tags: sensors, led, resistor
---


# Question
Title: Serial.write displaying repeating output from Xbee communication
I want to use xbee's to communicate between two different arduinos. I'm using this tutorial as a guide to setup my xbee's. I've already used XCTU to setup one xbee as a router and another as a coordinator (both in ZIGBEE AT mode). I used XCTU's terminal feature to verify that info was being sent and received properly.

Basically, I have both arduinos connected to the same PC via USB cables, but the communication is taking place through the Xbee's. I also made sure to disconnect the TX & RX wires when uploading the sketches to avoid an AVRDUDE error.

I wanted to test the communication by sending a "hello world" message once every five seconds, from the router to the coordinator. To do this, I wrote the following code:

```
//Code for Arduino attached to Xbee in Router AT mode
void setup(){
 Serial.begin(9600);
}

void loop(){
  Serial.println("Hello World!");
  delay(5000);
}

```

and

```
//Code for Arduino attached to Xbee in Coordinator AT mode
void setup(){
  Serial.begin(9600);
}

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

```

I checked the serial monitor for the arduino connected to the router, and it does exactly what I expected to see: a new Hello World message once every 5 seconds. However, the serial monitor on the arduino connected to the coordinator does not produce the desired effect: ***the "hello world" message instantly displays the message over a hundred times per second and repeats without end, each time on a separate, new line***. Sometimes, when I turn the serial monitor on, the message instantly appears with a few repetitions before displaying some strange characters and stopping altogether.

I'm not sure if the problem is with the serial monitor or with the xbee. Any help with this problem would be greatly appreciated.

# Answer
Code is correct and it does what it is asked to. The receiver code reads the RX pin of arduino which is connected to the Xbee. The same pin is used by the FT232 interface IC to send data to your computer through USB.

The "hello world" you send is received by the Xbee and is send to microcontroller and FT232 at same time as that pin is shared between them. Thus the "hello world" will be seen in serial monitor, first time from Xbee and second time, from `Serial.write(Serial.read())` of the program.

Also check whether the settings are correct from this tutorial, as Xbee will not be configured as P2P.
> 1 votes

---
Tags: xbee
---


# Question
Title: Reading a 10 pin 7 segment (2 digits) sing Arduino 1. Please Help!
thanks for taking the time to read this, I really appreciate it. I am very new to Arduino and the Micro controller world so please forgive my ignorance.

So I have an old 7 segment display that displays outside temperature, what i want to do is read the temp into the Arduino and light up an LED if the temperature gets high, and a different color if the temp gets low.

I know i can use a thermometer and plug it into the Arduino and go from there, but that would be cheating. So my question is, can i read each pin of the 7 segment display and translate that into a number into the Arduino?

please see pictures.

Any help would be very very appreciated!!

Thanks again for reading.

This last picture shows "21" using the code and set up on the above link. I want to jump another Arduino into the breadboard and read "21" or any other temperature (depends on outside thermometer) into the serial monitor. Now the challenging part is the code, Im not really good at coding but i understand if this had 1 pin for each LED i would just read each one and translate it into the serial monitor. However this only has 10 pins therefore represents a challenge.

Any input is greatly appreciated, I dont even know how to start.

# Answer
> 3 votes
Your display is multiplexed, so you will need to monitor not only the segment lines but also the digit lines.

First figure out if your display is "common anode" or "common cathode" as the logic in one case will be inverted from that of the other.

For your test case, you can write the driving and reading arduinos to the display in the same way, but configure all the connected pins on the reading one as inputs.

The tricky part is going to be detecting when the segment select has changed, but you could do it by storing the current value of each select pin, and then reading the new value. If you see that the old value was inactive and the new value active, then wait a tiny amount of time and read all of the segment lines. You want to wait long enough to make sure that the data lines have been driven to match, but no so long that you get the data for the next digit instead. If you have access to a scope, you can find the best value, but you could also experiment by making the delay short until you get wrong data, making it long until you get wrong data, and then picking an intermediate value.

You may find it easiest to read all 7 or 8 segment lines into a single byte value, and then compare it to each element in the lookup table you used in the driver code until you find a match.

If you don't know the exact wiring of the segments on the unknown target board, consider printing the bytes to the serial monitor as you cause the displayed values to change (cup of ice water, cup of hot water...) and taking notes of the segment values vs. the digits you see display. It will be a puzzle, but one you should be able to figure out.

# Answer
> 1 votes
First of all, make sure that the voltage is below 5V (but above 2.5V so it can register as HIGH on a digital pin). If not, it will either fry your Arduino or won't work.

As for the code, you can do one of the two following things:

* Use a library like **PinChangeInt** to help you detect when and what changed.
* Store the data and check every so often.

Chris Stratton had a good idea with the byte and compare it. To do this, you would do something like this:

```
byte data = 0;
if(digitalRead(10) == HIGH) {
  data |= B00000001;
}
if(digitalRead(11) == HIGH) {
  data |= B00000010;
}
if(digitalRead(12) == HIGH) {
  data |= B00000100;
}
//...

```

Basically, this is *bit-wise math* that sets one bit of your byte to a 1. If it is a 0, then you leave it alone (all bits default to 0 because of how I declared `data`).

If pins 10 and 12 were HIGH, the byte would look like this in binary:

```
00000101

```

# Answer
> 1 votes
so I realized that the 2 pins that are driving this toggle at 4kHz, when one is on the other is off, but there is a 6usec time when both pins are on. So what im trying to do now is adding "if right bit is == 1, if A=1 b=0 c=1 d=1... and so on" then number = 6 then scan for it. Im not sure how to use that library.

```
void loop() {
// read the input pin:
//int buttonState = digitalRead(pushButton);
int State_A = digitalRead(A);
int State_B = digitalRead(B);
int State_C = digitalRead(c);
int State_D = digitalRead(D);
int State_E = digitalRead(E);
int State_F = digitalRead(F);
int State_G = digitalRead(G);
int State_DP = digitalRead(DP);
int State_RIGHT = digitalRead(RIGHT);
int State_LEFT = digitalRead(LEFT);

if (State_LEFT==1)
{
 if(State_A==0 & State_B==1 & State_C==0 & State_D==0 & State_E==0 & State_F==0 & State_G==0)
{
number=6;
Serial.println(number);
// Serial.print(State_LEFT);
}

```

i plan to add that for every digit. is there any easier way to do that?

# Answer
> 0 votes
What you are trying to do is tricky and awkward, and probably not worth the trouble.

It's also above your current skill level, both in hardware and software.

As the other poster has said, the display is likely multiplexed. If so, it sends a value to 1 digit, then to the next, and alternates them quickly. Only one digit at a time is actually lit.

It's also possible that the digits are latched. The processor sends a value to one digit at a time and that digit's circuitry remembers the value until it changes again. However that's less likely because it's more complex and expensive to do

To decode a multiplexed display you'll need to figure out how the multiplexing is done. There are lots of different ways it could be done.

You say it's common anode. It might have the anodes of a digit wired together, and have them both connected to the controller. The anode that's currently being displayed would be connected to +5, and the cathodes of like segments from each digit would be wired together in parallel. To drive a digit, the control circuitry would connect the anode of that digit to the positive supply, and connect the segments to be displayed to ground. All other connections would be left floating. Then it would disconnect the anode of the first digit and connect the anode of the other digit to the positive supply.

The display may also have a logic level that determines which segment is being driven. For a 2 digit display all you'd need is one line, and a HIGH would drive 1 digit and a LOW would drive the other digit.

A logic analyzer would help you sort this out, but you need to know how to use it.

You might also try researching the thermometer you're using and see if you can find a schematic for it, in the documentation, the manufacturer website, or in a patent

Once you figure out how to read the segment values from each digit, you will need a truth table that maps segment values to numbers, and will need to do a lookup. That is intermediate level C programming.

---
Tags: c++, led, display, analogread, temperature-sensor
---


# Question
Title: Arduino LED backlight - should PWM be used with transistor or capacitor?
I have implemented a PWM controlled LED backlight for the LCD in my Arduino Uno design. One LCD backlight pin is connected to +5V, the second to the ground via 220 Ohm resistor and MOSFET controlled from a PWM capable D9 pin.

Everything seems to work fine, I do not see any oscillation, but after some reading about PWM I am not sure if I perhaps should connect a 100 uF capacitor to smooth the voltage?

Is the MOSFET even necessary? It seems backlight is drawing about 5 mA - can I perhaps drive it directly from the D9 pin, using the resistor? (It seems another user in Do I need to use a resistor if I am using a potentiometer to control an LED's brightness? is controlling brightness without any of those.)

# Answer
**You don't need the MOSFET, you don't need the capacitor, you *do* need the resistor.**

The pins on your Arduino can deliver up to 20mA comfortably, so in this case there is no need for the MOSFET. However, if you were to replace your backlight with a high power LED, your current setup will work just fine.

Without a capacitor, your PWM is a nice square wave. The cap will, depending on its capacity and the resistor in your circuit, turn that into a more rounded waveform, or very ripply DC. Whichever is the case, it will not benefit the (dimming of) your LED. With some bad luck it will even introduce flickering instead of preventing it!

The reason why you should still use the resistor is to prevent the LED from drawing too much current. Without it, it's simply a game between the LED and the Arduino pin to see who will burn first. Whoever wins, you'll end up with a destroyed backlight or fried Arduino. Adding a component costing a few cents can prevent that.
> 6 votes

---
Tags: lcd, pwm
---


# Question
Title: Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini?
I have seen several references where the solution to interfacing a 5V Arduino with a 3.3V nRF24L01+ was to power the nRF24L01+ externally.

How do I do this? The ground of the nRF24L01+ is connected to the Arduino; can I simply attach 3.3V power between the power and ground pins of the nRF24L01+?

# Answer
> 4 votes
To connect the nRF24L01+ to a 5V Pro Mini you will need external 3.3V power supply to power the nRF24L01+. The ground for the Pro Mini and the ground for the nRF24L01+ should be tied together to ensure a common ground reference.

The inputs to the nRF24L01+ are 5V tolerant so you will not need a level shifter to convert the 5V Digital IO on the Pro Mini to 3.3V. Be aware the not all 3.3V devices have 5V tolerant inputs like nRF24L01+.

You might want to look into using a 3.3V Pro Mini with that you should be able to use the regulated 3.3V power on the Pro Mini to power the nRF24L01+. Be aware that the 3.3V Pro Mini only runs at 8MHz instead of 16MHz.

# Answer
> 1 votes
Yes, You can. In any communication system, each module should have the same reference point of operation, or else the line is said to float. Here it is GND of arduino mini and GND of nRF24L01+.

# Answer
> -1 votes
you can download the references from this link: https://s3-ap-northeast-1.amazonaws.com/sain-amzn/20/20-019-102/NRF24L01.rar Hope the information may be helpful. Cheers!

---
Tags: power, arduino-pro-mini
---


# Question
Title: Wrong data from DS18B20 temperature sensor after long power off
I have my Arduino Uno connected to the PC via USB when prototyping. I am developing a thermometer with memory, using DS18B20 sensors.

When PC is shut down, there is no power on the USB and the Arduino is off. Sometimes, when my PC is turned off for several hours and then, when I turn it on, the Arduino is started, but it behaves "strange" - the program is showing buggy values on the display, looking like if there is some bug in the sketch. However, when I upload the sketch again, it works fine.

The buggy values are the averages for the run, computed simply by summing a float and dividing by int. What I see is e.g. instead of seeing something around 23.5 I see 85.1. The current values read from the sensor look OK (show 23.5 as expected), but I cannot tell for sure if perhaps some value read early might be wrong.

It is not easy to reproduce, I see it only sometimes, always when powering Arduino on after several hours without power.

My first idea is either the sketch got corrupted during the long power down, or variables are initialized wrong, and the sample sum / sample count is not zero.

However I though the sketches are uploaded into the Flash RAM, which should be non-volatile according to the docs. Is there something obvious I am missing, some explanation why is the sketch working differently after long power down?

# Answer
> 3 votes
There should be no difference between turning on your computer and plugging in a USB cable. The embedded devices typically plugged into a USB ports such as mice, keyboards, wireless adapters, hard drives, etc don't have their FLASH memory corrupted when the computer is turned on so it is unlikely that your Arduino would.

To confirm there isn't something dodgy going on with the USB power supplied to the board, use a multimeter to monitor the 5V pin of the Arduino. If the voltage isn't going too high or too low then everything should be fine. Even if it goes too low, the microcontroller will have brown-out-detect enabled to shut it down in this event.

You mentioned a display. Perhaps, and this is pure speculation, some how the display is being initialised wrongly due to the Arduino being reset by USB connection. If the display has a general reset command, or a reset pin, enable it at the start of your sketch to ensure the display is in its default state.

# Answer
> 4 votes
I researched this once when I was getting consistent, exactly 85 degC readings from my sensors. The Maxim DS18b20 data sheet (rev 042208, page 4, in a footnote to Table 1) says:

> "The power-on reset value of the temperature register is +85°C.

Double check that the Arduino code is follows the sensor communication protocol correctly.

# Answer
> 0 votes
The number you are seeing instead - 85.1, is suspiciously close to a Farenheit reading instead of Celcius - my guess is that there maybe a setup step for the Dallas DB18B20 that you are issuing too early for it, before it has initialised, and so it is ignoring it.

My guess would be steps being a unit setting, and a calibration setting.

can you attempt to wait a little time (perhaps 100 millis) before initialising the temperature control library.

---
Tags: sensors, power, sketch, flash, temperature-sensor
---


title: Arduino serial port programming

text:
# Question
Title: Arduino serial port programming
I bought an Arduino-on-breadboard kit. I have several PCs with serial ports, and now I'm being told I need a USB-to-serial converter. I thought I was ready to start uploading sketches, so how can I do this?

I'm able to understand serial communications and am capable of wiring a MAX232 chip into a breaduino if necessary, but I'm not sure it will work, so to save some time I'm asking, mostly because I was unable to figure it out with Google searches alone.

PS: I also have a stk500, but then I would be out of the easiness of using Arduino sketches and the programming language. I need the fastest route to prototyping/testing my sketches.

# Answer
An RS232 port wired via a level converter (as you mentioned max232) and a 1uF capacitor between RTS and "Arduino reset pin" Getting started with Arduino.

The capacitor is to trigger a reset on the Arduino so the bootloader kicks in and awaits a "Arduino sketch" via the serial port.

Your setup is AKA "Arduino Bare bone".
> 1 votes

# Answer
If your PCs have real RS-232 serial ports (rare these days), you can use those directly. Otherwise, you will need a USB\<-\>RS-232 serial adaptor cable.

**Correction:** I thought my Arduino did have an RS-232 port, but I was thinking of another board. If your board only has a TTL-level serial port (ie. direct from the ATMega328), then you need either an RS-232 level translator, or a USB\<-\>TTL serial cable. A suitable cable is available from Adafruit (and no doubt, others).
> 0 votes

---
Tags: serial, programming
---


# Question
Title: How to send numbers to Arduino UNO via Python 3 and the module serial
I am new to Arduino (and computer programming in general), so I apologize if this question looks silly.

Once I set up a basic arduino-LED connection, I have problems sending INTEGERS to arduino through the serial port. I can easily send characters such as 'm', 'o' and so on.. However if I send a number it looks like it simply does not get it.

Here is the Arduino code, ideally it should get a value from the usb port through python or the serial monitor and then adjust the brightness of the LED according to the value. (value must be in range \[0,255\]).

NOTE: I am using ARDUINO UNO and PYTHON 3

//--------------------------

```
int LED = 10;
int number;

void setup(){

pinMode(LED,OUTPUT);
Serial.begin(9600);
}

void loop(){

number = Serial.read();
Serial.print(number);
Serial.print('\n');
if(number == -1){
number = 0;
}

else if(number > 255){

number = 255;

}

else if(number < 0){

number = 0;
}

analogWrite(LED,number);
delay(1000);
}

```

However, when I input a value into the Serial port or through Python, for instance 0, it gives me 48 as answer (which, interestingly, is the ASCII code for 0!) and lights up the LED which is not what should happen since at 0 the LED should be off!! I am missing something but I cannot find what... Could you please tell me what is wrong?

Here is the code I use in Python:

```
import serial
import time
try:
    arduino = serial.Serial(port,speed)
    time.sleep(2)
    print("Connection to " + port + " established succesfully!\n")
except Exception as e:
    print(e)

#Note: for characters such as 'a' I set data = b'a' to convert the data in bytes
#However the same thing does not work with numbers...
data = 0
data = arduino.write(valueToWrite)
time.sleep(2)
arduino.close()

```

what am I doing wrong or misunderstanding? Thank you.

# Answer
> 6 votes
Parsing on the Arduino can be slow and time-consuming (which is bad if you use clock prescaling or have time-critical tasks), so let's do it in Python.

The problem is that you're sending the numbers as ASCII whereas you need to be sending them as raw binary. This is where `struct` comes in.

```
3>> import struct
3>> print(struct.pack('>B', 0))
b'\x00'
3>> print(struct.pack('>B', 255))
b'\xff'
3>> print(struct.pack('>2B', 255, 0))
b'\xff\x00'
3>> print(struct.pack('>H', 9000))
b'#('

```

So what you really want is:

```
data = arduino.write(struct.pack('>B', valueToWrite))

```

or something to that effect.

# Answer
> 1 votes
`Serial.read()` reads only **ONE** character from the serial port and returns its ASCII value, which explains the `48` you got.

To read a complete number, you have 2 options:

1. Use `Serial.parseInt()` that reads as many characters as needed and performs the conversion before returning the read number as an `int`. Please further check the reference here.
2. You read eachn character in a loop (with `Serial.read()`) until the last one, put each read charcater into a buffer (`char` array) then convert the resulting string to a number with the standard C function `atoi`.

Of course, the first option is the easiest one but it will return `0` if nothing is read after a 1s timeout (configurable with `Serial.setTimeout()`).

---
Tags: arduino-uno, python
---


title: How to use readLine from JSSC

text:
# Question
Title: How to use readLine from JSSC
When I use JSSC and call `serialPort.readLine(event.getEventValue())` from `public void serialEvent(SerialPortEvent event)` I've got fragments, not all string. What I must do to get all string from begin to `"\r\n"`? What I must do to get all string from my start marker (like `"[start]"`) to my stop marker (like `"[stop]"`)? What to modify in this code:

```
private static class PortReader implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR() && event.getEventValue() > 0){
            try {
                String data = serialPort.readString(event.getEventValue());
                serialPort.writeByte((byte) 1);
            }
            catch (SerialPortException ex) {
                System.out.println(ex);
            }
        }
    }
}

```

# Answer
The event gets fired when a single character is received, not the whole string. You have to build the string up until you get to `\r\n` and then process it. This is my code for a similar project. It uses a protocol where `>` signifies the start of a message and `\r` signifies the end. `processMessage` is a function to process the entire message and update GUI elements etc. It is invoked using `runLater` because the serialEvent function will be on a different thread to the GUI thread.

```
StringBuilder message = new StringBuilder();
Boolean receivingMessage = false;
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                if (b == '>') {
                    receivingMessage = true;
                    message.setLength(0);
                }
                else if (receivingMessage == true) {
                    if (b == '\r') {
                        receivingMessage = false;
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                    }
                    else {
                        message.append((char)b);
                    }
                }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

```

A simpler version for you might be the following. `processMessage` is called whenever a `\r` or `\n` is received and there are some bytes in the message.

```
StringBuilder message = new StringBuilder();
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                    if ( (b == '\r' || b == '\n') && message.length() > 0) {
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                        message.setLength(0);
                    }
                    else {
                        message.append((char)b);
                    }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

```

**Edit:**

Two things fixed: 1. Using `StringBuilder` instead of `String` to save making a lot objects every time the message is incremented. 2. Make a copy of the message string before passing to `runLater` otherwise when it does run it will use the up to date version of the string, which could have new characters, and thus cause problems.

**Edt 2:** On Windows I found it needed `if(event.isRXCHAR() && event.getEventValue() > 0)` as the event would sometimes be fired with 0 bytes causing a null point exception in `for (byte b: buffer)`
> 3 votes

---
Tags: serial, programming
---


title: Strange values from LSM303 Magnetometer

text:
# Question
Title: Strange values from LSM303 Magnetometer
I am having problems with values i get from Pololu MinIMU-9 boards's magnetometer. I am using Arduino-micro and the arduino library from Pololu. The sensor on the board is 3 axis accelero- and magnetometer LSM303. The problem is - the highest value always seems to be in vertical axis, not horisontal, as i would expect.

For example, here is the data i got when i put sensor flat on the table and made 360 clockwise turn in horizontal plane: (values are X Y Z)

```
-6 102 -516
-11 103 -515
-11 103 -515
-21 102 -514
-31 109 -515
-40 114 -512
-57 116 -509
-57 116 -509
-77 111 -507
-93 109 -506
-104 106 -507
-104 106 -507
-114 99 -508
-126 88 -504
-131 74 -507
-142 52 -507
-142 52 -507
-151 31 -506
-150 4 -509
-147 -27 -513
-147 -27 -513
-133 -60 -513
-119 -80 -519
-112 -87 -517
-102 -97 -521
-102 -97 -521
-89 -101 -522
-77 -101 -524
-50 -104 -527
-50 -104 -527
-43 -105 -529
-14 -98 -532
2 -92 -535
23 -92 -535
23 -92 -535
36 -81 -534
66 -54 -534
76 -32 -531
76 -32 -531
76 -21 -532
78 -7 -531
85 10 -528
91 39 -524
91 39 -524
94 50 -524
91 63 -524
76 75 -525
76 75 -525
63 82 -526
47 93 -525
44 98 -522
44 98 -522
38 104 -521
26 110 -521
26 112 -518
21 116 -519
21 116 -519
18 116 -518
12 120 -517
11 120 -515
11 120 -515
8 120 -517
5 122 -515
-5 123 -514

```

Turning the sensor "upside down" and then rotating it in horisontal plane again gives similar results, only Z axis has positive 500+ value.

Shouldn't the magnetometer always point in the direction of the magnetic field - in X or Y direction? I have tried this in different rooms and buildings and got the same results. Rotating the sensor on other axes yields the same results - vertical axis has the largest (and constant) value.

For reference, here is the code i used to get the values.

```
#include <Wire.h>
#include <LSM303.h>
LSM303 compass;

void setup()
{
  Serial.begin(115200);
  Wire.begin();
  compass.init();
  compass.enableDefault();
}

void loop(){
  compass.readMag();
  Serial.print(compass.m.x);
  Serial.print(" ");
  Serial.print(compass.m.y);
  Serial.print(" ");
  Serial.print(compass.m.z);
  Serial.print("\n");
  delay(100);
}

```

# Answer
> 5 votes
The earth's magnetic field is not parallel with the ground. In some locations it can be pointing more down than across.

NOAA has a magnetic field calculator where you can enter you latitude and longitude. For example, I am located at approx 19deg S 147degE and the field is

```
North Comp    East Comp    Vertical Comp    Total magnitude
32,434.4 nT   4,280.6 nT   -36,035.1 nT     48,670.7 nT

```

So the downwards strength is more than the other two combined for my location. I'm guessing the calculator will also show a very strong down component for your location.

Some other things to be aware of are that the LSM303DLHC magnetometer can have quite large offsets, up to the equivalent of 2 earth magnetic fields, and therefore requires calibration. Also hard and soft iron distortions can affect the readings.

Edit: Please see my answer here for methods to calibrate the sensor.

---
Tags: sensors, arduino-pro-micro
---


# Question
Title: Issues programming Arduino Uno with Sparkfun's MAX3232 breakout board
I'm having an issue programming the Arduino Uno with Sparkfun's MAX3232 breakout board attached. Sometimes the Arduino IDE won't see the Uno plugged in. I'm thinking of connecting a switch to the GND or the 3V - 5.5V pin so I don't have to disconnect the breakout board when programming. Are there any better solutions?

Sparkfun link: https://www.sparkfun.com/products/11189

# Answer
Switching the power off to the MAX3232 appears to be okay.
There are no components connected to the Rx and Tx lines on the breakout board to complicate it.

Unfortunately the break out does not give access to pin 1, EN which is "Enable Control", or pin 18 SHDN "Shutdown Control". AFAICT they could have been used to turn off the receiver and transmitters of the MAX3232. That would have been ideal. Maybe contact Sparkfun and suggest the improvement to put them on pads for folks to use, and offer to beta test it :-)

The datasheet for the MAX3232 says that it is able to withstand a continuous short on the Tx line, so it sounds pretty tolerant to minor abuse. Also, the diagrams dont show any pull-ups on the MOS/TTL Tx line. So I would expect it t be okay if you shut the power off, but continued to wiggle the Tx Rx pins.

An alternative would be to disconnect the Tx pin from the Arduino, so that the MAX3232 wouldn't interfere with the host PC's USB comms. It sounds like the thing on the RS232 connection will ignore data it receive while the Arduino is being programmed. If that is not true, then it would need to be disconnected too.

At the moment, switching off power looks like a reasonable approach. Disconnecting Tx and Rx also looks reasonable, and slightly better than powering the MAX3232 off.

Do you know how you want to do that?

NB: The MAX232 datasheet shows that part should not be driven by a high when the chip is unpowered. However the MAX3232 datasheet does not carry that warning. My preference would be to use the MAX3232 signals 'EN' and 'SHDN'. However those are not available on the breakout. I'd recommend having the part powered, and disconnecting Tx and Rx from the Arduino.
> 1 votes

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


title: Release power to stepper motor

text:
# Question
Title: Release power to stepper motor
I'm driving a large stepper motor via a GeckoBoard G213V and arduino UNO and I have that mostly working fine. However, I'd like to 'release' the stepper so it can swing freely.

There's two reasons I want to do this:

1) (Most important) I want the rotated object to naturally swing back to the 0 position thanks to gravity. 2) The motor gets hot - I'd rather not juice it when it should just be sat at 0.

Anybody know how I can do this? I'm using the AccelStepper library so a solution compatible with that would be ideal.

# Answer
> 2 votes
From the documentation:

> **TERMINAL 7 Disable**
> This terminal will force the winding currents to zero when tied to the step and direction controller +5V.
>
> The DISABLE input on the G213V is optically isolated and requires logic “1” to DISABLE and logic “0” to ENABLE the drive. Once it is disabled, the motor windings are unergenized\[sic\] and ***the motor freewheels.*** *(emphasis mine)*

So, feed the disable input a high.

---
Tags: arduino-uno
---


title: Is TM4C123 similar to Arduino?

text:
# Question
Title: Is TM4C123 similar to Arduino?
I'm currently studying embedded systems on eDx. https://courses.edx.org/courses/UTAustinX/UT.6.01x/1T2014/info (must login to see) http://users.ece.utexas.edu/~valvano/edX/index.html (don't need to login) and I found out that TM4C123 is quite similar to Arduino. but I haven't worked TM4C123 yet.(I ordered it and I'm waiting for it) I don't know much about it. and it's not that popular as Arduino I guess. so If anyone has used Tm4C123, please give me some information compared to Arduino.

# Answer
> 3 votes
The Tiva C LaunchPad is comparable to the Arduino Due in power and capabilities, but is incompatible with the stock Arduino ecosystem. It uses "BoosterPacks" rather than Shields, and Code Composer Studio (or other \[some non-gratis\] tools) instead of the Arduino IDE and libraries.

The Energia IDE is a port of the Arduino IDE and significantly simplifies configuration and programming Tiva C launchpads.

Beware of odd quirks with the Tiva C Launchpad board, such as the 0-ohm shunts that must be removed if you want all pins to be completely independent.

# Answer
> 1 votes
I have completed the edX course, and the TM4C123 is significantly different to the Arduino from a programming perspective. Each family of microcontrollers have (on the surface) a fair amount in common - GPIO pins, an ADC or two, timers etc. However the way these work internally are very different - different registers, different process for using them, different gotchas to look out for, etc. If you're looking at tackling a new MCU family, be prepared to effectively learn a new "language".

Incidentally, the Launchpads from Texas Instruments have a processing-based language similar to the Arduino - called Energia - which should work on your TM4C123.

Enjoy the course, I did.

---
Tags: arduino-uno
---


# Question
Title: Can I use this pinhole camera with arduino?
The pinhole camera is a 420TVL, 3.7mm Passive Infrared Detector Color Covert Security Camera. Can I use this camera with an arduino creation?

Things I don't know to answer the question:

1. Does the power need something special arduino can't offer?
2. Is the arduino powerful enough to push the video feed/photos to a computer or any other method to video/photos.

Here are some specs from the site:

> * Sensor 1/3" Sony Super HAD II CCD
> * Picture Elements NTSC 768x494
> * PAL 752x582
> * Horizontal Resolution 420 TVL
> * Minimum Illumination 0.001 Lux
> * S/N Ratio more than 50dB
> * Scanning System 2:1 interlace
> * Synchronous System Internal, Negative sync
> * Auto Electronic Shutter NTSC 1/60s ~ 1/100,000s
> * PAL 1/50s ~ 1/100,000s
> * Gamma Characteristics 0.45
> * Video Output 1 Vpp, 75 ohms
> * Auto Gain Control Auto
> * Power / Current DC 12V (±10%) / 150mA
> * Lens 3.7mm Taper Pinhole Lens

Is it possible? They're on sale but I don't want to throw money away and find out that they don't work with any arduino. Also, I don't have any setup for this to be plugged into. Therefore, I'm not tied down to previous creations the cameras need to fit in.

# Answer
> 3 votes
No, you cannot use this with an Arduino without additional hardware in between, and even with it, not as more than a still camera (or maybe low quality video for one of the ARM- rather than ATmega-based boards).

The first problem is that this camera has a high speed analog output called composite video. It is basically what would be fed into a modulator to produce an old-style analog TV signal. Capturing this digitally requires an Analog to Digital converter (ADC) capable of several million measurements per second, while that on the classic ATmega-based Arduino tops out at around ten thousand.

But let's say you had an additional Analog-to-digital converter to put in between this and your arduino. The next problem is that the data rate out of the camera will be too high, and the Arduino won't have enough RAM memory to buffer it.

In theory, you could get a "frame grabber" consisting of an ADC and its own buffer memory, which would take a still snapshot of the video and allow the arduino to read it out more slowly. But you can buy cameras which already do that with their onboard electronics, and allowing something like an Arduino to read the still image data out over a moderate speed serial interface.

Even the ARM-based arduino boards would be taxed to keep up with the output of a video ADC and do much of anything useful with the results - typical digital cameras do not record raw images to SD card, but do JPEG compression within a frame. When cheap digital cameras operate in video mode, they compress each frame of the video before storing it (just as with stills - they do not compress between frames in the manner of real video recorders), and are able to get that processing done in time because the actual computing hardware is optimized for it in a way that none of the Arduinos are.

If you want to experiment with a camera on a development platform, there is one with a high speed digital interface sold as an add-on for the Raspberry Pi board. Or you can use a more inexpensive USB webcam with that.

---
Tags: power
---