text:
Using an ultrasonic sensor to act as a potentiometer for a Servo?
I would just like to start off by saying that I am new to Arduino so my code and approach to the wanted outcome are probably not the best. Anyway, I had the idea of using an ultrasonic sensor and my hand to act as a potentiometer to control the position of a servo. So, I wired everything up and wrote the code but the Servo just jitters around and doesn't move the way I wanted it to. The serial readings are fine, it is just that the servo isn't responding the way I hoped. Here is the code
#include <Servo\Servo.h>
#define echoPin 7
#define trigPin 8

int maximumRange = 400;
int minimumRange = 0;
int angle;
long duration, distance;
Servo myServo;

void setup()
{
    Serial.begin(9600);
    pinMode(echoPin, INPUT);
    pinMode(trigPin, OUTPUT);
    myServo.attach(9);
}

void loop()
{
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance = duration / 58.2;

    angle = map(distance, minimumRange, maximumRange, 0, 179);
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.print(" Angle = ");
    Serial.println(angle);
    myServo.write(angle);
    delay(50);
}

If anyone can help, it would be appreciated if you could post what is wrong with my code and how to fix it.
Note: I'm using Visual Studio instead of the Arduino IDE, so that is why it says #include <Servo\Servo.h> at the top.

WHat does the serial monitor display? Do you have frequent small variations of angles? If yes, that would explain the servo jittering. The solution is then to somehow smoothen the angle to avoid small angle variations. The fact is that the ultrasonic sensor will not give the exact same value everytime, event if the distance does not change.

This question http://arduino.stackexchange.com/questions/4135/arduino-starter-kit-servo-is-shaking may be related to your problem, check its answers.

what servo are you using?


text:
Make upload stuck on osx 10.10 bare-arduino-project
I followed the instructions in here, including to use arduino IDE v 1.0.5, but when I tried to make upload it stuck. I can upload it when using Arduino IDE.
Here is what I got:
  mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject
 /Applications/Xcode.app/Contents/Developer/usr/bin/make reset
 /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino  /dev/cu.usbmodem1421
 /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload
 /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \
        -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i

What did I miss?
I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, my Makefile

I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)
Have you installed pyserial and avrdude?
To install avrdude just run brew install avrdude and to install pyserial, you need python installed, then you can run pip install pyserial.
https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial
Hope it helps :)
Next time, feel free to open an issue in the Github repo as it might also help others.
EDIT: my bad, I did not read your Makefile carefully!
the problem is with:
BOARD_TAG         = mega328
# it should be
BOARD_TAG         = uno

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Sending binary data to Matlab via serial
I would like to exchange data via Xbee. I've set up a communication based on strings between the Arduino and a Matlab software.
Unfortunately this kind of communication isn't enough robust and sometimes messages aren't delivered correctly. So I decided to move to the binary communication.
The problem:
I'm not able to send binary data from the Arduino to the computer.
Let's say we want to send the decimal value 17 which is 0x11 in hex if we receive 16 from Matlab.

[...]
SoftwareSerial xbee(pinRx, pinTx);
void setup()
{
  Serial.begin(BaudRateSerial);
  xbee.begin( BaudRateXbee );
}
[...]
void loop()
{
 while(xbee.available())
  {
    getData = xbee.read();
    Serial.println();
    Serial.print("Received: ");
    Serial.print(getData,HEX);
    Serial.println();
    if(getData == 16)
    {
      // First attempt
      //uint8_t s = 17;
      //xbee.write(s);  -> Fail
      // Second attempt
      //xbee.write(0x11);  -> Fail
      // Third attempt
      byte message[] = {0x11, 0x11};
      xbee.write(message, sizeof(message));
    }
  }
}

In the third attempt I tried sending an array of bytes and noticed that the received values were different.
byte message[] = {0x11, 0x11};

xbee.write(message, sizeof(message));

The Matlab software sends data correctly. I used the fwrite function as follows fwrite(xbee,hex2dec('10')); and the fread function to receive the ack which:

reads binary data from the device connected to the serial port object,
  obj, and returns the data

Matlab relevant code:
fwrite(xbee,hex2dec('10'));
disp('Ack Requested...')
ack = fread(xbee);
disp(ack);
if (ack == 17)
     % communication established
end

I've also tried using XC-TU to monitor traffic on Serial port (blu values are sent from the PC, red ones are received from the Arduino) and as you can see red values are different and none of them is equivalent to 17! What am I missing?

what is the range of your number?

I think the problem is in Matlab. You send data from string so String a = "1"; is byte 31. Make a debug, add Serial.println(getData,HEX); and see what are you getting

The range is +/- 5000. I am able to receive data from Matlab. I've done the test with XC-TU to see the hex values sent from Arduino and as you can see, the boards sends every time different values. (Red ones) XC-TU and matlab receive the same data.

xbee.write(message, sizeof(message)); this shows in MatLab as 75,70??? Not sure but try to check baud rates or so. I just can't see what is wrong..

Yes exactly. Every time I click a button in MATLAB, it sends 16. Arduino receives it and responds with 17 twice. The values sent are completely different from each other. It doesn't make sense... Is the software serial library the problem?

Add Serial.println(getData,HEX); after getData = xbee.read(); and say what you get

The value displayed on the serial monitor is 16

Ok, now it works. It was because of a previous sketch uploaded. There were bytes stored in the buffer. The values I was receiving belonged to an old buffer. Maybe xbee.flush() should do the job

if you can read "17" in the serial monitor you sent the characters "1" and then "7", not the binary number 17.

narutov6 please clear your question and problem. From now it is hard to unerstand what is wrong. Be more detail and eliminate all unnecessary parts

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What is the best way to measure PWM signals ( pulseIn ) with the Arduino via a Raspberry Pi?
I connected my Arduino Uno to my raspberry via USB serial. I'm able to read out both digital and analog pins of my Arduino using the Python nanpy library (v.0.8).
However, I can't find support for the pulseIn() function. It seems nanpy doesn't support pulseIn() at all.
What is the best way to measure PWM signals with the Arduino and forward the results to the Raspberry Pi?
I am able to measure PWM using the Arduino GUI, however I would to take PWM samples at fixed time intervals over a long period of time and combine this data with other measurements that my Raspberry is making.I also tried pyFirmata, but it doesn't support pulseIn() measurements either.

It seems like this could be a fairly trivial addition, if you can find the source code for both the Arduino and host portions, and successfully build and use new versions.  Often it's useful to try to create and test a from scratch build before you try to modify it.  But it may also be possible you run into more complicated interactions, for example if the usual pulse timing mechanism delays expected traffic.

You can just have a sketch in the arduino that takes the measurements at whatever interval you want using the analogRead(pin) function and then forward those results to the raspberry pi via serial using Serial.print(whatever you want here). If you don't know how to use serial with arduino just go to their site, they have very good documentation.
Hope that helps :)

Nanpy seems to have a CounterClass that does frequency measurements.
Or do you want to measure the PWM duty-cycle?

I would like to measure the downratio. Preferably I would use pulseIn to measure one uptime pulse and one downtime pulse. From this I can calculate the desired downratio.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Sense distance with Bare Conductive's Touch Board
How can I sense distance with Bare Conductive's Touch Board, like they suggest in their product video?
I know how I can set the touch and release thresholds, so my Touch Board is more sensitive and triggers before I touch a sensor. What I want to do is get the information how near I am. Not in centimeters or so, but a simple value telling me when I'm nearer to or farther from the sensor like in the video.

As a member of the Bare Conductive team, I can tell you that looking at the grapher will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the Datastream code. Datastream will give you the sort of raw electrode data that you're looking for.


text:
Getting Push Button Logic To Stick?
I'm trying to get a sensor to activate if a push button is clicked. And deactivate when a certain condition is met and reactivate when the push button is pressed again.
#include <SPI.h> // Included for SFE_LSM9DS0 library
#include <Wire.h>
#include <SFE_LSM9DS0.h>

#define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
#define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
// Create an instance of the LSM9DS0 library called `dof` the
// parameters for this constructor are:
// [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

const byte INT1XM = 4; // INT1XM tells us when accel data is ready
//const byte INT2XM = 8; // INT2XM tells us when mag data is ready
//const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
const int buttonPin = 15;     // the number of the pushbutton pin

int buttonState = 0;

double X;
double Y;
double Z;

void setup(){

  pinMode(INT1XM, INPUT);
  pinMode(buttonPin, INPUT);

  Serial.begin(9600);
  Serial1.begin(9600); // Start serial at 115200 bps
  // Use the begin() function to initialize the LSM9DS0 library.
  // You can either call it with no parameters (the easy way):

  uint16_t status = dof.begin();
  // Or call it with declarations for sensor scales and data rates:
  //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

  // begin() returns a 16-bit value which includes both the gyro and
  // accelerometers WHO_AM_I response. You can check this to make sure
  // communication was successful.
  // Serial.println(status, HEX);
  setODR();
}

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.

 // Serial.println(buttonState);

  if (buttonState == 1) {   //if push button is pressed

    printAccel(); //print sensor data

  }

}

void printAccel()
{
  // Only read from the accelerometer if the accel interrupts,
  // which means that new data is ready.
  if (digitalRead(INT1XM))
  {
    // Use the readAccel() function to get new data from the accel.
    // After calling this function, new values will be stored in
    // the ax, ay, and az variables.
    dof.readAccel();

    //Serial.print("A: ");

    // Using the calcAccel helper function, we can get the
    // accelerometer readings in g's.
    X=dof.calcAccel(dof.ax);
    Y=dof.calcAccel(dof.ay);
    Z=dof.calcAccel(dof.az);

    Serial.print(X);
    Serial.print(", ");
    Serial.print(Y);
    Serial.print(", ");
    Serial.println(Z);

    // Serial1.println(Z);

    fall(); //jump to check condition

  }
}

void setODR(){

  dof.setAccelODR(dof.A_ODR_25);
  dof.setAccelScale(dof.A_SCALE_16G);
}

void fall(){

  if(-0.08<X && X<0.08){
    if(-0.08<Y && Y<0.08){
      if(-0.08<Z && Z<0.08){

        Serial1.println("N");
        Serial.println("Fallen!");

        loop(); //if condition is met, jump to loop to wait for push button to be pressed again.

        }
      }
    }
  //else{

    printAccel(); //else continue printing sensor data

  //}
}

However I am having some trouble getting it to work, above is what I have worked out thus far.

What does your DFA look like?

@IgnacioVazquez-Abrams I'm a little new to this, what does DFA stands for?

You'll need to store whether the button has been pressed.
bool buttonActivated = false;

...

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.
  if (buttonState == 1 ) {
    buttonActivated = true;
  }

  if( buttonActivated ) {
    printAccel(); //print sensor data
  }

}

to deactivate, use:
buttonActivated = false;


text:
How to power a Seeeduino Stalker v2.3 - water proof with charger instead of solar panel
I am currently coding on a Seeeduino Stalker v2.3 - water proof kit.
http://www.seeedstudio.com/wiki/Seeeduino_Stalker_-_Waterproof_Solar_Kit
It is sold with a solar panel to recharge the battery. Unfortunately, I will not have a lot of light where my sensor will be installed and I would like to power the board with a charger from 110V-220V plug and keep the battery only for potential power shortage.
My questions are:

What is the best option for connection and charger?
I have a previous Arduino Uno charger (9V-1A). Would it work with some linear regulator? What wiring should I use?
Any recommendation for a Li-Ion battery that could I buy and that would last longer than this 3.7 V at 1000mA?

Thank you for your help :)

To be as little invasive as possible, I'd remove just the solar panel and replace it with a power supply with the same typical voltage (5.5V) and at least the same typical power output (0.5W). It should not be too difficult, nor too expensive. Any USB charger that can provide 5V should do. You can just cut the USB connector and attach the wires to the board. Or be more elegant and create an adapter. Either way should work. And the price should be about a couple of bucks.
Yes, I think it would work, although linear regulators 9V -> 5V are really inefficient. See my proposed solution from the previous point.
On ebay there's plenty of options, but they might not fit in the box of the seeduino. You have to compare the dimensions of the battery vs whatever extra space might be available.

You can charge the battery and power the board, via USB. The CN3063 requires between 4.4V to 6V, so not a huge range of options besides a 5v wall-wart
No. 9V would be too high.
How many mains power failures / brownouts do you get, where you live?

About point 2: @Somarinho proposed to use a linear regulator. While that would be highly inefficient, it could work.


text:
Explanation please, of hardware and software serial links
I am starting to use a Seeeduino GPRS shield (please see note), which is essentially an Arduino Leonardo that, among other things, can be used as a mobile 'phone for sending and receiving texts. I have successfully tried the "blink an led" and "fade an led" sketches, so the compiling and uploading are ok
I am using a desktop computer with Linux Fedora 20.
Now I want to go on to use the cell phone network to communicate with my mobile 'phone. However I am puzzled by something I assume everybody else understands already, and that is the references to "select either software serial port or hardware serial port to be connected to GPRS Shield". Please could someone explain what "software or hardware serial port" is, in simple terms, or point me to a web site that does so? Do I need any wired connection with my PC other than the USB link I use for uploading sketches?
Note: I bought a discounted GPRS shield labelled version 1.0a2. All the information on the 'net is of version 1.0 or 2.0 (with no "a2") and photos and diagrams do not correspond with what I have. I am awaiting official documentation, but meanwhile treating it as an Arduino Leonardo seems to be working.

The Seeeduino GPRS shields version 1.0 and 2.0 are just shields. They do not contain an Arduino MCU and don't have a USB, and so will not function as an Arduino. As you say, yours is a bit different and does function as an Arduino. This may be the source of your confusion with the guides, as they assume you are plugging the GPRS shield into another Arduino. Please post a picture of the board.

Most small micro controllers, AVR's included, have dedicated hardware for communicating with different serial devices. In arduino these are referenced with "Serial", "Serial1", "Serial2" and so on, depending on how many hardware serial ports your particular arduino has.
Leonardo's are an exception, the first hardware port is "Serial1" and "Serial" refers to the PC's usb connection. On the other arduinos that I know of "Serial" is hardware serial used for PC comms, so using it for other hardware requires sacraficing your PC link.
Software serial ports use the processors more generic pin-change interrupt system to communicate on any pins that support said interrupts, but they have a higher processing overhead and often cannot support the same high speeds as the hardware serial. There are different libraries for Software Serial that have different approaches giving different advantages and drawbacks.
To use a software Serial port you will need to make one to be used in your code, which will look something like this, depending on the type name the library you include uses:
SoftwareSerial softSerial( txPinNumber, rxPinNumber);

So in short, your processor has dedicated hardware for communicating over serial that should be used first, but if you need more ports the processor can simulate some extras which is referred to as "Software Serial". The documentation to your GPRS shield implies that either will work just fine. You should look at the arduino documentation for your board to see how many ports you have and which pins can be used for serial.
The documentation does not imply you will need any special link to your computer outside of the USB connection.

Yes - if this were at ATmega328p-based board like an Uno, the hardware serial is already used for the PC connection, so serial peripherals usually go on a software serial if they cannot be permitted to block PC communication.  But on a Leonardo type board as in this question the hardware UART is free and so can be "used first" as you recommend.  Similarly, if the board were a Mega, there would be multiple hardware UARTs, some possibly free.

The hardware serial port is the serial port which connects to the computer this takes up pins 1 and 2 I believe. You can read about this here http://arduino.cc/en/reference/serial.
Software serial ports are only on digital IO pins. You can read more about this here
http://arduino.cc/en/Reference/softwareSerial
You should not need anything other the USB connection port.

The question concerns a Leonardo-type board, where the computer connection is not via the UART pins, but rather via the on-chip USB interface.

A SoftwareSerial connection is created using the UART pins 7 and 8.
Having the device in HardwareSerial mode allows the device to connect to pins 0 and 1, allowing direct control from the serial connection to the computer.
In SoftwareSerial, you can communicate with the Arduino Via serial, and the Arduino controls the GPRS shield via uart.

Software serial can be on any GPIO pins.  And the Leonardo-type board in this question does not connect to the computer via a UART on pins 0 and 1, but rather via the on-chip USB interface.


text:
Powering a 5V Arduino Pro Mini with 3.3V
I want to run the 5V board at 3.3V because I can get the 5V version cheaper than the 3.3V version.
I read that you can power the Arduino Pro Mini with a battery by connecting the battery to the 5V pin, bypassing the regulator.
Somewhere else I read that the only difference between a 3.3V and 5V Pro Mini is the regulator.
Are these assumptions correct? If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

The 3.3v version runs at a slower speed (reason). Note that some voltage regulators don't like it when the have a higher voltage at the output, than on the input. One went up in smoke on some other board I have. Just desoldered it, as I didn't need it. Other than that, no problem.

I just discovered that I knew the answer to this, because I was accidentally running some 5v/16MHz Pro Mini boards at 3.3v without issue.
Short Version
Yes, you can run one feeding it 3.3v, but you need to program it as a 5v/16MHz board to get the clock speeds right.  Also, all your TTL levels (outputs) will be 3.3v, not 5v.  Additionally, at least in my experience, the processor will run at 16MHz and not 12MHz with 3.3v.
Background Story
I had some generic Pro Mini boards that didn't mark their voltage at all, so I tried programming (and running) them using my FTDI at 3.3v using the 3.3v/8mHz option in the Arduino IDE.  I was able to upload programs just fine, but the clock was clearly wrong, as the "Blink" program ran about 2x as fast.  That told me that it was running faster than 8MHz .
So I tried again this time telling the IDE it was a 5v/16MHz chip, and everything ran fine, despite the fact that I was feeding it 3.3v.  I even saw that pin 13 was cycling from 0v up to 3.3v - exactly what I was feeding it.  So for a while I just thought they were 3.3v Pro Minis.
But then thinking about it, I realized that having to tell it to run at 16MHz to get the clock right meant it really was a 16MHz chip - which I didn't think was available with the 3.3v model.
So on a whim (and since I have a ton of these little boards), I changed my FTDI to 5V, and was able to run and program the board just fine.
So from that, I conclude that yes, you can run them at 3.3v, but your TTL levels will be just 3.3v.

Pro Mini 5V has voltage regulator for 5V and 16MHz quartz.
Pro Mini 3.3V has voltage regulator for 3.3V and 12MHz quartz.
According to manufacturer specification Atmega328 chip powered by 3.3V cannot run 16MHz and needs at most about 13MHz. But it's official specification. Some chips are better than specification (faster) some are worse (slower). So you can try whether your Pro Mini is better or not. Or you can change quartz to 12MHz, if you can solder SMD parts.
Or better look for cheaper 3.3V clone, they are not much more expensive as 5V version...

You could also temporarily hook up ISP and use that to set the fuses for an internal 8 MHz, ignoring the crystal.

All the Pro Mini 3.3V's that I've seen run at 8MHz. But you are correct that about 12MHz is the official maximum frequency for the Atmega328 at 3.3V.

I just ran a generic (eBay special) 5v Pro Mini with 3.3v, and saw that it does still run at 16mHz.  I based this on using 1 sec "Blink" program and putting it on an oscilloscope.  So as mentioned above, test it first - it may run at 3.3v and 16mHz just fine.  I outlined some details of this in an answer below.

First I am going to say it is very much possible. Allow me to explain.
The 5v version can be powered with 3.3v, but it is not recommended to supply power through the 5v pin, bypassing the regulator. Only regulated 5v power should be supplied through the 5v pin. Any other voltage levels should go in the RAW pin. If you supply the Arduino Pro Mini 5b with 3.3v the chip will only be underclocked to 8-12MHz, and the voltage for Vcc (the board's operating voltage and what it will power its pins with) will be 3.3v; but there is another way.
I primarily source my components from SparkFun due to their reliability, cheap price and awesome support. They provide the Arduino Pro Mini in 3.3v and 5v variants for only $10. I have used both variants for many purposes, but primarily when working with embedded and small solutions. One of those times I was accessing sensors that ran on 5v TTL logic, but I didn't have room to place a >5v battery, only room for a LiPo (which generally powers 3.3v).
I was able to solve this issue with a SparkFun 5v Step-Up Breakout*, which boosts the voltage to 5v without any other major issues. I should warn you that there are some issues you could face if you are using a LiPo to feed into the Step-Up. Even if you aren't I'll list it here for reference. The Step-Up's maximum safe input voltage is 4v, and can be a bit unreliable if the voltage goes above it. Unfortunately a LiPo's discharge curve places it above 4v when it is within the upper 95% soc (state-of-charge), so a 3.3v regulator (which SparkFun also sells) would be needed to reliably power an Arduino Pro Mini 5v through a Step-Up breakout (at least in my experience). Also, power from a Step-Up breakout is regulated.
*Pololu also sells a comparable Step-Up that could handle an input up to 5.5v in theory, but I haven't personally used it.

Im feeding 5V pro mini clone with 2 AA battery, to VCC pin, about 3V and it works normally. It consumes few current compared to 5V.
And you can see what it the setup in here.
Also this video can be useful.

You should feed the battery to the Vcc pin, and not Raw. Raw goes thru the regulator, Vcc will bypass it.  The same 328P chip is used on both 5V and 3.3V boards, the difference is the Resonator (16 MHz vs 8 MHz) and the regulator (5V vs 3.3V).       Running a 16 MHz board at 3 or 3.3V is running it out of spec, you may see some odd behavior, the Arduino forum has seen cases where Serial did work correctly at lower voltages.

Its on VCC already sorry. I don't use Serial function. I read DHT22 and use i2c oled without a problem.

So, just change the fuses to use internal 8 MHz oscillator, and you're within specs, right?

If yes, can I use a 5V Pro Mini like a 3.3V by powering it with a 3V Battery on the 5V pin?

two options (at least):
1) apply 3.3v at the regulator output pin. there may be already a break-out for that on the board;
2) solder in a 3.3v regulator in place of the 5v regulator -> fairly easy to do as well.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Digital Potentiometer not fading LED
So I am trying to test what will eventually be a Arduino controlling 3 110V motors that are currently controlled by an analog pot. But more on that later.
I am trying to test out using a digital pot (never have before) and am running into some issues with tutorials I have found online. For now, I want to control a LED with the digital pot (Spec Sheet) so that the LED fades in and fades out in a continuos loop.
Here is the tutorial I followed. It uses a different chip model but it seems from the pot I am using that the pins are the same. (I could be wrong?)
I double and triple checked the wiring and it matches below.

Here is the code I am running (slightly modified from the tutorial, also tried the tutorial code)
#include <SPI.h>
byte address = 0x11;
int CS= 10;
int i=0;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotWrite(i);
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotWrite(i);
      delay(10);
    }
}

int digitalPotWrite(int value)
{
  digitalWrite(CS, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

As a result of the two above, I have an LED that stays lit (at about 50% it seems) and does not fade in/out at all.
Being relatively new to wiring and EE in general, is there a better way to replicate an analog pot without using a digital pot? Can I just use PWM to control it? Why would the LED be just staying lit?
Thanks!

The spec sheet you provide is very general and covers very different models of digital pots. What is the exact reference of yours?

Sorry @jfpoilpret, I am using the MCP41X1 reference as the chip is a MCP4131 via Amazon

Yes, you can just use Arduino PWM to control an LED. See http://arduino.cc/en/Tutorial/Fade .

After studying the datasheet differences between MCP41100 (digital pot used in the tutorial) and MCP4131 (the one you get), I found two major differences between both:

Difference in resolution:

MCP41100 has 257 steps resolution (8 bits + 1): you can see that at the beginning of its datasheet
MCP4131 has only 129 steps resolution (7 bits + 1): you can get this information on page 2 of its datasheet

Difference in commands formats sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:

MCP41100 command byte is X X C1 C0 X X P1 P0 where X is unused, C1 C0 is one of 4 possible commands,  only 2 being valid commands actually: 01 (Write data), 10 (Shutdown), finally P1 P0 should be always 01 for an MCP41100
MCP4131 command byte is AD3 AD2 AD1 AD0 C1 C0 D9 D8, where AD3-AD0 is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is 00 which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), C1 C0 is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be 00 (write data); finally D9 D8 are the high order bits of the value to write to the register, but D9 is unused and should always be 0. For 257-steps pots, D8is used to have the full resistance scale, otherwise it should be 0

Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:
00010001 value

The first byte can be broken down as such:

0001 address of the pot wiper register 1 (not 0): this wiper does not exist on MCP4131 hecne writing to it will have no impact...
00 command bits meaning "Write to register specified in previous address"
01 high order bits (D9-D8) of the value to write to the wiper register.

Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:
byte address = 0x00;

And that should be fine! Indeed, now your program passes:
00000000 value

Which means "write value (between 0 and 128 which matches exactly the 129 steps resolution) to the wiper register 0 of the port".
Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.
void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotIncrement();
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotDecrement();
      delay(10);
    }
}

void digitalPotIncrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x04);
  digitalWrite(CS, HIGH);
}

void digitalPotDecrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x08);
  digitalWrite(CS, HIGH);
}


text:
Can I use this replacement motor without modifying the circuit?
I have a demo that spins a motor, but the leads on my motor broke. I happen to have another motor lying around that I'd like to swap in, but it's of a different type. Here's my circuit:

This is the old (broken) motor: https://www.sparkfun.com/products/11696. It has an operating voltage range of 1.0 to 3.0V DC and a no load speed of 6600±10% RPM (@1.0V DC, 110mA).
The new motor that I'd like to use is part of this kit: https://www.sparkfun.com/products/12866. It's a 6VDC motor with a No Load Speed of 90±10rpm and a No Load Current of 190mA(max.250mA).
I'm running this off a Sparkfun Redboard, which is UNO R3 compatible.
Can I swap in the new motor without any circuit changes? Will I have to add additional power for the new motor? Or should I change the circuit with a larger resistor or something else?

The board runs off USB, so 5v, I think.

You really shouldn't be running motors off the Arduino's power supply to begin with.  The new motor's higher voltage rating suggests that at the same voltage it may actually draw less current than the low voltage motor did - but it may also fail to spin.

Regarding voltage, I think there should be no problem as the datasheet for your replacement motor specifies a "suggested voltage 4.5V DC".
However, be careful that there is another important value in motor datasheets: the stall current.
Simply stated, this is the current consumed by the motor when it tries to rotate but is unable to, due to its too low torque in comparison with the effort needed for rotation, e.g. if it tries to rotate the wheel of a robot that is too heavy.
The original motor has a stall current of 0.8A according to its datasheet (you can get it from the link you provided).
Your replacement motor has 1A according to the link you provided.
These 200mA can make a big difference for the transistor used in your circuit, a P2N2222A.
Indeed, that transistor is specified to switch a maximum of 600mA current at the collector.
So in the best case, the motor will run correctly without load, but if you provide some load that makes it stall, then the transistor will raise temperature (you could sense that by approaching your finger) and ultimately would get toasted.
Please also note that some poorly designed motors may consume a current near the stall current, due to internal friction (I have already almost grilled a transistor this way...)
So my answer is:

you can do it for a simple experiment with no load on the motor
if you really want to do something with the motor, take another transistor with a higher Ic current

Great answer! This motor does work in a pinch so I can get my demo done; it's a little wimpy but does spin. Thanks for explaining the robustness / torque factor!


text:
How can I pass an object as a parameter to a function?
I am making a tiny game, and want to store high-scores. I made a Highscore-class in the top of the sketch file, like this:
class Highscore {
public:
  String name;
  int score;

  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

setup() { // etc

Now. Near the bottom of the sketch, I have a function I want to take a Highscore-object as a parameter, but the compiler will not let me. Example:
void writeHighscore(Highscore hs) {
  File f = SD.open("high.txt", FILE_WRITE);
  // Do stuff

The complation error is as follows:

sketch.ino:19:21: error: variable or field ‘writeHighscore’ declared void
  sketch.ino:19:21: error: ‘Highscore’ was not declared in this scope
  sketch.ino: In function ‘void setup()’:
  sketch.ino:64:20: error: ‘writeHighscore’ was not declared in this scope

After changing parameter type to String, int or whatever, all the errors go away. I am able to create Highscore-objects INSIDE the writeHighscore() function, but how can I pass objects to it?
Edit 1 - Object creation
Highscore hs = Highscore("John", 975);
Serial.println(hs.toString()); // Prints "John - 975" as expected
writeHighscore(hs); // Error

can you please post the code where you create Highscore object?

Included the object creation code.

I think the problem is some missing bracket or so. Because there is no full code, I can guess and see: 1)  setup() should be void setup(). But it should generate C++ warning/error. 2) Passing class parameter forces object copy when procedure is called. gcc should also generate a warning if copy constructor is missing. Use:
void writeHighscore(Highscore &hs)
or
void writeHighscore(Highscore *hs)
Copy compilable snipet in your post.

Like stated in the original question, by changing the Highscore-parameter by, say, a String or an int, the errors go away, there are no missing brackets. I've also tried the &hs approach beforee writing the post, as well as passing the pointer writeHighscore(&hs) -> void writeHighscore(Highscore *hs) but to no avail.

Please post the full source code, otherwise the line numbers in compilation errors are pointless.

You are doing everything right, but you need to move the class outside of your .ino file for this to work.  I'm not sure why the arduino IDE makes you do this  (see edit) , but it is something I've run into before.
I just tested this, and moving the class declaration outside the ino and into a header file in the project folder makes it compile correctly. Just remember to include the header you make in the ino and to #include "Arduino.h" in the header to get access to "String" again.
Technically, only a forward declaration of the class needs to be in a different file.
Edit:
I'm relatively sure what is happening is the IDE is generating forward declarations for all your functions but not the class, which are placed before your class definition.
This means that breaking the function regex the IDE uses with a dummy "throw()" fixes your problem. for example:
void writeHighscore(Highscore hs) throw() { ...

should work just fine (it worked for me)

This is a classic example of the IDE "helping" you by generating function prototypes, and not doing it very well. Example code to reproduce:
class Highscore {
public:
  String name;
  int score;
  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

void setup () { }
void loop () { }

void writeHighscore(Highscore hs)
{
// do stuff
}

This gives the error:
sketch_jul06b:4: error: variable or field ‘writeHighscore’ declared void
sketch_jul06b:4: error: ‘Highscore’ was not declared in this scope

If you look at the output of the IDE preprocessor (you can do this by turning on verbose compilation, and finding out the name of the file it is actually compiling) you see this:
#line 1 "sketch_jul06b.ino"
#include "Arduino.h"
void setup ();
void loop ();
void writeHighscore(Highscore hs);
#line 1
class Highscore {
public:
  String name;
  int score;
  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

void setup () { }
void loop () { }

void writeHighscore(Highscore hs)
{
// do stuff
}

The important part is that it put:
void writeHighscore(Highscore hs);

before where the class is declared.

You can fix the error by simply generating your own function prototype like this:
void writeHighscore(Highscore hs);  // function prototype
void writeHighscore(Highscore hs)
{
// do stuff
}

Now it compiles without errors. It detects your own function prototype, and therefore does not generate its own. The first few lines of the generated file are now:
#line 1 "sketch_jul06b.ino"
#include "Arduino.h"
void setup ();
void loop ();
#line 1

That troubling prototype has gone.


text:
What in the example code is different from my test code? LED matrix lights up differently
I'm trying to get my LED matrix to run Conway's Game of Life. After 4 different pin configurations, I've finally been able to run a separate test code, that lights all the LED's in order, and then turns them off in order (Code Below). I've written the entirety of GoL in C#, but the Arduino language is just different enough to where I can write sort of ok in it, but not enough to understand what's going wrong. I got a Game of Life code from here and it won't even light my LEDs, or when it does, it's incredibly dim, unlike my test code. I'll show my pin layout in the code. I've tried changing the pins in the GoL code, copying the setup from one to the other, and  but for the life of me, I can't seem to figure out why one would light up the LED's without a hitch, and the other is struggling. Can anybody see the changes I'd need to make that would make the GoL code at that link, work like this test code?
Here's my Test code that works fine:
int speed = 4; //the delay time in milliseconds

int pauseDelay = 1;    //the number of milliseconds to display each scanned line

//Pin Definitions
int rowA[] = {14,15,16,17,2,3,4,5};          //An Array defining which pin each row is attached to
                                     //(rows are common anode (drive HIGH))
int colA[] = {6,7,8,9,10,11,12,13};  //An Array defining which pin each column is attached to
                                     //(columns are common cathode (drive LOW))

//The array used to hold a bitmap of the display
//(if you wish to do something other than scrolling marque change the data in this
//variable then display)
byte data[] = {0,0,0,0,0,0,0,0};

//Setup runs once when power is applied
void setup()
{
  Serial.begin(9600);         //Open the Serial port for debugging
  for(int i = 0; i <8; i++){  //Set the 16 pins used to control the array as OUTPUTs
    pinMode(rowA[i], OUTPUT);
    pinMode(colA[i], OUTPUT);
  }
}

//repeats
void loop()
{
 //Example #1 - test pattern
 //Run a small test program which lights up each light in time
  test();

 //Example #2 - static image
 //Display a defined bitmap
/*
  data[0] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[1] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  data[2] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[3] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  data[4] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[5] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  data[6] = B10101010; //row 1s bit mask (1 LED is on 0 LED is off)
  data[7] = B01010101; //row 1s bit mask (1 LED is on 0 LED is off)
  showSprite(speed);
*/
 }

//An array to store power values to act as bit masks
const int powers[] = {1,2,4,8,16,32,64,128};

//Runs a pattern where each LED is lit one after another
void test(){
  for(int i = 0; i < 8; i++){
for(int ii = 0; ii< 8; ii++){
data[i] = data[i]+ powers[ii];   //Goes through each row of lights lighting each column one after another
showSprite(speed);
}
  }

  for(int i = 0; i < 8; i++){
   for(int ii = 0; ii< 8; ii++){
data[i] = data[i] - powers[ii];   //Goes through each row of lights turning off each column one after another
   showSprite(speed);
    }
  }
}

void showSprite(int speed2){
 for(int iii = 0; iii < speed2; iii++){                 //show the current frame speed2 times
  for(int column = 0; column < 8; column++){            //iterate through each column
       for(int i = 0; i < 8; i++){
           digitalWrite(rowA[i], LOW);                      //turn off all row pins
   }
   for(int i = 0; i < 8; i++){ //Set only the one pin
     if(i == column){     digitalWrite(colA[i], LOW);}  //turns the current row on
     else{                digitalWrite(colA[i], HIGH); }//turns the rest of the rows off
   }

   for(int row = 0; row < 8; row++){                    //iterate through each pixel in the current column
    int bit = (data[column] >> row) & 1;
    if(bit == 1){
       digitalWrite(rowA[row], HIGH);                   //if the bit in the data array is set turn the LED on
    }

   }
   delay(pauseDelay);                       //leave the column on for pauseDelay microseconds (too high a delay causes flicker)
  }
 }
}

I ended up using a different PIN layout, and the GoL code had the pins As anodes where they were Cathodes in the other code. Switched rows pins to Columns pins in the code and Problem solved.


text:
Have Arduino write data to a MySQL database?
Would it be possible to have an Arduino write directly to a MySQL database?
I'm a web programmer, so I'm familiar with how to get records from a MySQL database. I have MAMP installed on my mac, so I have the ability to build an interface, directly in the web browser, that retrives the records from a MySQL database.
What I'm thinking is to connect the Arduino directly to my computer via USB, and write data from the sensors, or the pins, directly to my MySQL database.
I'm using two phototransistor to record whenever something blocks the light. Each sensor records individually a timestamp for when the blocking occur.
Is that possible?

This looks like a project that will do what you are looking for https://launchpad.net/mysql-arduino

It's possible if you forget about the Arduino directly writing to the database.
Simply put, the Arduino is restricted to a serial connection.  To directly communicate with MySQL you would need a network connection, and then implement the MySQL protocol - a huuuge amount of work.
The normal way is to have an adapter program running on the PC which receives data from the Arduino over the serial connection, then performs any insert, select, etc instructions on the MySQL for you.
There is a "MySQL Connector" available* (https://launchpad.net/mysql-arduino) but of course that requires you to have an active network connection of some form to your Arduino.  Remember that the Arduino (certainly the Uno) is very limited on memory and program space, so having the Arduino connect direct, and doing anything else, might be mutually exclusive.

*Nice find, @SomeHardwareGuy...

You can do that using an Arduino Yun: the Yun has a linux cpu paired with the ATMega32U4, so you can delegate things like accessing a mysql database, either local or remote.
Take a look at this instructable.
There are different ways for delegating logging sensors readings to the linux side and have them stored on a mysql: the easiest is to code a short python script and call it from the sketch using Process.


text:
Can the Arduino use this i2c LCD Panel
Can the Arduino Mega2560 use the New Haven NHD-0420D3Z-NSW-BBW-V3 LCD panel by controlling it with the New LiquidCrystal library? What cable will you use to connect the LCD to Arduino, are there screw terminals on the LCD board to secure the connections? It seems like only 4 connections are needed, for GND, VCC, SDA, SCL.

The I2C in that library is expecting a IO expander ASIC. The display you use requires different I2C commands. Better look around for a different library.

Unfortunately you cannot control that display using that library; the library expects to be connected to a HD44780-compatible driver but the display uses a fully custom control scheme. You may be able to adapt the library to the scheme, but I have not looked at that specifically.
I2C itself only requires 3 connections: SDA, serial data; SCL serial clock; GND, ground reference. Since the display is not powered separately it also requires power, in this case 5V. Since the display can only communicate at 100kHz you don't need to be too terribly concerned about cable quality; Cat3 or even telephone cable is acceptable as long as you don't exceed a few feet in length. Don't forget the external pullup resistors though, on SDA and SCL.


text:
Using PBC library on Arduino
I want to know if there is a way to install/use the PBC library on Arduino UNO. I want to implement some cryptographic primitives using PBC library.
Thank you.

GMP could be very painful to get working on something as small as the ATmega328P.

Anyway, I want to know how to do it

Hello Miss Jéssica Carneiro, Could you tell me "Is it possible to install PBC library on Arduino ?"

You could use the RELIC toolkit. It has PCB and they have scripts to compile for Due and Mega. I'm not sure if you could use this with Uno. But this library targets resource-constrained devices.


text:
Read data from 3 ColorPal 28380 simultaneously on Uno/Mega
I've been trying to get an Arduino (I have a Mega and Uno lying around) to read values from a small array of 3 ColorPal 20380, which individually, work as intended with some reflective material. The demo gives no problem, but I am confused as to how to approach activating all the 3 sensors and reading the 3 different sets of values so that I can analyze them in a program on the Arduino.
How can I get all three sensors to output data to my program in parallel? I want to use the values at the same point in time on all three sensors to do some calculations in my program. Should I approach something like a state machine? Or at least near-parallel (a few ms delay is fine too)? How would an example look like?
The most confusing thing for me is the non-inverted, open-drain protocol it uses. From the documentation:

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

I tried modifying the demo to something silly in sequence like this just to see how it would work in the Arduino but I got nothing (pins 2, 4 and 6 are the data pins):
/* ColorPal Sensor Example for Arduino
  Author: Martin Heermance, with some assistance from Gordon McComb
  This program drives the Parallax ColorPAL color sensor and provides
  serial RGB data in a format compatible with the PC-hosted
  TCS230_ColorPAL_match.exe color matching program.
*/

#include <SoftwareSerial.h>

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

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

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

void setup() {

  // Unoptimized setup

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

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

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

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

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

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

void loop() {

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

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

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

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

void readData() {
  char buffer[32];

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

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

I don't think you can reinitiate SoftwareSerial several times. Try using variable like e.g. serin1, serin2, serin3 and serout1, serout2, serout3 and (only) initiate them before setup() to make it easier, try getting only one to work first. Then later add the other two.

So looking around the SoftwareSerial library, it is impossible: "It is possible to receive on two different SoftwareSerial ports in the same sketch. You just have to take some care that you aren’t trying to receive from both simultaneously. There are many successful designs which, say, monitor a serial GPS device for a while, then later accept input from an XBee. The key is to alternate slowly between them, switching to a second device only when a transmission from the first is complete." Source

I will try to learn how to use the AltSoftSerial (Apparently this instead for the Uno) since the author says that it can work in parallel instead, but disables a few pins.

You could try using 2 pins, instead of one. One for the RX and the other (via a transistor) for the TX. You'd have to filter out the TX data also coming into the RX pin.

@Gerben Could you explain to me how and what hardware I'd need to wire it using two pins? I have very limited electronics experience, to be honest. Most of this project is a learning experience.

Like I said, just a simple transistor. TX pin on the arduino, via a (±1k) resistor, to the base of a regular transistor; emitter to ground, connector to the shared TX/RX line; connect the RX pin to this same line. Though I'm not entirely sure if it works. I too am still a bit new to this.

I'm also having issues in reading color from 2 colorPal sensors with Arduino. Could you please update if you made any progress?

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

I'm also a novice when it comes to electronics, so we're on the same boat. I've delved a little deeper into the comms scheme, and noticed this sensor uses a 1-Wire communication scheme or "the non-inverted, open-drain protocol" mentioned, which seem to use normal GPIO with that OneWire Arduino library. But this demo code uses the SoftwareSerial library instead, which seems to have its own complications, including only receiving one stream of data at a time. The Setup part is a fair point though.

That said, the Arduino Uno seems to have only two native UART pins (pin 0 and 1), so it seems that having three or more will have to incur at least using some other sort of pin and a library for the communication scheme. I'm looking into the aformentioned OneWire for Arduino and see if I can come up with something...

Try using serin.listen() for each SoftwareSerial before using serin.read().
Only one pin can be read at a time and by default it's reading from the last pin initialized.


text:
Assuring an unsigned long int?
Basic question: How far do I have to go to assure that integer math is done correctly? For example, this is probably overdone:
unsigned long burnTime = 0UL;
unsigned long curBurnTime = 0UL;
// Do some stuff that sets the above variables to millis() at various times
// Later on...
unsigned long adjustedBurnTime = (unsigned long) ((burnTime + curBurnTime) / 1000UL);

Would the math be done correctly if I went to a more minimal last statement (since all the elements of the equation are unsigned longs)? Like this:
unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000UL);

Or even:
unsigned long adjustedBurnTime = ((burnTime + curBurnTime) / 1000);

Only one way to really find out! Compile them both and disassemble them.

@IgnacioVazquez-Abrams either that or read through the GCC compiler code. :) Printing output to serial is, of course, the easiest!

If argument of math operation is unsigned long then it should be calculated in long precision and potentially shortened when assigned. I.e.second case should be ok. But double checking in assembly is the best choice how to save time when provides strange results.

This issue is very relavent to time; check out http://playground.arduino.cc/Code/TimingRollover it outlines the same issue. Where I would agree with TMA, in that since all are casted the same, it is not needed. However, I always play it safe. In case the casting was changed.

Thanks for the thoughts. I'm not savvy enough to check the assembly code so I'll try the serial output route. @mpflaga, I agree better safe than sorry. I was just hoping to be (safely) a little less redundant in my code but why take a chance, I suppose. Since I'm tracking runtimes it will be an issue.

I compiled all three of the examples above and the result was three identical hex files. Unless I'm missing something it seems I've answered my question. ...Am I missing something?

No, your're not; the hex file exactly represents your code (plus some loading instructions). If two hex files are identical, and presented to the same loader, the results (the memory loads) have to be identical.

Any good C manual will tell you the result type for each basic math operation on given types. But briefly, the basic math operators return a result as wide as the widest operand, with the narrower operand being widened to match the wider one, if they differ. The same with assignment: assigning a result of a given type to a variable of the same type will not involve any conversion.
tl;dr: No, you're not missing anything. You don't need any casts in your example.
PS: One thing you do need to be aware of is whether any of your intermediate results will overflow the arithmetic type you're using. For example, the final result may be not exceed an unsigned long but the expressions (burnTime + curBurnTime) must also not exceed it. This is a greater concern with smaller data-types, of course.
PPS: Good on you for tackling fixed point arithmetic rather than just reaching for the floating-point library!

Thanks, that's a great answer because it explains not just whether but why. My uninformed guess would have been the opposite. Also very appreciative of the warning on intermediate results; it would have been just a matter of time until that bit me.


text:
How can I implement double buffering with an Arduino UNO?
I am creating a tiny game on my Arduino UNO with an Adafruit ST7735 1.8" TFT / SD breakout. I am performing screen operations using the built-in TFT-library.
The problem is screen flickering. Even though I take care to prepare data and minimize the time between clearing the screen and writing the new stuff to it, the screen "refresh()" is significant. I heard someone mention something called double buffering, so I read a bit up on it, but I am frankly clueless on how to implement it on an Arduino UNO.
Is it possible to implement double buffering on an Arduino UNO to prevent screen flickering, and if so, how?
Libraries used:
#include <TFT.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

The screen is "cleared" like this:
screen.background(0,0,0);  // Clear it
screen.text(buf, 10, 25);  // Write new stuff

If you're already preparing the next screen's-worth of data before you clear the screen, then double buffering won't help. In that case, the time taken to re-write the screen data is what causes the flicker, and the only way to improve it is to write the screen faster. If the software is to blame, it will be in screen.text(). If the software is already driving the hardware as fast as the hardware will go, then that's the best you can do.
Double-buffering would let you prepare the next screen while the currently-prepared one is loading (and will require interrupt-driven I/O to do it). The result would be more screen refreshes per unit time, but it doesn't sound like that is your problem.
One easy experiment to try is to not clear the screen before you re-write it, if that is possible to do. Then your next screen will overlay the current screen with (we hope...) no blanking period. That might prevent the blinking.

How can I implement double buffering with an Arduino UNO?

Full screen double buffering (aka off-screen bitmap) for an ST7735 (128 x 160 x 16 bit color) would require 40 Kbyte. With only 2K byte SRAM on the Arduino Uno double buffering is not possible.
Some of the flickering is due to the Arduino core unoptimized SPI protocol and the graphics library. They could be optimized to reduce some of the flickering.
Please see the Cosa ST7735 driver and SPI support for examples of high speed inter-leaving SPI transfer and graphics optimizations.
Smaller mono-chrome screens (such as ST7565) can be supported with double buffering. An example is the Cosa OffScreen Canvas that can be used to create a bitmap that is transfered to the screen in a single operation.
Cheers!

Arduino Due has 40k RAM to spare, but I don't see how that solves the issue of the screen flickering as you will still need to transfer the data to the display controller, meaning you will still have to watch the screen slowly update and for complex contents the screen will spend much more time while updating is in progress than it will be displaying the desired final contents.

@VioletGiraffe Most Arduino graphics libraries use pixel level update and draw directly to the display memory. They do not use a off-screen bitmap and then transfer in a single operation. The transfer can be synchronized with the display to avoid flickers. See chap. 9.11 in the ST7735 datasheet, https://www.displayfuture.com/Display/datasheet/controller/ST7735.pdf

Interesting, thank you very much for responding, I want to investigate the possibilities of of some sort of partial buffering / transfer batching.
It's a shame that none of the popular controllers (ST7735, ILI9341, SSD1963 etc.)  support indexed 8-bit color palettes. 256 colors is more than enough for most embedded applications, and having 8-bit pixel values would mean that each of the controllers I mentioned can already store at least two full sets of image data.

To add to previous answers:
Double-buffering is an approach where you write to the actual device - but in an off-screen area. Then you switch to the new area in a single instruction, indistinguishable to the naked eye, rather than clear the visible area and write while it's still being displayed.
This requires that the device has extra memory to support the two areas: on-screen and off-screen. Absent that extra memory, then the best that you can do is pre-calculate as much as possible, and write to the screen as fast as possible.


text:
How to split in string
I want to split this:
char* value = "12;32;blue";
or
string value = "12;32;blue";

into this vars:
TV = 12;
AR = 32;
LED = "blue";

is it possible?

For C-strings (char*), your best option (in terms of performance and memory consumption) is to use strtok:
char* value = "12;32;blue";
char* token = strtok(value, ";");
int TV = atoi(token);
token= strtok(0, ";");
int AR = atoi(token);
token = strtok(0, ";");
char* LED = token;

Note 1: the code above takes it for granted that value is properly formatted, i.e. contains 3 parts split by ;. If it is not sure, then you should add additional checks on token value returned by strtok.
Note 2: strtok is modifiying its value argument, so that at the end of the code above, value will not be equal to 12;32;blue any longer.
Note 3: LED variable above will point directly to the character b inside value, which means that if value is modified afterwards, LED might be modified as well.

Scan function should do the job.
int tv, ar;
char color[10];
sscanf(value, "%d;%d;%s", &tv, &ar, color);

That's a great old trick. I totally forgot about it! https://www.daniweb.com/software-development/c/code/216535/parsing-a-string-into-tokens-using-sscanf

I think you meant sscanf not scanf as the latter needs stdin which Arduino doesn't have. Also in your example you shouldn't pass &color, but rather color.

and where do i tell the sscanf to get val from my var 'value' ?

@Thiago: as first parameter. Corrected.


text:
Measure Water Flow in literes using Arduino Mega 2560 Board and Water Flow Sensor
I have a water flow sensor with Arduino Megs 2560 board. I am trying to conceptualize the concept to calculate amount of water getting dispensed esp. in 1,2,3,4 and 5 liters quantity.
Water flow sensor specification:
http://www.seeedstudio.com/wiki/images/b/b7/Water_flow_sensor_datasheet.pdf
I would connect the sensor input to any pin from 22-53 pin.
Suppose I connect to ping 23 so in my setup() function I would add:
attachInterrupt(23, pulseCounter, FALLING);

where pulseCounter is an interrupt function triggered on each signal generated from sensor and increments a variable
void pulseCounter()
{
  // Increment the pulse counter
  pulseCount++;
}

Now how do I calculate the flowrate and water dispensed in milliliters using this information?  How do I know the freqz of the MCU (which is required as water dispensed per pulse is different for different MCUs)?

If your sensor really gives pulses/second, the water amount per second must be constant, i.e. the water pressure must be constant, because the pipe diameter is surely constant. Otherwise there's no way to calculate the volume. I'm quite sure this is not the case, but your sensor gives a certain number of pulses per volume. Am I right? Would you share the sensor datasheet with us?

Sorry it would be pulses per volume of water,. I have updated the question accordingly

the pulse rate can be derived without knowledge of the CPU clock speed. To achieve the pulse rate from your sensor input you can do two things:

count the pulses dn within a certain (i.e. fixed) interval T of time) or
measure the time dt between two pulses.

I'll come back later on this concerning accuracy.
To measure time, you can use the function millis(). This function returns you the milliseconds since bootup as an integer upon calling it. Method 2 is rather simple to implement.

Setup three global integers a, b and c.
At the end of setup set a to current millis();
In your ISR set b to current millis();
Also in ISR: set a=b;
calculate c=b-a (i.e. your dt);

c holds your current full wave pulse length in milliseconds, which is updated every pulse. You can derive your flow then from it.
The first method uses a counter as demonstrated in your suggestion. You then need a timer outside your ISR, two variables d and e. Either you poll millis() in your main "loop()" or you install a timer interrupt, both will work here.

At the end of setup set d to current millis();
If your predefined time T is passed (by comparing d with millis(),
save your counted pulses to e=pulseCount
reset: pulseCount=0

e holds your pulse count during interval T, from which you can derive your pulse rate.
Accuracy
Method 1's accuracy increases with higher T and higher flow speeds. Therefore the update rate of your measurement is low. By changing T you can easily increase accuracy on cost of responsiveness. This is perhaps a good idea, if you have pulsating flows in your tubings, or the sensor is a bit rattling.
Method 2's accuracy increases with lower flow speeds. It is best to measure very low flow speeds. Update frequency is minimal (1/dt).
Regarding this sensor you should calibrate it yourself. It is a cheap and rugged device (I'm using it, too), but its output depends on several parameters like mounting position, fluid viscosity and so on. Make sure, there are no bubbles, foam or contaminants in your fluid systems as they garble the results effectively.
n.b.: make sure to take care of an overflow of millis().


text:
Proto Shields wthout breadboard?
I want to use a proto shield (brand is unimportant) and solder some components to it, to make something more premanent than using a breadboard.
My question is can the components be soldered directly to the middle area where there are a lot of small holes?
I would assume this is possible, but everywhere I look people add mini breadboards to their proto shields.
If it's possible, then I assume components and wires can't just be connected in a row like on a breadboard and would instead need some solder between 2 holes where for example a component and seperate wire are connected?

You are completely right there. Just note that some proto-shield have some interconnected rows, just like a breadboard. But you can easily see that (example)

Thanks Greben. Would upvote and accept if you posted as an answer. :)

There are many different types of photo-shields, sometimes they have interconnected rows or they just have individual solder holes or even breadboards.  What you get all depends on what you are doing.  My personal favorite are the interlocked rows so I buy that and use a breadboard while I am developing my project then take off the breadboard and solder everything into place.
Example of non interlocked rows  and an My favorite proto-shield, it has a little of both kinds


text:
Custom Library Pin Change
I'm using an Arduino Uno with Funduino I2C 1602 LCD display. The LCD display is connected as
LCD
SCL--> A5
SDA -->A4
I need to measure the temperature, pressure and the velocity of a duct flow. So I connected a BMP180 to my arduino with the following connection
SCL--> A5
SDA -->A4
As you can see, both of them are connected to same pins. The connection works fine just for BMP180 but when I add a rotary encoder and print its value on LCD, I'm getting delayed and wrong data.
I'm using this BMP180 library
https://github.com/adafruit/Adafruit_BMP085_Unified
The LCD uses this library (v1.2.0)
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads
how can I change bmp180 or LCD analog pins in these libraries?

You can have multiple devices connected to the same I2C pin (A4,A5). So both devices worked till you connected the rotary encoder? What pins are the encoder connected to?

actually, I think I'm having a coding problem. Encoder is connected to digital pins so there is no problem with it.


text:
Dead reckoning with an accelerometer
Is it possible to use an Arduino, connected to a 3 axis accelerometer, to estimate a platform's continuous change in position and orientation? I have a small mobile robot, and given an initial position and velocity vector and sequence of acceleration changes, I'd like to calculate the current position and velocity vector.
From this question, it sounds possible, but I can't find any reference to projects or code to accomplish it with an Arduino. I understand the main problem will be the build-up of errors over time, but that's ok, as a rough estimate is acceptable. I'm also using wheel encoders to calculate the same values, and I want to use the accelerometer to account for errors in the encoders, like slippage. e.g. If the encoders say we're accelerating at 1cm/sec but the accelerometer says we're at a constant speed, then I know to ignore the encoders because the wheels are probably slipping.
I understand the math behind this, so the problem is how to write it in C to run on an Arduino. Is anyone aware of existing open source code for something like this? I'd like to avoid reinventing the wheel in-case anyone's implemented a similar system.

for each accelerometer:
   sample the accelerometer;
   low-pass filter its values (current and recent history) to remove noise;
   multiply by the sample interval to get the velocity increment;
   add the increment to a running sum to get velocity;

   sample the velocity (the running sum you just updated);
   maybe low-pass filter, as above;
   multiply by the sample interval, as above, to get the position increment;
   add the increment to a running sum to get position;
end;

Noise, the artifacts created by filtering, and the double summation all work against your accuracy. That said, if your problem is to sense traction or loss of it, how about sensing real velocity more directly such as by dragging an encoded but otherwise free fifth wheel? Or if circumstances allow, optically sense the velocity of the surface underneath you as an optical mouse does?

using the midpoint rule when multiplying by the sample interval will help a little bit

I considered the optical approach. It's still tricky. A hacked optical mouse sensor has a simple interface, but will only work when very close to very flat surfaces. A cheap USB webcam could be used instead, but then you need a beefy processor to calculate optical flow, which an Arduino isn't really suited for. And extra wheel would be cheap and simple, but would be mechanically cumbersome and awkward. An accelerometer is small, relatively cheap, and can be easily accessed by an Arduino.


text:
How do you benchmark an Arduino?
I am trying to run a test of the speed of an Arduino, and how it's affected by different temperatures. Does the following code assess this properly?
long num = 0;
long startTime = 0;
long endTime = 0;
int duration = 0;
String buffer;

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

void loop(){
  startTime = millis();
  benchmark();
  endTime = millis();
  duration = endTime - startTime;
  Serial.print(startTime);
  Serial.print(", ");
  Serial.print(endTime);
  Serial.print(", ");
  Serial.println(duration);
}

void benchmark() {
  num = 0;
  for(num = 0; num < 1000000; num++);
}

I'm using an Uno, if that matters.

Is there a particular reason why you're doing this?

I have an idea. An Arduino with GPS and real time clock, using this https://www.sparkfun.com/products/10710 . I'd replace for millis.

Thank you everyone for helping. I will post my results when the trials are completed.

No.
That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.
Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).

Would it work to use a serial output to a PC, and having it measure the interval?

Maybe. But how precise is you PCs clock? How does Serial.print() affect your benchmark? What is the latency of the serial connection (I don't think you have a realtime OS)?

It doesn't have to include Serial. I'd just like to know how fast the Arduino is running, so I can determine the difference temperature makes.

20ppm is only a 0.002% difference. You'd need some pretty precise instruments to measure this tiny difference.

Ah, I see. I only need to be precise enough to see there is no large difference.

"Large" is relative. 20ppm is about 10.5 minutes over an entire year.

But then you'd have to have a constant temperature during this entire period :-)
What is it you want to achieve with the results? You can just look at the datasheet of the crystal to get an idea of what the difference would be.

I really just want to measure real world performance.

Quite simply, you cannot measure the stability of a device using routines that themselves depend on the device clock.
To do this properly you need an external measuring device that has a clock source at least 10 times more stable than the Arduino xtal. Most frequency counters would qualify.
Just set up a timer to provide a constant output frequency, and attach the counter to the pin.

First of all, compiler will just remove your loop, unless you disable compiler optimization, witch will invalidate your test.
Also don't worry about clock drift; as clock also run instruction, a faster clock will also mean a faster instruction cicle, so in the end if you calculate instruction/s the value will be valid.
Also serial communication slowness is not a problem as you calculate the value BEFORE sending anything.
Now, exactly what you want benchmark? In your case, you should put some instruction the for, like a variable++, and then print that sum (if you don't use it, again compiler will optimize all away)
But the you are bancharking for and ++. You may use a NOP() instruction, and then a float, a bitshift, a function call, and so on; you will find very different result, sometimes, sometimes compilator will trick your code.
Then when you'll have banchamark, against what will you compare your result?

Thanks for the answer. I'm not going to compare it to another device, but instead just graph speed vs ambient temperature.

Whoa missed that. Basically you want measure the clock drift, witch means you need to find a more precise clock. As far as i know there are very expansive thermo compensated clock. Pc clock may drift lot, they need to output fast clock, its stability may have relatively great error


text:
MHz Sampling Rate for Arduino
How can we increase the Arduino's ADC sampling rate to 1 MHz while maintaining a 10 bit resolution? Can we change the prescaler to 16 to get 1 MHz ADC clock?
If not, what alternatives are there? Another Atmel chip that works with the Arduino library? Or any external ADC?

Arduino and Atmel are completely independent; that Arduino has chosen Atmel devices is more serendipity than anything else.

The problem with driving the ADC faster is that the S+H circuit won't have enough time to reach the final value before the conversion is performed, meaning that precision will be lost.
The best thing to do would be to use an external ADC from e.g. TI or Microchip that has the capabilities you're looking for.


text:
Arduino GSM shield GSM_READY not ready ever
I am using an Arduino Mega and an Arduino GSM shield. I am using the receive SMS example under GSM in the Arduino IDE. My GSM shield's hardware IP is set correctly.
Here is the sketch:

/*
 SMS receiver

 This sketch, for the Arduino GSM shield, waits for a SMS message
 and displays it through the Serial port.

 Circuit:
 * GSM shield attached to and Arduino
 * SIM card that can receive SMS messages

 created 25 Feb 2012
 by Javier Zorzano / TD

 This example is in the public domain.

 http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

*/

// include the GSM library
#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess;
GSM_SMS sms;

// Array to hold the number a SMS is retreived from
char senderNumber[20];

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("SMS Messages Receiver");

  // connection state
  boolean notConnected = true;

  // Start GSM connection
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
      notConnected = false;
    else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

void loop() {
  char c;

  // If there are any SMSs available()
  if (sms.available()) {
    Serial.println("Message received from:");
    // Get remote number
    sms.remoteNumber(senderNumber, 20);
    Serial.println(senderNumber);
    // An example of message disposal
    // Any messages starting with # should be discarded
    if (sms.peek() == '#') {
      Serial.println("Discarded SMS");
      sms.flush();
    }

    // Read message bytes and print them
    while (c = sms.read())
      Serial.print(c);
    Serial.println("\nEND OF MESSAGE");

    // Delete message from modem memory
    sms.flush();
    Serial.println("MESSAGE DELETED");
  }
  delay(1000);
}

The issue is this line:
if (gsmAccess.begin(PINNUMBER) == GSM_READY)

The serial monitor outputs everything until that line.
It just never gets past it, so I assume it cannot connect? The SIM has no pin code: I have tried it with my phone. The SIM has full signal strength when in my phone. I have tried my other SIM card also but the same thing happens.
This seem to be the same question, yet no answer:
http://forum.arduino.cc/index.php?topic=270551.0

I have the same problem. Did you fix it and if yes, how did you do? It's been a few days and still didn't find a way to fix it.

You could always try setting a pin code and then retry
http://arduino.cc/en/Tutorial/GSMToolsPinManagement
What version of the Arduino IDE are you using ? Also, are you sure you are suppying the board correctly ? "It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use."

I Have The Same Problem.
But First Of All you have to set your modem Network Band according to your cellular Network Band.
GSMBand band;
String newBand= "GSM_MODE_EGSM_DCS";// Your Band In My case That was
  band.begin();
  Serial.println("Modem restarted.");
  String bandName = band.getBand(); // Get and print band name
  Serial.print("Current band:");
  Serial.println(bandName);

band.setBand(newBand);

Band Help:
  GSM_MODE_EGSM                ---- E-GSM(900)
  GSM_MODE_DCS                 ---- DCS(1800)
  GSM_MODE_PCS                 ---- PCS(1900)
  GSM_MODE_EGSM_DCS            ---- E-GSM(900)+DCS(1800) ex: Europe
  GSM_MODE_GSM850_PCS          ---- GSM(850)+PCS(1900) Ex: USA, South Am.
  GSM_MODE_GSM850_EGSM_DCS_PCS ---- GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

Then You Have To use
gsm.access.begin();

I had the same problem. Then I used gsm.shutdown(); before gsm.begin(PINNUMBER). After that it goes past gsm.begin(PINNUMBER) but not always. I don't know if this is the right way to do it, but it works for me.


text:
Arduino works bad when powered by 9V battery
At first I am sorry for my bad English.
I am making robot which can do a lot of things...
If I connect arduino on my robot with PC via USB, the robot works properly. If I use external power supply (9V battery) the robot is doing almost nothing.. The diodes are little bit blinking and sometimes dc motors make motion... And thats all. Batteries are charged. Where's the problem?
Everything I want is make into motion dc motors.. With 5V USB it works. With external power supply not (9V battery).

9V batteries are crap for anything that needs any real amount of current.

Does it really show you 9V? If it is written on side it doesn't mean it's 9V

Yes, It really has 9V. I have 2 same 9V batteries. One for DC motors and one for arduino. DC motors are working properly with this battery but arduino is not.

probably you were right. If I disconnect all sensors from arduino, the DC motors are making some motion... they're really slow but they are moving.

what I should use instead this 9V battery?

The input voltage of the arduino external power supply needs to be at leased 7,2V or else it will fail. Make sure your battery is providing enough voltage to the arduino.

I got a fresh 9 V out of a packet and measured it.
 9.58 volts

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:
 7.4 volts

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.
And that was with a fresh battery, testing for a few seconds.
Those 9 V batteries are just not designed to drive motors.
I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.


text:
Can I use a spare Darlington Pair on my ULN2003A to drive a DC motor?
I'm successfully running a stepper from my Arduino via a ULN2003A and a secondary power supply. It uses the first four of the seven Darlington Pairs on the chip, leaving three spare.
A) Is there any reason I wouldn't be able to use one of the remaining pairs to drive a standard DC hobby motor? (For the sake of helping future visitors .. what about running three motors off the remaining three pairs?)
B) Do I need anything other than to connect the motor to the chip? (The chip's board has LEDs and resistors on each of pins 1 - 4, but I don't believe they're in series and thus my guess is they can be left off.)
C) The DC motor is on a PWM Pin. Is that the correct way to control its speed?
The image attached shows the setup in case I haven't been clear.

(I could probably just build it and see, but I'm new to Arduino and still scared of the blue smoke if I get something wrong!)

Low karma on this SE. Suggest adding tags: "ULN2003A" and "Darlington"

Is the COM connection of the chip available anywhere?

@IgnacioVazquez-Abrams: Yes, I believe the COM of the chip is the GND pin where the black wire connects it to the negative rail

I hope not, because that's not what it's for at all.

Also, what piece is that and why aren't you using a schematic?

@IgnacioVazquez-Abrams: The piece is this: http://www.lctech-inc.com/Hardware/Detail.aspx?id=f8364b6f-346b-48dd-af91-0fed4d56dd6c .. and I'm not using a schematic for it as I can't find one. And because I'm relatively new to this. I made my own Fritzing part for it.

Should work just fine. But you'd have to connect the motor to the positive rail, and since the ULN2003 can only sink current.
Normally when connecting a motor, you'd add a flyback diode. But the ULN2003 already has those inside the chip.
PWM is the easiest way to (somewhat) control the speed of a DC motor.

So I should just move the black wire connecting the yellow side of the motor from the ground to the positive?

Yes, assuming the motor isn't polar. (otherwise, purple to positive, black to the ULN2003)


text:
Not in sync: resp=0x00
I had problems with Arduino uno and reseted firmware. Followed this tutorial. Now I can't upload my code Arduino IDE says:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

I tried loop-back mode, everything is fine.
Firmware was located in this location:
/usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

It looks like you changed the bootloader which would change the behaviour of arduino ide (ie there is no arduino bootloader to connect it to). You might want to look into reflashing the bootloader.

Can't you tell me how to do that?

Writing bootloader from Arduino IDE throws the same error

I was talking about the actual software that arudino uses to load up the code see here http://arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader  It would help if you have another arudino to work with

There are two processors on the Uno board.

The Atmega328P which is the "main" processor with your sketches on it
The Atmega16U2 which handles the USB interface

Firmware was located in /usr/share/arduino/hardware/arduino/firmwares/atmegaxxu2/Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex

Hopefully you reflashed the Atmega16U2 with that file. Did you?

I tried loop-back mode, everything is fine.

Therefore the Atmega16U2 is OK. The problem may be with the Atmega328P.

I had problems with Arduino Uno and reseted firmware.

You shouldn't need to do this, I never reflash the firmware on my Atmega16U2.
What problems did you have? Did it involve motors? LEDs? High voltages? Sparks? Flames? Screaming?
Please see the steps described here, run through them, and see if that fixes the problem: Have I bricked my Arduino Uno? Problems with uploading to board


text:
Arduino hangs after 3-4 minutes on battery power, but not on USB
I have a simple sketch running on a BE Leonardo-compatible board.
It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.
Other than that, the only code is serial I/O for debug purposes.  (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)
When the board is powered by USB, everything works.
When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength.  (There is nothing connected to pin 13.)  Even the reset button doesn't work.
If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.
Can anyone offer a possible explanation for (and solution to) this fault?

If I could I'd offer a bounty, because I need this thing running as a prop tomorrow night.  Since I can't, I offer my heartfelt thanks to anyone who can help. ;)

Try using a AA battery pack instead of a 9V. Or parallel 2 9V batteries together (not in series!). 9V batteries can't provide that much current. So your project is probably drawing near it's limit. Then after a few minutes the batteries voltage drops too low for the arduino, which resets. This continues starting, resetting will explain the board led flickering.

@Gerben: Ah.  That will be it.  The draw should only be about 120ma (2 RGB LEDs), but perhaps the battery isn't fully charged.  (For comparison, the same battery has run a project involving 2 2.5in 7-segment LEDs and a medium size servo for several hours... so I simply hadn't thought of it drawing low from 2 LEDs, even RGB ones.)
(Heads off to try to figure out where he can fit in more batteries withot making a noticeable problem...)

Could yo post the simple sketch so that we can check it cannot be the source of your problem?

As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.
Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.

Yep, this was it.  (Unfortunately there was a reason for the 9V battery, and it was battery pack space, so the obvious solutions are not an option... but I can manage 2x9V parallel, and recode for power saving.)

Instead of the second 9v, use a more efficient switching regulator.  Also consider if you can make your application work at a slower clock speed and reduced voltage, or sleep your processor when it is not doing useful work.


text:
Arduino Serial buffer
I am trying to write one code that takes data from serial
ie. 0x4E, 0x20, 0x--, 0x0D.
0x-- may be any hex in --
The user will input these hex one by one and raspi will take all of them in buffer.
Whenever 1st, 2nd and 4th data is matched, the 3rd one will be printed in serial
ie.
Serial.print(3rd); //Decimal value
else Serial.print() // may be 00

I was trying with this code:
byte buffer[4];
int cnt = 0;

void setup()
{
 Serial.begin(9600);
 Serial.println("Start");
}

void loop(void)
{

 // read max 12 bytes
 if ((cnt <= 4) && Serial.available()) buffer[cnt++] = Serial.read();

 if (cnt == 4)  // all bytes read...
 {
   // assume the arrays are the same
   boolean same = true;

   // the ans array holds the right answer
   byte ans[]={0x4E,0x20,0x01,0x0D};

   for (int i=0; (i<= 4) && same; i++) same = (buffer[i] == ans[i]);

   if (same)
   {
     Serial.println("Yes");
   } else {
     Serial.println("Enter another number");
   }
   Serial.flush();
   cnt = 0;
 }
  //Serial.print("Done");
 // do something
}

But I was not able to do it. Anyone have a suggestion?
Edit: I have tried this state machine in Arduino :
It accepts those data and according to it, it should bi color LED light. But not working properly. Not lighting up anything
//int currState;
//int reChk, data, confirm;
const int pingPin = 13;
int inPin = 12;

void setup()
{
  Serial.begin(9600);
    // initialize digital pin 13 as an output.
  pinMode(32, OUTPUT);
  pinMode(34, OUTPUT);

  digitalWrite(32, LOW);
  digitalWrite(34, LOW);
  //currState = 0;
  //reChk = 0;
  //confirm = -1;

}

void loop() // run over and over
{
  static int currState = 0, reChk = 0, confirm = -1;
  int data;
  if(reChk == 0)
  {
    //ultrasonic();
    if(Serial.available())
    data = Serial.read();
    else
    currState = 5;
  }

  switch(currState)
  {

    case 0:
    reChk = 0;
    if(data == 78)
      currState = 1;
    else
      currState = 0;
    break;

    case 1:
    reChk = 0;
    if(data == 32)
    currState = 2;
    else
    {
      currState = 0;
      reChk = 1;
    }
    break;

    case 2:
    reChk = 0;
    switch(confirm)
    {
      case -1 :
      confirm = data;
      currState = 3;
      break;
      case 0 :
            digitalWrite(32, LOW);
            digitalWrite(34, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      case 1 :
            digitalWrite(34, HIGH);
            digitalWrite(32, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      case 2 :
            digitalWrite(32, HIGH);
            digitalWrite(34, LOW);
            delay(10);
      confirm = -1;
      currState = 0;
      break;
      default :
      confirm = -1;
      reChk = 1;
      currState = 0;
    }

    case 3:
    reChk = 0;
    if(data == 20)
    {
      reChk = 1;
      currState = 2;
    }
    else
    {
      confirm = -1;
      currState = 0;
    }
    break;

    default:
    reChk = 0;
    currState = 0;
    confirm = -1;
  }
  delay(10);
}

void ultrasonic () //ultrasonic
{
      const int pingPin = 13;
      int inPin = 12;
      //raw duration in milliseconds, cm is the
      //converted amount into a distance
      long duration, cm;

      //initializing the pin states
      pinMode(pingPin, OUTPUT);
      //pinMode(greenLed, OUTPUT);
      //pinMode(redLed, OUTPUT);

      //sending the signal, starting with LOW for a clean signal
      digitalWrite(pingPin, LOW);
      delayMicroseconds(2);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(5);
      digitalWrite(pingPin, LOW);

      //setting up the input pin, and receiving the duration in
      //microseconds for the sound to bounce off the object infront
      pinMode(inPin, INPUT);
      duration = pulseIn(inPin, HIGH);

      // convert the time into a distance
      cm = microsecondsToCentimeters(duration);

      if(cm > 50)
      {
      //printing the current readings to ther serial display
      Serial.print("5");
      }
      else
      {
      Serial.print("0");
      }
      //Serial.print("cm");
      //Serial.println();

      //checking if anything is within the safezone, if not, keep
      //green LED on if safezone violated, activate red LED instead
      //if (cm > safeZone)
      //{
      //  digitalWrite(greenLed, HIGH);
      //  digitalWrite(redLed, LOW);
      //}
      //else
      //{
      //  digitalWrite(redLed, HIGH);
      //  digitalWrite(greenLed, LOW);
      //}

delay(1000);
}

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

how are you typing in the values?

4E
then in next input others one by one. it may be in decimal values of those numbers too

as @Kitana said, Serial.read() takes one byte from buffer. If you enter 4E then buffer[0] = 4, buffer[1] = E and so on. Arduino isn't mind reader :))

It's rather unclear that this should have been migrated: although the target is an Arduino, the issue here is entirely generic to any serial-connected system.

actually a bit serial but also related to arduino as well

It's unclear how the users input the hex numbers.
If i assume a simple serially attached terminal the user doesn't enter hex numbers but characters.
As an example when the user types 0, x, 4, E the user has only typed one hex number but already four bytes or characters. Instead the user has to type N, , whatever letter, Enter. (Depending on the OS or terminal you will get "CR", "LF" or "CR+LF" when you press enter)
I'm not familiar with C, but your code seems to have also a coding flaw: The 3rd byte will be checked for equality too. You would need something like:
boolean same = true;

if (buffer[0] == ans[0]) { same = false }
if (buffer[1] == ans[1]) { same = false }
if (buffer[3] == ans[3]) { same = false }

Only three tests not four.

say user gives 78320113
78 = 4E in hex and so on
32 = 20
01 = 01
13 = 0D
one buffer will take this as input. it will check 1st 2 and last the 4th.if match found then Serial.println(the 3rd element ie. theresult will be 01 at serial monitor)
Hopefully I am clear

The users still enters eight characters and not four. Either you take my proposal and convert the hex codes to ASCII characters or you read in eight bytes and compare six of them with their ASCII equivalent. However i'm not shure if we're still on topic for this site.

also break could help stop checking if it was !=

And e.g. FF in decimal is 255 so that is three characters