text:
How to handle multiple input pins at once?
I am relatively new to Arduino platform and not know much. I am working on a Bicycle speedometer with turn and stop indicators.
I am planning on connecting an inductor magnet to calculate the rotation of my front wheel while providing the following services from the same arduino board:

Input horn and turn indicator switches.
Output to turn indicators.
Stop light when one of the brakes is
applied.

While I am sure of how to connect all the sensors, except the magnet, I am not sure how to handle the various inputs and the outputs at once.
I must be able to horn and stuff while the indicator blinks at a regular interval all the while the monitor keeps displaying my speed and distance covered.
Any reference or help would be greatly appreciated.
Thanks in advance.
Bharath. S.

Count rotations in an interrupt.  Monitor user inputs in your loop() whenever you have nothing better to do (which will still be very frequently in human terms).  The blink can be implemented either with a time interrupt or by checking elapsed time in the loop, with tradeoffs each way.

If you're willing to get your hands dirty, try timers. I'm probably going to write a library here soon to do that, so I'll post that if I get around to it. That would help with the blinking the LEDs...

You need a finite state machine. Then you can have code that would typically require delay() but without blocking the loop() while it waits.
Here is a crude class I wrote to do it
stateMachine.h
/*
 StateMachine

 Class to perform some state machine logic on the Arduino
*/

#if (ARDUINO >= 100)
 #include <Arduino.h>
#else
 #include <WProgram.h>
 #include <pins_arduino.h>
#endif

class StateMachine
{
  public:
  // Constructor
  StateMachine(void (*)(void));
  // Functions
  void update(void);
  void nextState(uint16_t, uint32_t);
  uint16_t currentState(void);
  void stop(void);

  private:
  void (*callback)(void);   // Callback to state machine code
  uint16_t state;      // Current state of the machine
  uint32_t delay;      // Delay until state change. Delay of -1 is stopped
  uint32_t timer;      // Timer to keep track of last run time
  uint8_t isRunning;   // Are we running?
  int16_t counter[2];  // Two counters for general use
};

stateMachine.cpp
/*
 StateMachine

 Class to perform some state machine logic on the Arduino
*/

#include "StateMachine.h"

//
// Constructor
//
StateMachine::StateMachine(void (*callbackFunction) (void)) {
  state = 0;
  delay = 0;
  timer = 0;
  isRunning = 0;
  callback = callbackFunction;
  counter[0] = 0;
  counter[1] = 0;
}

//
// Update the state machine
//
// Use in loop()
// Will keep running over and over unless stop()ed
//
void StateMachine::update(void) {
  if (isRunning) {
    if(millis() - timer >= delay) {
      timer = millis();
      //Call the state machine
      callback();
    }
  }
}

//
// Current state
//
uint16_t StateMachine::currentState() {
  return state;
}

//
// Next state
//
void StateMachine::nextState(uint16_t nextState, uint32_t nextDelay) {
  state = nextState;
  delay = nextDelay;
  isRunning = 1;
  //Restart timer
  timer = millis();
}

//
// Stop
//
void StateMachine::stop()
{
  isRunning = 0;
}

Then you need a function with the logic:
void exampleStateMachineCallback()
{
  switch (exampleStateMachine.currentState()) {
    case 0:
      //initialise everything and then got to state 1 immediately
      exampleStateMachine.nextState(1,0);
      break;

    case 1:
      //do something then do state 2 500ms later
      exampleStateMachine.nextState(2,500);
      break;

    case 2:
      //do something then do state 1 500ms later
      exampleStateMachine.nextState(1,500);
      break;
  }
}

Finally in the global variables we join them up
StateMachine exampleStateMachine = StateMachine(exampleStateMachineCallback);

And in loop() we call update all the time
exampleStateMachine.update();
The states implement your logic. For example, state 1 in the above code could be turn on the led, and state 2 could be turn it off. State 0 might prepare some variables. If you wanted the led to start flashing with a button press it might look like
if(digitalRead(LEFT_BUTTON) == HIGH) exampleStateMachine.nextState(0,0);

And if you wanted to stop it:
exampleStateMachine.stop();

In the StateMachine class I put two counters, you could use these to do other timers. For example, to flash a led for 30 seconds it might look like
void exampleStateMachineCallback()
{
  switch (exampleStateMachine.currentState()) {
    case 0:
      exampleStateMachine.counter[0] = 0;
      exampleStateMachine.nextState(1,0);
      break;

    case 1:
      digitalWrite(13,HIGH);
      exampleStateMachine.nextState(2,500);
      break;

    case 2:
      digitalWrite(13,LOW);
      exampleStateMachine.counter[0]++;
      if (exampleStateMachine.counter[0] >= 30) exampleStateMachine.stop();
      else exampleStateMachine.nextState(1,500);
      break;
  }
}

How fast do we need to read the magnetic switch to not miss any pulses? I'll make some working assumptions:

Using 700c wheel and 28mm tire [assumed; adjust as necessary]
Rolling radius 2.1m [from here; there are other ways to arrive at this]
Max speed 22 m/sec (50mph), [working assumption; adjust as you see fit]
Magnet and switch interact for at most 3% of a rotation, [WAGuess]

The wheel will have to turn at ~10RPS at max speed giving a pulse period of 100ms. The pulse width will be at most 3% of that, or 3ms.
Your service loop would have to execute in somewhat less than 3ms, every time, in order to not miss any wheel pulses and that's if I haven't been too optimistic about the pulse width. I'd personally assume a 1ms maximum loop time, then test it on the road by sampling & logging wheel-pulse level with an Arduino at at least 10x that rate or 10+KHz.
Or I'd go with an interrupt-driven wheel pulse period timer not width) to ease the constraints on the main loop.
The main loop need only poll your turn, brake, and horn switches and a timer for blinking the turn signals. Even if the timing is a little erratic for some reason, no harm is done, and nothing is likely to be apparent to the rider or other road users.

Since I apparently can't comment yet, here's an incomplete but I think useful answer; this is a perspective on how I would go about it:
For the brake lights it's pretty easy to just put it in a loop that 'if brakes, brake light on'. I would say keep everything in one loop, no interrupts or anything. If an indicator switch is on, the loop gets the current time with millis(), sets a flag to on, and turns on the light. It then loops like normal, checks the flag and if sufficient time has passed turns off the light, gets a new time, and unchecks the flag. If i understand your needs correctly, the rest is just 'if input high, output high' that you can check every time through the loop. Can't help with the magnet though, no experience there.

Since your post mentioned that you are relatively new to Arduino, in case you have not done below, you may start by
a) get a printed book, ebook or 'well structured' tutorial, says, systematically covering 10 to 20 topics instead of short tutorial on just one topic
b) this will get you covered for your task 1 to 3, but, only as individual tasks.
c) after mastering (b), try to combine them, instead of stand alone in tutorial
d) interrupt is advance topic and not be cover in many starting books. You can see http://arduino.cc/en/Reference/attachInterrupt   Interrupt works only on certain pins, depending on which Arduino board model.


text:
Buy a genuine arduino board or a sainsmart board?
Arduino Day is so popular! Many boards are cheap during arduino day. So should I buy a genuine arduino board or a sainsmart board?

You should get the one that satisfies your requirements.

You should clarify your question and tell what you intend to do with it, so that we get a chance to give you hints on selection...

It looks like they are pretty much identical. So it doesn't really matter.

Buying an official board can be a good choice for a couple of main reasons. First of all, you're guaranteed a good quality board which conforms to the official schematic, and is definitely compatible with any relevant official software and hardware. If the board turns out to be faulty when you get it, you'll be able to get it replaced. Additionally, buying official boards means some of the money you spend goes towards funding future Arduino projects.
As you've no doubt seen, cloned (i.e. unofficial) boards based on Arduino are often much cheaper. Nonetheless, many of the boards are very good. Functionally, you might not see any difference whatsoever from the official/genuine boards. Some of them actually have some additional features which you might find useful depending on your project, such as switching the IO pins between 3.3v and 5v.
However, not all cloned boards are worth using. Some of them may have lower quality components. It's even possible that they weren't designed/constructed correctly in the first place. This could lead to a range of problems, from incompatibilities through to outright failure of the hardware. Given the geographic location of some of the manufacturers/sellers, you may not have any way to get a refund if something goes wrong.
If you choose to use a clone, look for a brand which other people have had success with. Also do your best to ensure the board uses the correct microcontroller (e.g. the Atmega328 for boards based on the Uno).
Ultimately, the decision is up to you. There's no 'right' answer necessarily.

With the current Arduino board, you might be supporting the wrong side, when buying an official board.

Going by the number of complaints seen about Sainsmart assemblies in the Arduino forum, I would suggest original.
You're also less likely to get a "go ask in the Sainsmart forum" reply when you ask for help in the Arduino forum.

source: Stack Exchange

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

sort: votes


text:
AVR ATmega328p-pu operating circuit?
I used to work with PIC micro-controller so i know what it needs to work from operating circuit to crystal oscillators needed and other components to power it up , my question here where can i find the operating circuit for ATmega32p-pu and other AVR models . or all i need to do is to give it +5v and gnd and it will work ?

Just 5v, crystal (with caps), and probably a pull-up on the reset pin. Just make sure you connect all the 5v pins and all ground pins. PS you can skip the crystal if you use the internal RC oscillator. PPS blank chips have their fuses set, so it runs at 1mHz from the internal oscillator. With some programmers you need to select a slower speed, to program the AVR running at only 1mHz.

You're looking for this I think? How to set up an Arduino on a breadboard.

thanks man but not exactly i don't need the complete functions of arduino i just want to power up and make the chip work no more no less

So, just take the bits you need from that page - it  is quite modular.

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


text:
Serial data to arduino problem

I cant understand what is going on here , I was trying to find way to send through Serial a number for example 12 and then extract from it number 1 and 2 and store them in two different variables , but suddenly i was unable to make a simple division !!

Have you read what Serial.read() does?

@IgnacioVazquez-Abrams : yes it reads what ever i send to the serial

@IgnacioVazquez-Abrams meant what datatype it returns.

Anonymous Penguin's code works for me on an Uno after fixing a couple of typos.  It is often best to make sure that both the numerator and the denominator are floats to ensure that the result is also treated as a float.  So please try the following where the 10 is replaced with a 10.0:
while(Serial.available())
{
  float number = (float)(Serial.read() - 48) / 10.0;
  Serial.println(number, 4);
}

If you want to deal with each digit separately an array might be best but that will depend on your end goal.
const int MAX_LENGTH = 10;
char buffer[MAX_LENGTH];
char lineFeed = 10;

int length = Serial.readBytesUntil(lineFeed, buffer, MAX_LENGTH);
int i = 0;
while( i < length )
{
  //do what ever needs to be done to each character here, I'll just convert them to an int and print them as an example
  Serial.println( buffer[i]-48 );
  i++;
}

the point here they are still one number i need to separate them

Okay, let me make sure I understand you.  It sounds like you have two questions, #1 how to make division work properly, #2 how to read multiple characters from the serial port and do something with them.
Have we solved #1 for you?  Would you like to open a new question for #2 where you can describe what you want to read and what you want to do with it?

i didnt ask for Question one , and Q2 is exactly what i need

Do you want to eventually do 12 / 10 or 1 / 10 and 2 / 10? If the second one, you'll have to read all the serial values into an array and convert those characters to their plain integer values (subtracting 48 from each value). After that, you'll have to add them together with the correct placeholders (A * 100 + B * 10 + C).
Basically, the read() function returns one character in the ASCII format. ACII basically representing characters on your screen with numbers. 48 displays a 0 on your screen, 49 a 1, and so on.
You're also facing a problem where your numbers are getting truncated. This means it cuts off the decimal. For when you send 100, it is 48 / 10 = 4.8, however 4.8 becomes just 4. The same thing happens for 49.
To fix this, you need to use a float data type. This allows decimal values. You also want to make sure that the conversion from float to string works correctly for the Serial.print() so you don't end up with 4 again.
Final code:
while(Serial.available()) {
  float number = (float)(Serial.read() - 48) / 10;
  Serial.println(number, 4);
}

I used your code and i send 12 the result is 0.00000.0000 !!

@AbdelrahmanTarief: Did you read the first paragraph of the answer? Do you understand why I commented on the question?

the repeated dots are from different numbers. You need to print a space between printing the digits for it to make sense. 0.10000.20000 is supposed to be 0.1000, 0.2000. 0.000.00 would be 0.00, 0.00.

@AbdelrahmanTarief fixed the code, a few typos.

@AnnonomusPenguin i understand the code i cant deal with each number individuality

@AbdelrahmanTarief what do you mean? Do you want it to be 12 instead of 1 and 2? If so, I already mentioned that in the first paragraph.

@AnnonomusPenguin : Bob Lutz answered me with his code , what i need exactly is to use each byte of the input separately

@AbdelrahmanTarief that is what my code does... in fact we have the same exact code. I'm not sure what you need.

ok sorry i didnt get your code (iam a noob)


text:
What is the best way to get started?
I am interested in learning about arduino.  What is the quickest and cheapest way to find out if this is something I can and want to do?

By an Arduino starter kit and do all the projects. There are components and instructions for 15 different circuits. This is not cheap, but I think it will give you a good taste for electronics.

The starter kit would get you everything you need to do a whole set of projects. Alternatively there is a PDF on the Arduino site with a whole set of projects in it. You could go through it, put together an inventory of the parts you need, and order those parts from an electronics supplier like Mouser, DigiKey, Jameco, etc, and save some money.
The starter kit is probably worth the extra money, though, because it has everything you need, plus an organized set of lessons that teach you the various skills you'll need.


text:
Is there an ICRn CTC mode interrupt vector?
I can use the CTC waveform generation mode to loop to OCRnA and trigger the corresponding TIMER1_COMPA_vect interrupt.
// CTC mode
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B &= ~(1 << WGM13);
TIMSK1 |= (1 << OCIE1A);
OCR1A = 250;

ISR(TIMER1_COMPA_vect) {}

But if I use CTC mode with ICRn as "TOP" is there a corresponding interrupt vector?
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << WGM13);
TIMSK1 |= (1 << ???);    // which interrupt to enable?
ICR1 = 250;

ISR(???) {}              // which interrupt vector?

I think it was TIMER1_CAPT_vect. Have to check when I get home.

It seems I used TIMSK1 |= _BV(ICIE1); ISR(TIMER1_CAPT_vect), but looking at the datasheet, that's not supposed to work. It works, but it's not specified behavior.

@Gerben That works for me too. Can you elaborate on "not specified behaviour"? The datasheet isn't very explicit as far as I can tell.

@Gerben: This behavior is actually specified. It would seem we had both misread the datasheet. :-/

You are right; I stand corrected. Apparently past me is smarter that present me :-)

No, there isn't. But you do have a simple alternative: use WGM 14
(fast PWM with TOP = ICR1). Then the TOV1 flag will be set after
the timer reaches TOP:
TIMSK1 |= (1 << TOIE1);  // enable Timer 1 overflow interrupt

ISR(TIMER1_OVF_vect) {}  // Timer 1 overflow vector

Note that this waveform generation mode behaves very much like the CTC
mode. If you do not set any of the COM1 bits in TCCR1A, then there will
be no PWM output.

Edit: My bad. As noted by Gerben and confirmed by you, the
TIMER1_CAPT_vect can be used, and it is specified in the datasheet,
although maybe not very prominently:
In section 17.9.2 “Clear Timer on Compare Match (CTC) Mode”:

An interrupt can be generated at each time the counter value reaches
  the TOP value by either using the OCFnA or ICFn Flag according to the
  register used to define the TOP value.

In section 17.11.40 “TIFR5 – Timer/Counter5 Interrupt Flag Register”, in
the description of bit 5 (Input Capture Flag):

When the Input Capture Register (ICRn) is set by the WGMn3:0 to be
  used as the TOP value, the ICFn Flag is set when the counter reaches
  the TOP value.

It does actually seem to work with CTC mode and ICRn as TOP, by using the TIMER1_CAPT_vect interrupt.
// CTC mode with ICRn as TOP
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << WGM13);

// enable interrupt
TIMSK1 |= (1 << ICIE1);

// TOP value
ICR1 = 100;

// interrupt at TOP
ISR(TIMER1_CAPT_vect) {}


text:
Why does the battery eliminator connected to the wall provide a better spin to my dc motors than my battery of the same voltage?
Using a H-bridge, I've connected my DC Motors to an Arduino. When I accept the external power source from a wall, using a 9V battery eliminator, the motors spin well and consistently. However, when I connect it to a 9V battery, the motors spin slower, and the speed deteriorates till the motors stop. This happens in approximately 5 minutes. I checked with multiple 9V batteries of the same type. I have tested the batteries to check if they're dead after the motors stop. They are not, and if I reconnect the motors to them, the same process occurs all over again. I have checked for short circuits, and there are none. Any possible ideas as to why this is happening?

Does the battery heat up? If you immediately disconnect then reconnect after running down do the motors go again?

No, the 9V battery does not heat up. Once i reconnect, the motors spin, but still very slow compared to the wall power.

First off, never use 9V batteries to power motors or any device that consumes more than a few hundreds mA. Those batteries are just too weak.
Now a battery eliminator is not a pure equivalent as it can typically supply 800 mA or more, depending on the model you get.
The only commonalities between the battery and the eliminator are the 9V voltage and the socket.
If you want to power DC motors with batteries then rather use several 1.5V batteries in series.

Yes - those 9v batteries are series strings of tiny (smaller than AAA) 1.5v cells, simply use the same idea with larger AA, C, or D cells.

The question is not about volts, but current.
A 9V battery is notoriously bad at powering anything that requires high current, like running a motor. Due to to chemical nature of the battery, the 9V will struggle to keep supplying enough current and will fairly quickly drain.
A regular alkaline 9V block can supply you with 565 mAh, which is not much if you power motors. You'll have more luck with LiPo (lithium polymer) batteries, which are capable of supplying 2200 mAh or more!
To learn more about different types of batteries check out https://learn.sparkfun.com/tutorials/battery-technologies
Wall power can quite easily provide the required current your motors need.

Batteries use a chemical process to produce power. If you draw to much current (motors use quite lot) the chemical process can't keep up and the voltage will drop, resulting in a slower running motor. Try connecting two batteries in parallel. That way each battery only has to produce half the current.

That's not really a good solution.  What's missing from the analysis is that the process you describe - in effect the internal impedance - is very limiting for the 9v "transistor" battery, and it simply should not be used for most motor loads.


text:
Robust communication between Xbee and Python
I am using Xbee API library for Python to process the data received by the Xbee module. I am wondering how to construct the robust protocol for sending and receiving data. What I would like to build is

send the data request message to power monitoring uint (Xbee in remote).
Receive the transmitted power monitoring data and process it in Python.

If the aforementioned process works in just one time, it would be great, but sometimes it does not work. Thus, I would like to code autonomous acknowledging procedure into this communication. That is

send the data request message to power monitoring uint (Xbee in remote).
If the dat is not received, go back to 1.
If the data is received ok.

Here are my code, but it does not work all the time. Would you please look at how can I improve the code further to make it this
def listeningAndClusterData(targetWT):

#targetWT-->this will be used to construct the target address
targetAddress = struct.pack('b',0x00)+struct.pack('b',targetWT)
Data = struct.pack('h',0x0000) #prefix for requesting information
xbee.tx(dest_addr=targetAddress, data=Data)
ser.flush()
time.sleep(0.01)
response = xbee.wait_read_frame(100)#wait for data packet from Xbee, if packet is not recieved within 100ms, return 1

watingData = 1;
while watingData:
    try:

        if response != 1: # if the data is received
            sa = hex(response['source_addr'])
            rf = hex(response['rf_data'])
            datalength=len(rf)
            agentId = int(sa[2:4],24)
            # if datalength is compatible with two floats
            if datalength==16:
                voltage=struct.unpack('f',response['rf_data'][0:4])[0]
                current=struct.unpack('f',response['rf_data'][4:8])[0]
                power=voltage*current
                watingData = 0 # I received the average data and escape the loop
                ser.flush()
            else: #data is received but the format is not correct
                ser.flush()

        if watingData != 0: #if the data is not received--> keep sending the request message to other xbee
            xbee.tx(dest_addr=targetAddress, data=Data)
            print("data is requested again")
            time.sleep(0.01)
            ser.flush()
            response = xbee.wait_read_frame(100)

    except KeyboardInterrupt:
        break

return  voltage, current, power

Why do you flush before you read a frame? Is it not possible to have received the frame before you flushed?
Also how does it fail, is it an error is there sometimes no response from the xbee?

I thought ser.flush() will clear the buffer containing the message sent my xbee.tx(dest_addr=targetAddress, data=Data).I couldn't yet figure it out why the error occurs. Do you have any idea how to wisely use sleep() and ser.flush()?

You can just use xbee.wait_read_frame. The protocol is very fast


text:
How can I set two PWM at two different frequencies?
I'm using the arduino uno hooked up to two LEDs. One is in pin 3 and the other one in pin 5. I know that pin 3 is controlled by timer3 and pin 5 by timer 1. I've tried a lot of things to have two independent frequencies. I really don't care about the PWM, I have it to 50% (constant).
There are resources to set the frequency (http://playground.arduino.cc/Main/TimerPWMCheatsheet), but these are predefined frequencies. I need to have one PWM at 650Hz and the other at 850Hz.
Any recommendations on how to approach this problem?

Have you looked at the datasheet yet?

Since you are already  using two different timers, the key is setting the proper Wave Generation Mode with the appropriate Prescaler and TOP for the desired frequencies.  Look in https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf for ATMEGA328p  or https://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf for ATMEGA2560 for "CS10" and "CS30" for the prescaler tables. and WGM10 and WGM31 for Wave Generation modes 8,9,10,11,14, or 15.

The ATMega PWM hardware underlying the Arduino primarily supports changing the duty cycle; the frequencies can only be selected from a few fixed choices.  Typically the timers run from 0 to 255 or 65535 and loop back to 0, and you can select where within that full cycle the output changes on and off.
Since what you want is a simple 50% duty cycle with fine control of frequency, the PWM functions are not very useful.  What you want is tone or frequency control.  The ATMega timers support this too, but it's a different function than PWM. For frequency control, the timer will cycle from 0 to your choice of upper limit.  So for example, you might count up to 200 instead of 255; or to 201 - so you get much finer control of frequency.
Unlike PWM, on the ATMega328p used in the Uno, you can only get one frequency per timer (you can get two PWM outputs per timer - both at the same frequency).  And if you want millis() and microseconds() and delay() to continue to work, you don't want to mess with timer 0 for frequency control (you can get PWM from timer 0 if you accept the default frequencies).
So that leaves you with two frequency controllable timers - timer 1 (16 bit resolution) and timer 2 (8 bit resolution).
See the tone() function in the Arduino library for examples of a single tone at a time.
For multiple simultaneous frequencies (on different pins) see this library: https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation.  You can have two tones at a time, or three if you don't need millis() etc.

I recommend you to use two PWM signal with different duty cycles with the same frequency using timer1 and output pins 9 and 10. The next sketch was tested and it works very well.
 /*
 * Este programa genera 2 PWM signals a partir del timer 1. Las dos señales tienen la misma frecuencia (250Hz)
 * lo que varia es el duty cycle independiente para cada señal. Una sale por el pin 9 y la otra por el pin 10.
 */
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  //******** PWM Variable Definitions
**********************************************************
  // Register initilisation, see datasheet for more detail.
  TCCR1A = 0b10100010;
  //Timer/Counter1 Control Register A COM1A1 COM1A0 COM1B1 COM1B0 - - WGM11 WGM10
  // COM1A1 COM1A0 COM1B1 COM1B0
  //   1      0      1      0       Clear OC1A/OC1B on Compare Match, set OC1A/OC1B at BOTTOM (non-inverting mode)
  TCCR1B = 0b00011001;
  //Timer/Counter1 Control Register B ICNC1 ICES1 - WGM13 WGM12 CS12 CS11 CS10
  // ICR1 Register is not double buffered. Using the ICR1 Register for defining TOP works well when using fixed TOP values.
  // By using ICR1, the OCR1A Register is free to be used for generating a PWM output on OC1A. That's why, I am using WGM 14.
  // WGM13 WGM12 WGM11 WGM10
  //   1     1    1     0           Fast PWM ICR1 - fixed TOP, update of OCR1x at BOTTOM. WGM 14 (Table 13-4).
  // ICNC1 is 0                     the Input Capture Noise Canceler is disable
  // ICES1 is 0                     falling (negative) edge is used as trigger
  // CS12 CS11 CS10
  //  0    0    1                   No prescaling
  TIMSK1 = 0b00000001; // Timer/Counter1 Interrupt Mask Register. The Timer/Counter1 Overflow interrupt is enabled.
  // TOP value is put in ICR1 and is equal to 64000, it means that 16000000 / 64000 = 250Hz (since no prescaling), the frequency of PWM signals
  ICR1   = 64000;
  DDRB = 0b00000110; // Set PB1(DB9) and PB2(DB10) as outputs.
  interrupts ();
}
 void loop() {
  // put your main code here, to run repeatedly:
}

 ISR(TIMER1_OVF_vect) {
  // change duty-cycle every period.
  OCR1A = 16000;// in OCR1A is put the value corresponding to duty cycle, OCR1A output pin is 9. Duty cycle 25%. 16000 / 64000 = 0.25
  OCR1B = 48000;// the output pin of OCR1B is 10, duty cycle 75%. 48000 / 64000 = 0.75
}

There is a great library with functions to change PWM frequency on Arduino microcontrollers, called
arduino-pwm-frequency-library. I hope this helps you.

IF you need to dim leds use:
/*PWM signal on most pins is approximately 490 Hz
On the Uno and similar boards, pins 5 and 6
have a frequency of approximately 980 Hz
brightness1, brightness2 = from 0(0v) to 255(5v)
So make eqution to calculate needed frequency*/

//LED are connected to:
const int ledPin1 = 5;
const int ledPin2 = 6;
byte brightness1 = 100; // ~2v
byte brightness2 = 200; // ~4v
void setup()
{
  // initialize the ledPin as an output:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

void loop() {
    // set the brightness of the LED:
    analogWrite(ledPin1, brightness1);
    analogWrite(ledPin2, brightness2);

}

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


text:
Flexibility of SoftPot Membrane Potentiometer during the use?
Does anybody have some information or experiences with the flexibility of Spectra Symbol's SoftPot Membrane Potentiometer during the use? Is it possible to partly wind it up on a reel (or something similar) and use the remaining part dynamically without loosing precision and control? Are there "ghost touches" caused by the force/pressure of bending/winding the sensor strip? Or should the sensor always be used in a flattened position?
Thanks for any helpful comments.

As you can see from this data sheet it will show you examples on how it is used. https://www.sparkfun.com/datasheets/Sensors/Flex/SoftPot-Datasheet.pdf
I'd buy a curved one just to make sure, because as it bends, the 2 conductive materials will touch.

If I helped let me know, it's the first time I have answered a question.

Oh and also, it does not need to be flat.

Thanks Mateo for your answer. I know that there are different models of the sensor (length, curve, rotary). But my questions refers to the capability of the measurement accuracy/possibility during the use of extremely roll/winding/bend applications (for example mount it around a small flower tub, or use it as a retractable tape measure). I know that the sensor strips are bendable (as the name and soft material indicates), but I don't know about practical limitation of the maximal winding/bending radius.

Let me do some research, it will take me sometime, and I will also ask someone who I know that is familiar with it.  Sorry for the misunderstanding :)


text:
Is there an Arduino simulator that runs on Mac OS X?
I need to simulate my Arduino project with other circuit components before implementing the project. Is there a decent simulator that runs on Mac platform?

There is a decent program called Simulator for Arduino made by Virtronics. Although it is made to run only in windows, you could run it in a WINE environment. WINE allows windows programs to be ran in Mac and Linux OS.

Ouch - "Pointers not implemented - some sketches with pointers may run but generally pointers don't work"

I'll try to install on Mac and see if it works

web-based Arduino simulator from wokwi,com will even work on Mobile platform. It is easier than ever to keep learning Arduino and tinkering with the projects


text:
Use of two external power sources for a power cell - charger
I have a SparkFun Power Cell - LiPo Charger/Booster and want to use the external 5V charge capability. Now my question:
Can I directly hook up a DC jack (for a 5V power supply) and an inductive charging circuit to the external charge pins of the Sparkfun Power Cell LiPo Charger Module or should I use a slide switch so that either the power supply via the dc jack or the inductive charging module can power the Sparkfun Power Cell LiPo Charger? I prefer the first option, but I have concerns that the inductive charging module is damaged when for example the power supply is hooked up...
Have anybody experience with an similar setup?
Thank you in advance for your answers.

A switch would be the best way of preventing damage, but you could also use diodes to prevent power flowing back to the PSU or Inductive circuit.
I tried something similar once using transistors to prevent both circuits operating at the same time, but never managed to get it to work.  You could practice any solutions on a breadboard with some LEDs.


text:
Code runs different on USB vs Battery
I have two Arduino, one is to handle the Bluetooth communication and send a signal to the other Arduino, and the other to interpret the signal and display or hide an image on the E-ink display.
It work just fine when they both are connected through the USB. But when I connect a 9V battery to the Arduino running the E-ink, instead of the USB, the image is displayed and cleared (looping), as if the IF ELSE conditions are not there.
I have tested if it actually runs the method by adding delay to the showImg()-method, and that seems to work.
I have also tested with connecting the USB cable to the E-ink Arduino to a 5V charger, and the case is the same.
Image:

Bluetooth code:
int ledPin = 13;
int state = 0;
int flag = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 Serial.begin(9600);
}

void loop() {

 if(Serial.available() > 0){
 state = Serial.read();
 flag=0;
 }

 if (state == '2') {
 digitalWrite(ledPin, LOW);
 if(flag == 0){
 Serial.println("Screen: off");
 flag = 1;
 }
 }

 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 if(flag == 0){
 Serial.println("Screen: on");
 flag = 1;
 }
 }
}

E-ink code:
#include <epd.h>

int displayed = 0;
int val = 0;

void showImg(void)
{
  Serial.print("showImg");
  displayed = 1;
  //epd_clear();
  epd_disp_bitmap("PIC9.bmp", 0, 100);

  epd_udpate();
  //delay(10000);
}

void clearImg(void){
  Serial.print("clearImg");
  displayed = 0;
  epd_clear();
  epd_udpate();

}

void setup(void)
{
  //Serial.begin(9600);
  epd_init();
  epd_wakeup();
  epd_set_memory(MEM_TF);
  pinMode(7, INPUT);

}

void loop(void)
{
  val = digitalRead(7);

  if(val == 1){

    if(displayed == 0){
      showImg();
    }

  }else {

    if(displayed == 1){
      clearImg();
    }
  }
  //Serial.println(val);
  //delay(3000);
}

I am a beginner when it comes to Arduino, So I hope someone can give me some hints to what may be wrong.
Thanks!

Please edit the question to fix the following ambiguity: in “connecting ... to a 5V charger ... the case is the same” it isn't clear whether you mean like the battery setup or like the USB-to-computer setup, ie, whether it fails or works

The USB provides the one thing that is missing from your diagram there: the common ground.
The GND pins of the two boards must be connected together. By using USB the USB becomes that connection. As soon as you use batteries there is no connection, so no communication happens.

Thanks for the reply Majenko. You are absolutely right, and I'm surprised I did not see this.... Thank you!


text:
Power servo with external power using a hacked USB cable
I want to use a servo motor and control it by an Arduino Duemilanove (or a Leonardo). It seems to work fine when I connect it directly to Arduino's VCC, GND and an PWM pin. But I am a bit worried if this is a good idea. The multimeter shows that it draws up to 0.6A which is about 10 times of what I'd expect that the Arduino can provide. Is this correct or does this apply only to the digital out pins? Would it be better to power the servo using an external power supply?
I thought it would be a nice and easy solution to power the Arduino using a USB power supply and to cut the USB cable and connect the servo directly to the +5V of the USB. But is there even a difference in powering the Arduino via USB and connecting the servo to the VCC of the Arduino? Is it a problem to connect GND and UGND?
(After first tests, I think that the Arduino led is pulsating less using the hacked USB cable, but still a pulsating LED shows that the servo is drawing a lot of power from the board.)
Bonus question: does your answer apply to all Arduino models? (I am interested especially in Leonardo and Duemilanove.)
Similar discussion:
http://forum.arduino.cc/index.php/topic,22132.0.html

What kind of servo are you using? PWM pin isn't providing any current. USB only rated at 500mA. So your best bet is to use an external power supply. You will indeed need to connect the ground of the arduino and the ground of the external power supply together. Limiting factor is USB not the arduino board (which by itself only uses 20mA).

USB 2.0 is normally only rated at 0.5A. So 0.6A is already 'border line'. How did you measure the servo current was 0.6A? Was the servo moving, or were you holding it still ('stalled')? If it was moving, expect the servo to have a much bigger 'stall' current; in this case USB will not be enough. If the servo stalls, which is easy to do by accident, the USB power supply may switch off or even fail.


text:
Replicate a Waveform Exactly with An Arduino Uno
So I've got a waveform that's high for 16ms and low for 2ms repeating forever. I need to recreate that and offsets of that waveform time exactly on a different pin. Right now, I've got an interrupt on the rising edge for the 16ms low/high transistion, and delayMicroseconds() that determines the offset and duration of the high and low pulses. Trouble is, I'm not sure the code I have is as fast and accurate as it could be. And the replicated waveform seems to shift through the full period of the original one. I need it to be locked in.Any suggestions?
Here is the code:
 //3 is interrupt for Timing
//4 through 11 are Time dependent receivers
//3-11 Pins 12-19
char incomingByte = 0;

int pins[9] =
{
  3,4,5,6,7,8,9,10,11
};

void timing()
{
  //Serial.println("This is a 0ms Event");
 // if(Serial.available() > 0)
 // {
    incomingByte = Serial.read();
    Serial.print("I received");
    Serial.println(incomingByte);

     pinMode(10, OUTPUT);
     digitalWrite(10, HIGH);
     delayMicroseconds(16000);
      digitalWrite(10, LOW);
      delayMicroseconds(2000);
      digitalWrite(10, HIGH);
 }
//}

void setup() {
  // put your setup code here, to run once:

for(int i=0;i<8;i++)
{
  pinMode(pins[i], INPUT);
}
pinMode(3,INPUT);
attachInterrupt(1,timing,RISING);

//Begins Serial
Serial.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:
}

Here's the waveform I'm trying to duplicate:

Don't use Serial inside a function that is called by a timer. Never.

I don't understand why you have an external pin that must trigger the beginning of every period of your waveform.

You mention that "the waveform seems to shift". after how long does it seem to shift? Of how many ms can it shift?

What you've failed to mention is: are you doing anything else at the same time? If so, you're going to have to get rid of those delays because it will halt your code. If not, then it really doesn't matter, but still, just set a flag in your interrupt and run it on flag in the main loop. If you ARE doing something else, implement a state machine in the main loop for it

If you're looking to speed your code up I would recommend not using digitalWrite or Serial. When using digitalWrite it can take quite a few unneeded clock cycles to turn the pin on or off, as a replacement I would suggest looking into using port manipulation.
Example of turning a pin on or off with a preprocessor macro using port manipulation
#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

Using port manipulation in your code:
#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

void timing()
{
    //incomingByte = Serial.read(); // If needed uncomment, but it's slow
    //Serial.println(incomingByte); // If needed uncomment, but it's slow

     // Set pinMode in setup()
     DIGITAL_WRITE_10_HIGH();
     delayMicroseconds(16000);
     DIGITAL_WRITE_10_LOW();
     delayMicroseconds(2000);
     DIGITAL_WRITE_10_HIGH();
 }

This code is wrong in many ways.
first of all, timing() is execute inside an interrupt, this mean that while it is running, all other interrupt and timer stop (delayMicroseconds works because it does not rely on timer, but on know instruction execution time). That mean you have to keep the interrupt funzion faster as possible, or bad things may and will happen. (microseconds still work because it is based on know instruction duration in loop)
For example, Serial is interrupt driven; this may cause a race condition that will freeze the code.
As far as i can understand pin 3 may be a button (in that case you need to apply some antibounce code, just look at the signal create by pressing a button with your oscilloscope to see what happen), so you can just make a digitalRead every loop, if true do your code. So you will keep timing() out of interrupt.
pinMode() only needs to be set once, in setup(). Also, digitalRead() is really slow: operating directly on the register is a lot faster! see port manipulation
but in your case i would delete all precendent code and do some math to use an ad-hoc PWM, so you will be almost code free and because it will be almost all done by hardware, precision and possible granularity will increase, see secret of arduino PWM

If all code is ran inside loop() and you're really looking to squeeze out a few clock cycles I would do the following void loop() { while(true) { /* Code Here */ } } as you don't have to worry about the small overhead of recalling loop()

You've said pinMode() can only be set once. I believe that's incorrect. It can be called as often as necessary, at any time.

you are right, but digitalWrite is a mayor speedup, to sqeeze mcu use the PWM and you will have a lot more power with a lot less efford (once you know how to PWM :) )

@PeterR.Bloomfield my english is bad, i can't find a way to say what i mean. if you can edit my answer to correct the sentence so it will be correct.. thank you


text:
Detecting ball moving between IR pair and handling ambient light changes
I plan to use the SEN-00241 IR Emitter and Detector pair to detect a ping pong ball moving fast between them.
I understand I could watch for voltage changes to detect this passing object, however how do people generally deal with ambient light changes? From my research it seems that the voltage will change with ambient light, and although I can take steps to create funnel vision between the 2 I'm sure it may still be an issue.
Would you take constant readings and find averages over 10 consecutive readings to allow for changes in ambient light and set a new baseline reading? Then if the voltage changes dramatically and only for a few reads then I know that was the ball and not to change the baseline reading.

this is the same problem that IR remote/television has; how can TV they tell if that high voltage is a direct light or a logic 1 sent by remote? Simply because remote does not send a "HIGH" signal, but a modulated one, tipically at 36KHz. This mean a logic "HIGH" is a train of "HIGH-LOW" at 36KHz (you can see it as PWM at 50%duty cicle and 36KHz frequency)
Ambient light des not have fast variation, and inside light are at 50-60Hz, so they will be "filtered" out.
So, until you see high voltage change at 36KHz, you have your beam fine, if it is not the case, then look at voltage: if fixed at normally low voltage, beam is broken; is fixed at normally high voltage then some light stronger than your emitter is "blinding" the sensor.
note that because 36KHz is a very use frequency on Remote, there a a lot of chip that will emit or read a modulated IR, but expose a normal digital input/output, but still can be done by software, expecially if hardware assistet (like PWM for output), interrupt for input


text:
Animated LED Strip & Sensing an Object
Problem: Have an LED strip do some animation (say it takes 15 seconds for that line of code to run) meanwhile, have a sensor (tried methods: PIR sensor and ultrasonic sensor) watching to see if an object passes by.  If it senses an object, stop the light animation and make the lights do something else.
Issues: The PIR sensor takes too long to reset... I have the timing turned all the way to minimum and I am still able to count 12 seconds before it starts sensing motion again.  (Is there anyway to override this in the code?)  The other issue is the ultrasonic sensor, as far as I know, can't reliably run the first animation and watch for a change in distance then call an interrupt since an interrupt can only happen on FALLING, RISING, LOW, or CHANGE. This is an issue because the ultrasonic sensor is continuously sending LOW to HIGH then back to LOW for its pulses.
OVERALL QUESTION: How can I effectively sense if an object passes by a sensor, run new LED animation then back to where it left off without having to wait 12 seconds every time.  Is there some other hardware I could try? Please help!?

PIRs are controlled by their hardware.

Can you post your code please.

It seems as you are using the delay(); function for your code. The reason that it doesn't run anything is your Arduino does nothing during the function. The easiest option IMHO is using millis();. This will "return" a long datatype. Some example code (modified from example sketches in Arduino IDE):
/*
 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen
 modified 5/16/14 by Anno. Penguin
 This example code is in the public domain.
*/

const int ledPin =  13;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
  //Sensor code
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Obviously, your code will be more complex than that. This one only blinks it, but you'll have to do some creative logic here. I don't know what the animation is, but most likely you'll need to add a few more variables (make sure to declare them outside loop() so they aren't disposed of each iteration!).


text:
Why does serial port stop sending data?
I'm using an Arduino Leonardo to interface with two pressure sensors and Python on my laptop, a MackBook Pro.
I'm using arduino IDE V. 1.5.4, Python V. 2.7.6, and OSX 10.8.5.
One pressure sensor is digital, using the Wire lib, and the other is analog.
My sketch compiles, runs, and works until I try to get the data in Python using pyserial.
If I try to grab a bunch of data using the readlines method in the scrip it will only return blank data or hang, depending on the serial object timeout settings. My python code sometimes works from the repl when I initialize the serial object and wait before reading from it.  If I don't wait the serial object will only partially fill a list and then any future reads will return an empty string.  This continues even after closing the serial object and reopening it in Python, or closing the serial object in Python and then opening the Serial Monitor in the Arduino IDE.  Once the serial port stops sending, I have to reset the Leonardo in order to read new data.
I could be running into some kind of buffering problem, but if that were the case I would expect future calls to return data.  Another option is that the Wire protocol is getting stuck and halting the program.
Here's my sketch
#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate
int PRESSURE_PIN = 1;

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  Wire.requestFrom(ADDRESS, REQUEST);    // request 6 bytes from slave device #2

  Serial.print(analogRead(PRESSURE_PIN));
  Serial.print(',');

  while(Wire.available())    // slave may send less than requested
  {
     Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
     Serial.print(',');
     Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
  }

  delay(10);
}

and here is how I read it from python
import serial

serial_port = '/dev/tty.usbmodem1a1221'
ser = serial.Serial(serial_port, 19200, timeout=0)

vals = [val.split(',')[0:2] for val in ser.readlines(1001*14)]

Welcome to Arduino SE! First of all, try viewing output of the sketch using the Arduino IDE port. If it's not the sketch, I don't know how on-topic this question is.

As far as I can tell, the problem is arduino related, either software or hardware.  I'm hoping it's just a stupid gotcha that I haven't realized

did you work it out?

Yeah.  There is some kind of USB communication problem I'm having with the Leonardo.  I plugged in a Mega and everything works fine.  I did notice that the tty and cu devices for the Leonardo would drop out of /dev when I had this issue.  I don't know enough of the lower layer stuff to adequately explain why this is happening but it's not an issue with a Mega board.

Writing custom clients on a Mac, you may find that you get better results using the /dev/cu.usbmodemXXX devices than the /dev/tty.usbmodemXXX ones.

The leonardo doesn't reset when the serial port is opened.
To check it isn't python, run your Arduino code, then open the terminal and run
screen /dev/tty.usbmodem1a1221 19200

NOTE: to exit the screen session type Ctrl-A Ctrl=\ (see here). If you just close the window it will stay connected and lock up the serial port until you recycle the power on the Arduino.
If the Arduino program spits out just fine to screen, then python is the problem. One thing that can happen is a python/java/whatever program can lock up the serial port driver, but recycling the Arduino power, not restarting the program, is required to reinitialise the driver. So the Arduino is not necessarily problem, as the serial port will stay locked up for ALL programs. So "I would expect future calls to return data" is actually wrong. If I stuff up the serial port code in my java interface programs the same kind of thing happens.
Other ideas:

Make the delay longer than 10ms.
Make sure hardware flow control is off in the python serial
Flash a LED in the Arduino loop to see if it is the main loop locked up or if that is running fine.

The Arduino forums talk the Arduino resetting when the serial port is opened. A solution as stated in the forums is to add a short delay. See if that works.
Source: http://forum.arduino.cc/index.php/topic,18371.0.html

My leonardo isn't resetting when the serial port is opened.  I can close and open it several times in both python or the serial reader and it won't give data until I power cycle the leonardo.  I'm beginning to lean more towards some race case in the wire library

My eventual workaround for the Leonardo was to set up a call-response loop on the Leonardo.  Here's the code:
#include <Wire.h>

int ADDRESS = 0x28;//I2C address of sensor
int REQUEST = 4;//# of bytes to request from sensor
int BAUD = 19200;//serial rate

void setup()
{
  pinMode(A1, INPUT);
  Wire.begin();        // join i2c bus (address optional for master)
  Serial.begin(BAUD);  // start serial for output
}

void loop()
{
  if (Serial.available() > 0) {
    Serial.read();
    Wire.requestFrom(ADDRESS, REQUEST);    // request 4 bytes from slave device at 0x28
    while(Wire.available())    // slave may send less than requested
    {
       Serial.print(((unsigned int)Wire.read() << 8) + Wire.read());
       Serial.print(',');
       Serial.println(((unsigned int)Wire.read()) << 3) + (Wire.read() >> 5);
    }
  }
}

I was able to simplify a little.
There are two things to note:

There is no built in delay and requests made too quickly will result in either an empty response or old data from the sensor.  Have to take into account in requesting program.
The sketch will respond a number of times equal to the number of bits sent.  Use a single ASCII character for one response, 2 characters for 2 responses, etc...  This is important if you use an API similiar to a write() and writeln() as the second sends extra characters.


text:
Serial: active low or active high?
When I use the Mega 2560 additional serial ports, I realize that it is active low, active high. I know that TTL is active high and the serial port is obviously stated in arduino serial port page.
I also found out that the receive pin flashed (put an LED) when I typed in to the serial monitor. Is this a mistake or problem?

What is your question exactly? You seem to be just describing various unclear observations you have made...

The Serial Class of the Arduino uses Typical usage of the Serial Ports is the USART in Async mode. Which is hard coded to IDLE state of HIGH or 1 or VCC.

http://midas.psi.ch/mscb/hardware/bits.gif
(picture wont add - so here is a link to it)
If you need to drive the TTL inverted from its traditional values, the Serial Class can not do this. However, you can use the SoftwareSerial Class and enable the inversion in the constructor
SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

As for why would someone want to invert the TTL UART. In some cases it is possible to drive RS232 directly. As RS232 converters inverts the TTL to +12V/-12V. 5V = -12V and 0V = +12V. So depending upon the RS232 receiver, it may actually trip its TTL output  at 2.5V and not 0V. If so then using the SoftwareSerial Class with inverse logic may drive the RS232 input of another device, without requiring a RS232 transmitter on the Arduino's TXout pin.


text:
Common Wire sizes for connecting peripherals to arduino
Please don't judge me for asking this question i have never touch arduino before but We plan to use it in our thesis we are doing a budget plan and it must include wires. can anyone tell me the common wire sizes used? This is to estimate the prices.

Used for what? Different purposes need different sizes.

Wire size (i.e. diameter) depends on the amount of current traveling through it. For most arduino stuff, wire size isn't really that important. You can just reuse wires from unused cables. Ethernet cables are a great source of wires. Decent diameter, and different colors (very handy).

Depends what you’re doing.
For low power (< 12v, 500mA) peripherals and digital signals:
If you’re going to use breadboard (and you really should start with breadboard) you’ll need solid core hook up wire. You can find pre-cut, pre-stripped sets with a variety of lengths and colours if you’re looking for neatness and simplicity.
(An example can be found at: http://www.maplin.co.uk/p/jump-wire-kit-fs65v)
Usually it’s 22AWG wire, so you could get a reel and cut it yourself if you’re going to need a lot or are going to solder it in place.
After you’re done breadboarding and want to make something more permanent you should look at rainbow cable. You can tear it to get anything from 2 to 32 way cables, and it’s almost impossible to get the wrong way around. You can solder it directly to a PCB or crimp connectors onto the ends for more flexibility.
(You can find this stuff everywhere, but Sparkfun is always there if you can’t: https://www.sparkfun.com/products/10649)
For higher power (> 12v, 1A):
Keep it away from the Arduino! Use switching transistors, relays, or MOSFETs and use cabling that meets, or preferably exceeds, the power that you’re going to put through it.
I don’t know where you’re going to buy this, but in the UK I use Mouser, Farnell, and RS for most of my electronics supplies. Never buy cabling off Ebay, a lot of it is counterfeit and won’t meet the claimed spec.
Hope this helps.

We have Mouser outlets here in the US as well. Also Digikey, Jameco, and quite a few others.

Thanks a lot.. you really helped.. It's good to read an answer that makes sense..

I wonder in which way eBay cable can be counterfeit? Not the claimed gauge? Not tinned or not copper? Insulation not heat tolerant?

@thomasrutter All of the above. I've seen "copper" core cabling clearly some bastard mix of metals to make it cheaper, 16 gauge wire sold as 12, and "silicone" insulation that flaked right off the reel (a fire risk for what we were going to use it for). Don't even ask about "un"twisted pair, "un"shielded, and coax that isn't. I'd always pay ~30% more and get the genuine stuff from a repitable supplier and save yourself a world of rage.


text:
How to read data from a rotary encoder with ATmega328
I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.
I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.
I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a getAngle() function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.
My questions:

How can I implement this getAngle() function using a rotary encoder?
What is an example of a rotary encoder that is suitable for this application?
Will it be better to use the interrupt pins of the Atmega328, or use some other method?

I have seen a few library's on Arduino Playground that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this getAngle() function.
Thank you!

This question is cross-posted to Electrical Engineering SEx. Please don't do that.

You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.
Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.
Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.
This code goes at the start of your sketch, right before setup() function:
const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
volatile long encCount = 0;

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.
Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
attachInterrupt(0, encoder_interrupt, CHANGE);
attachInterrupt(1, encoder_interrupt, CHANGE);

Last you will need the actual interrupt function that reads the encoder and updates the counter value.
void encoder_interrupt() {
  static unsigned int oldEncoderState = 0;
  oldEncoderState <<= 2;
  oldEncoderState |= ((PIND >> 2) & 0x03);
  encCount += encoderDirections[(oldEncoderState & 0x0F)];
}

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.
The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.
The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.
On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.
And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.
If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:
const int LINE_COUNT = 400;

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.
float getAngle() {
  long curCount = encCount;  // Store the current count.
  while(curCount < 0) {
    curCount += LINE_COUNT;
  }
  while(curCount >= LINE_COUNT) {
    curCount -= LINE_COUNT;
  }
  return (curCount / LINE_COUNT * 360.0);
}

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.

This is exactly what I was looking for. Thank you.

There is no such thing as an encoder that "works well with Arduino" - encoders are encoders, and there are several basic types. As @JRobert said, you need to make an appropriate choice, and an encoder that will mechanically couple well with your drill motor is probably your primary criteria, and of course an encoder that can spin unrestricted (some are only for an angular range like 180 or 270 degrees); my guess is you'll want to put the encoder on the ungeared motor, rather than the geared output of whatever it is you're driving, to get good feedback from a cheap (i.e. relatively small number of 'pulses per rev') encoder.  Search on DigiKey, Mouser, online hobby stores, etc.  Then just deal with whatever type of encoder it is, hack its electrical interface into the Arduino:
http://www.digikey.com.au/product-search/en?pv69=848&FV=fff4001e%2Cfff80033&k=encoder&mnonly=0&newproducts=0&ColumnSort=0&page=1&stock=1&quantity=0&ptm=0&fid=0&pageSize=25
This (2-signal quadrature) encoder library for Arduino is superb, by Paul Stoffregen @ pjrc.com:
https://www.pjrc.com/teensy/td_libs_Encoder.html
For best results you'll want the 2 'quadrature encoder' outputs to go into 2 interrupt inputs on the Arduino, and there are only 2 available.  There is an option to run this library on only 1 IRQ-capable input (the other can go into any input), or even no IRQ-capable pins, but performance will suffer.
Sampling at only 5/second isn't much - don't be afraid to increase that substantially - 10 to 50 / second.
You also might want a PID control algorithm, depending on what your actual aims are.  the "PIDLibrary" by Breatt Beauregard on the Arduino Playground website is excellent.
Coding your 'getAngle()' function shouldn't be hard - for a rotary quadrature encoder, X pulses from the encoder corresponds to 1 revolution.  The 'encoder library' you end up using may provider more than 1 pulse output per actual pulse output from the encoder.  Do that math. Simple.

Your encoder choice will probably be driven by the mechanical requirements and the precision you need:

Runs occasionally, and briefly to 450 RPM or runs continuously, and often at the higher speeds?
Do you need position to e.g., within 3 degrees (7 bits)? Or 1/3 degrees (10 bits)? Or are you willing to count pulses from an index mark (this gets more complicated if the direction of rotation can change).

An n-bit encoder can probably be read whenever you need a position sample, so interrupts would probably not be necessary. With an index wheel (a pulse every x degrees, plus a separate pulse at 0 degrees, e.g.)
you would probably benefit from tracking the position at interrupt level and letting the main loop simply access the last known position.
Your getAngle() implementation depends totally on the choices you make above. If you use a Gray-coded encoder wheel, you'd need to convert the code to a binary fraction and multiply by 360 to get degrees. If you use an index wheel, getAngle() just reads the current pulse-count maintained by your interrupt routine and converts it to degrees. But you need an interrupt routine to count angle-pulses and reset the count on the index pulse (not especially hard to do).
Fixed-point arithmetic is pretty fast. Floating point takes longer. Depending on what else, besides position-keeping, your code needs to do, and how math-heavy it is, whether you can afford floating point. The floating point library will take more code space, too, but my guess is you'll be constrained by time more than by code-space.


text:
What is the Vin Pin for?
I always asumed it was a different option to power the board, but it seems to act more like a 5V supply. What then is the difference between this pin and the 5V pin?

This is a classic example of an X-Y problem. You asked about what the Vin pin was for, and got some good answers, but what you really wanted to do (it turned out) was to trigger your camera shutter without using external components. You would get a faster (and better) answer if you state your real goal, rather than omit your goal, and mention what a possible solution might be (read the link for more info). You could always mention, as part of your question, that you wondered if using the Vin pin would help solve your goal. Just for future reference. :)

The Vin pin serves the same purpose as the barrel jack.  The only difference is (usually) that it doesn't go through the schottky protection diode that causes a small voltage drop.
Normally its voltage is at around 0.3-0.4V below whatever you feed into the barrel jack.
If you power from USB then the USB voltage (~5V) is "back-fed" through the 5V regulator to appear on the Vin pin.  It's not safe to use that power for anything since you could damage the 5V regulator if you do.
The pin is designed to either be used to power external higher voltage devices with power (almost) direct from the barrel jack (motors, etc), or to feed power in from an external source without using the barrel jack (great for a shield that can provide its own power source).

Thanks for your answer. Can I ask, what is the barrel jack and what is its purpose?

The barrel jack is the big round power connector that you plug your power adapter or battery into.

So is it possible to power the Arduino solely from the Vin pin without the usb or barrel jack?

Yes.  That is one of the normal uses for it.

Thanks. At the moment I am using it as a sort of 5V "virtual ground". Is this an okay use without damaging it? I have a camera which triggers when two wires coming from it are connected, so it triggers on a short. I have connected the 5V wire from the camera to the Vin pin, and the return wire to a digital out pin. This triggers when the digital out pin goes high. Is this an okay way to trigger the camera, or might I damage something?

No that is not an okay usage of the pin. You risk damaging the 5V regulator like that.  For that system you should have an optocoupler with the optotransistor side of it on the camera (use a DMM to find which pin has the higher potential) and the LED side driven by the Arduino.

To answer this added question:

At the moment I am using it as a sort of 5V "virtual ground". Is this an okay use without damaging it? I have a camera which triggers when two wires coming from it are connected, so it triggers on a short

I certainly would not be using it as a 5V "virtual ground" - whatever that means. The Vin pin could easily be up around the 10V mark, depending on what you plug into the barrel jack.
I had a project a while ago where I wanted to trigger a camera flash. In the same way as you describe, two pins had to be shorted.
I wasn't sure what voltages would be on them, or if there would be a spike, so I used an opto-coupler like this:

You need to identify by measuring with a meter which pin has the positive voltage on it. That would go to the collector of the transistor in the opto-coupler (pin 5 in this particular case).

(edited to add)

I'm just not sure about connecting 5V directly to ground though. Do you think this will be safe?

We can probably assume that the current will be low, after all they wouldn't short out the camera's battery through that pin. Put your meter in current mode across the camera's pin and measure the current when the pin is shorted (ie. the meter will short it).
If it is 20 mA or less then the Arduino digital pin can handle that. I imagine it will be a steady flow of current. I just measured my flash shoe with that method, and it seems to use a tiny fraction of current (0.1 mA).
So that should be safe, safer than your method with Vin anyway.

Then, when I want to trigger it I need to change the digital in pin to a digital out pin and enable the internal pull down resistor on this pin, effectively connecting this pin to ground, and shorting the two wires.

Sounds complex. Just make the pin LOW, and make it output to fire it. eg.
In setup:
digitalWrite (cameraPin, LOW);  // default will be INPUT mode

To activate camera:
pinMode (cameraPin, OUTPUT);  // drive low
delay (500);  // or whatever
pinMode (cameraPin, INPUT);   // make high impedance

Make sure you measure the pin and get the correct polarity. You want the positive side to go to the Arduino pin, and the negative side to Ground.
And make sure it isn't higher than 5V. (Use voltage mode on the meter to check that).

Thanks for your suggestion. Unfortunately I cannot add any external components, otherwise an optocoupler would have been perfect. I have been given a suggestion on Electronics stack exchange to connect the camera 5V wire to a digital in pin, and the other camera wire to ground. Then, when I want to trigger it I need to change the digital in pin to a digital out pin and enable the internal pull down resistor on this pin, effectively connecting this pin to ground, and shorting the two wires. I'm just not sure about connecting 5V directly to ground though. Do you think this will be safe?

See amended post with more details about that.

+1 also for answering the real question.

I like the way someone explained Vin to me. "Whatever power source you connect to the DC Jack is supplied there, be it 12v or lesser"


text:
How to interface to LPG consumption meter
I have sourced an LPG consumption meter from China with pulse output. I am looking to hook the output up to an arduino to get the consumption metrics. Unfortunately there is not too much documentation available on the unit that I can find. The suppliers inform me that:

Black wire(signal 1)
Black wire(signal 2)
Red wire(earth wire)

So that's a start, I know the unit pulses a signal for every cubic meter of gas consumed.
What I'm wanting to know is:

What are the input [likely] voltages for the unit (or how could I establish this)?
How do I wire the unit to an arduino?
I can cook up a sketch to do the reading but what is the signal I am looking for?

The mechanical meter itself has a metallic strip on the 0 digit of the wheel (how it achieves the pulsing itself no doubt) so another approach would be something like this http://phk.freebsd.dk/Gasdims/ which is a more accurate option. For this option any suggestions on what photoreflectors are available for the Arduino which could do the job.

Do you have a link to the gas meter documentation or the name of the meter?

Do you have access to an oscilloscope? That would make things very easy.

I have had some success using an SG-2BC as a photoreflector, details of my build are here https://github.com/Bra1nK/HomeMonitor/tree/master/Gas%20Meter%20Pulse%20Creator

Most connections into meters are open-collector or volt-free i.e. a relay or NPN transistor.

Start with earthing the red (!?) wire to the ground of the arduino.
Apply 5 volts via a 10k resistor to one of the black wires and also connect the black wire to the arduino as well.
Basically :
5V ----(10K resistor)---+---Black wire----( Gas Meter)-----ground
                        |
                        |
                        +--- arduino digital input

You should either get a high or a low signal. Try the other black wire, it might be inverted (as in high and then pulse low, vs low and then pulse high).
Failing that, pop the top off that cover and have a poke around. Might give you a clue as to what's what.

thanks @dgriffith, I'll give it a bash. so you think the two black wires are the same signal inverted? Why bother?


text:
Controlling a motor with a wav file
I've got an SD card and speaker hooked up to my nano and I can play mono audio files easily. My question is, is it possible to control the speed of a motor using the pwm output to the speaker? I tried just hooking the motor in where the speaker was, but that produced no noticeable variations in speed.
Alternatively, is it possible to analyse the wav file on the nano and control the motor that way? (i.e. motor speed is dependant on volume at a given time)
Thanks

Have you tried peak detection yet?

That sounds like the sort of thing I'm after, could you go into a bit more detail/provide a link?

Regular sound files will have an even amount of time spend energizing the coil positive and negative, so the motor will not spin around in the normal sense. With a strong enough amplifier it will produce the sounds in the file like a speaker, but it will not noticeably turn.
Actual PWM varies the percentage of the time the signal is HIGH in a fixed frequency square wave, thus all the different values are the same "pitch". Audio varies amplitude and frequency, but the cumulative effect of audio waves is neutral, it spends half of the time below neutral and half above neutral voltage. The simplest analogy I can think of is audio being itself, even vibrations in air, and motor PWM being wind.
I am not sure if it possible to generate a sound file that would turn the motor, it probably depends on the file type. In any case, you would be better off with a far simpler amplifier like a transistor, MOSFET, or H-Bridge on one of your nano's actual PWM pins.
As to whether or not you could analyse the file on arduino, it also depends on file type. The code for the arduino WAV sheild I've seen does not have the arduino actually processing data, but It should be possible with a simple enough file type for arduino to decompress. WAV is not normally compressed, just raw data, so your limits are the RAM and if you can code something to glean volume from the raw data. I don't have much experience in that kind of file processing on AVR so I'm not going to call it either way.

Thanks for the info. I have a transistor as an amplifier for the motor already. Would it be possible to build a circuit that would filter the audio into a usable signal for the motor? Like how a bridge rectifier changes the positive and negative of AC into just positive DC?

you could put a rectifier in, it would at least make it possible, but still sub optimal. is there a reason you need to power a motor off an audio amp?

Its not from an audio amp, but from an audio file, I may or may not have a speaker attached as well

I see. Have you thought about making a simple file of motor PWM settings to be read at a certain speed on the arduino?

I can do that, but this way allows me to be lazy as there are countless songs I can "play" already out there.

@BrettM - most likely the audio PWM amp output is unipolar (for sake of cost/simplicity), so the direction reversing / rectifier thing is a non-issue.  And given that the motor turns at all, we know there's no series cap in the circuit.


text:
Pressure Sensor and Arduino
I am currently working on reading pressure values using a tekscan a201 sensor. The sensors I have are limited to 25lbs.
My plan is to use eight on these sensors of them with a arduino Mega. Since I am measuring the resistance, I am thinking of making a 8 similar voltage divider circuits and grabbing the voltage reading via arduinos analog pins.
At the moment, I am not sure how to convert these readings to engineering units. Any ideas?

I have not previously met the Flexscan sensors but from the datasheet it appears that there are versions of the A201 rated at 100 pounds are you committed to the 25 lbf version?
A201 datasheet here
Here is a 15 page user manual thatexplains how to produce a voltage output using a single opamp per sensor - bottom of page 9.
Many idea starters here

What is your application and why do you wish to use these sensors. These seem to be a low accuracy alternative to eg load cells and seem to be expensive for what you get. If you need 8 for your task a loadcell based solution may e cheaper.

Thanks for responding.
I am helping out a few friends who are planning to use these sensors to test out compression wear for women. They already brought the tekscan sensors so I am kind of stuck with them.

You are right, they don't seem to be very accurate.

I decided go with the voltage divider approach as it seemed simple enough. The sensors themselves needed to be calibrated, which took me a while as I didn't have the required weights.
After the calibration, I used the line of best fit approach to find an equation that translated voltage to force.


text:
Watchdog timer stuck in restart loop? (green led flashing)
I am trying to set up a way to reboot arduino on command. The code below should do that but it seems like my arduino just get's stuck in some sort of a loop where I cant upload or get any serial output. The green led (pin 13) flashes very fast. The only way to stop this is to cut power to the device, even reset button does not work. This happens only when "R" is received via serial or if wdt_reset() function is commented out.
#include <avr/io.h>
#include <avr/wdt.h>

int ledPin = 3;

void setup()
{
  MCUSR=0;
  wdt_disable();
  Serial.begin(57600);
  Serial.println("BOOT!");
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  delay(500);
}

void loop(){
  if (Serial.available() > 0){
    char cmd = Serial.read();
    if (cmd == 'R'){
      Serial.println("R received!");
      wdt_enable(WDTO_1S);
      delay(2000);
      Serial.println("1 SEC.");
    }
  }
  wdt_reset();
  digitalWrite(ledPin, HIGH);
}

What am I doing wrong?

I think I ran into this a while ago, to upload a new sketch (without the watchdog stuff) I held down the reset button until right before the IDE began its "uploading" state.

Also see the note at the bottom of this post: http://ariverpad.wordpress.com/2012/02/26/resetting-the-arduino-through-software-for-fun-and-profit/

@sachleen yes, I followed that write up but am a little confused where that code goes. I assume it does not go into the sketch? I would prefer not to edit source files as that would affect every arduino I program.

Yes that would modify the bootloader and affect other sketches as well, but only if you're using the watchdog.

@sachleen Does that mean the bootloader would need to be re-flashed?

One of the most obvious issues here is that you are enabling the watchdog timer with a delay of 1S and then you are asking the micro controller to sleep for 2S, printing something and then going back into the loop. This, in theory, should be fine(your wdt should trigger a reboot during the 2 second wait) but I've seen it cause issues.
Additionally some bootloaders(notably the Optiboot bootloader on Uno and newer boards) can have issues with watchdog timers causing the wdt to remain enabled after reset even though the setup loop disables it. To start with - try increasing the wdt time to something greater than 2S(you should be able to do WDTO_8S) and see if the issue persists.
EDIT - The OP is using an Arduino Pro Mini clone. The included bootloader on the Arduino Pro Mini does not support system restarts by the WDT. Essentially, on a device with a bootloader that does not support WDT restarts, the board will restart but the timer / reset will not causing the board to continuously reset on reboot. There are alternative bootloaders for Arduino boards that may resolve this issue. Another solution is to use a different method to reboot the board.

So if it can cause issues, what method does not cause issues? I just tried 8 seconds with 9 second delay with same results. 8 seconds would bee too long anyways as I don't actually need any delay after serial command.

One of the first questions would be - what board is it and what bootloader are you running on it? Additionally - what happens with a simpler version of the watchdog code? For example one that is not reading an input but is rather looping a print statement n times and then resetting? Here(http://www.megunolink.com/how-to-detect-lockups-using-the-arduino-watchdog/) is an example of a very simple use of the watchdog timer - what happens when you run something like this?

I am using arduino pro mini clone with default bootloader (not sure what it is). With the copy pasted sample from the link it locks up just the same after a couple of seconds after power on.

A quick google on your product shows others with the same issue. The bootloader on the Arduino Pro Mini does not support system restarts supported by the watchdog timer. Essentially they restart the system but do not restart the timer causing the board continuously reset on reboot. I have not used an Arduino Pro mini nor have I had much luck with offbrands(nothing wrong with them, just bad luck on my part) so I can't recommend another bootloader offhand but a quick google search shows that there are folks who have found a functioning bootloader for the device that supports the WDT.

Is the bootloader required for watchdog at all? Could I just get rid of bootloader altogether, as long a I can program it over bluetooth that would be the best option for me.

That probably won't resolve your issue. It's not that the bootloader is the problem - it's the implementation of the WDT in the bootloader and how the bootloader is handing WDT events that is the problem. Getting rid of the bootloader doesn't get rid of the problem - it just changes it so that you need to implement the handling of WDT on your own. It is certainly possible to burn a sketch to an arduino without the bootloader(Here is some documentation about it.) But without a bootloader you will not be able to load a sketch via bluetooth.

Is there a particular reason you're using a WDT to reset the arduino? There are several other methods(here is an instructable detailing these methods) that you could use that would get around this.

WDT is the only software only solution but I guess I will go with using one of the pins to trigger the reset.

Enabling watchdog timer system restart and waiting in a loop until reset is a legitimate way of SW resetting the µC as is using watchdog for catching µC's misbehavior which can be caused by various reasons.
However, some precautions have to be made when using watchdog system reset because on all AVRs that also have watchdog interrupt the watchdog with prescaler set to 0000 = 16 ms remains active after watchdog system reset condition. It is therefore responsibility of a programmer to clear MCUSR and to disable watchdog timer as soon as possible after occurrence of such a condition. Since LPM routines for initializing .data and .bss sections can last longer than watchdog timeout interval, the code for disabling the watchdog must be placed in .init3 section and the contents of MCUSR can optionally be saved for later reset source examination. Here is the code that does the described:
uint8_t mcusr_copy __attribute__ ((section (".noinit")));
void disable_wdt(void) \
     __attribute__((naked)) \
     __attribute__((section(".init3")));
void disable_wdt(void) {
  mcusr_copy = MCUSR;
  MCUSR = 0x00;
  wdt_disable();
}

However, the problem may arise when using a bootloader which does not account for the possibility of watchdog system reset condition. If that is the case, watchdog timeout will happen inside bootloader (which is executed the first) before the above code will have the chance to disable the watchdog timer and µC will be stuck in an endless reset loop. Since reseting the µC will not clear WDRF flag in MCUSR register (it can be cleared only in software or by Power-on reset) the only way will then be to cycle the power and upload a new code when watchdog timer is still not activated by previous code. WDRF in MCUSR register must be cleared before wdt_disable() because WDE can not be cleared if WDRF is still set - therefore the order of the instrucions in the above code is very important. The function placed in .init3 section must not be called from later code.

Remove watchdogs flag at init is one solution. I am using optiboot 8.0 and it works perfect.
// Function Pototype
void wdt_init(void) __attribute__ ((naked, used, section(".init3")));

// Function Implementation
void wdt_init(void)
{
    MCUSR = 0;
    wdt_disable();
    return;
}

You can restart the Arduino with this command:
asm volatile ("  jmp 0");

This only does soft reset and will not reset it to defaults completely.


text:
Garbled high bits on serial output
I'm trying to send the byte 0x5A (0b01011010) on the serial output of an Arduino Due. My program is based on this example project, but I've stripped out all the unrelated parts:
#![feature(lang_items)]
#![no_std]
#![no_main]

extern crate sam3x;

pub mod rust_base;
use sam3x::*;
use sam3x::hal::peripherals::{Peripheral};
use sam3x::drivers::led::{Led};
use sam3x::hal::rtt::{init_timer, wait_ms};
use sam3x::hal::pmc;
use sam3x::hal::uart;

#[link_section=".vectors"]
pub static VECTOR_TABLE: VectorTable =
    VectorTable {
        reset_handler : start,
        exceptions    : [0; 14],
    };

fn start() -> ! {
    init_timer();
    pmc::enable_peripheral_clock_0(Peripheral::PioC);

    let led = Led::connect(Peripheral::PioB, 27).expect("Wrong pin for led.");
    let tx = uart::Tx::init(uart::BR_9600);

    let mut led_on = true;
    led.on();
    loop {
        tx.write_byte(0b01011010);

        wait_ms(250);
        if led_on {
            led.off()
        } else {
            led.on()
        }
        led_on = !led_on;
    }
}

As you can see, all I do is send out the byte 0x5A four times a second, with some LED blinking just to show the program is running.
My problem is that if I connect a serial terminal program with 9600-8N1 settings, I am not getting 0x5A; instead, I am getting mostly 0xBA, and sometimes a 0x9A slips through.
Writing out the bits:
0101 1010    5A
1011 1010    BA
1001 1010    9A

Note that the lower nybble is always correct, which is why I don't think it's a serial communication setting issue; also, it's pretty clear from uart::Tx::init's implementation that it defaults to no parity bits.

It seems this error is specific to the Rust ARM library I am using; quoting from https://github.com/klangner/sam3x/issues/9:

It looks that at bound rate=9600 the timer sends data with the speed of ~888. And then computer can't understand the output.

Based on this, I started playing around with the baud rate I pass to the library when initializing it, and using 11000 instead of 9600 empirically seems to work (i.e. I am seeing a steady stream of 0x5A on my PC receiving at 9600).