text:
Timer function without the use of a library
Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.
unsigned long previousMillis1 = 0;
unsigned long currentMillis1 = millis();
unsigned long previousMillis2 = 0;
unsigned long currentMillis2 = millis();
unsigned long previousMillis3 = 0;
unsigned long currentMillis3 = millis();

bool timer1(int preset){
  unsigned long currentMillis1 = millis();

  if(currentMillis1 - previousMillis1 >= preset ){
    previousMillis1 = currentMillis1;
    return true;
  }
  else{
    return false;
  }
}

bool timer2(int preset){
  unsigned long currentMillis2 = millis();

  if(currentMillis2 - previousMillis2 >= preset ){
    previousMillis2 = currentMillis2;
    return true;
  }
  else{
    return false;
  }
}

bool timer3(int preset){
  unsigned long currentMillis3 = millis();

  if(currentMillis3 - previousMillis3 >= preset ){
    previousMillis3 = currentMillis3;
    return true;
  }
  else{
    return false;
  }
}

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

void loop() {
  if(timer1(1000)){Serial.println(1);}
  if(timer2(2000)){Serial.println(2);}
  if(timer3(3000)){Serial.println(3);}
}

What is a "timer function"?

Do not store times in signed numbers! Your computation of currentMillis1-previousMillis1 is prone to signed integer overflow, which in C and C++ yields undefined behavior. Meaning it's always incorrect, even if it luckily works with your current compiler. millis() returns an unsigned long.

edited for the unsigned. Thanks for that.

Actually, signed longs are just as fine, as long as you compare T2 - T1 > duration. What is actually prone to integer overflows is T2 > T1 + duration. That is, assuming T2 is always "later" than T1 and the difference between them fits in the type.

Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.
Here it is easy: the only difference between your timer functions is
that they use a different previousMillis variable. Also, the name of
the currentMillis variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a reference to
the relevant PreviousMillis.
bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

And you use it like this:
void loop() {
  static unsigned long previousMillis1;
  static unsigned long previousMillis2;
  static unsigned long previousMillis3;

  if (timer(previousMillis1, 1000)) Serial.println(1);
  if (timer(previousMillis2, 2000)) Serial.println(2);
  if (timer(previousMillis3, 3000)) Serial.println(3);
}

I took the liberty of making all the previousMillis local to loop(),
since they are only used there. Making them static means their values
are remembered between call to loop(), much like global variables.
In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are explicitly manipulating
addresses, while this is implicit with references:
bool timer(unsigned long *last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - *last_time >= period) {
    *last_time = now;
    return true;
  }
  return false;
}

void loop() {
  /* [...] */
  if (timer(&previousMillis1, 1000)) Serial.println(1);
  /* [...] */
}

The next step in code modularity would be to wrap this timer function,
together with the associated data (last_time and period), inside a
class:
class Timer
{
public:

  Timer(unsigned long _period)
  : period(_period), last_time(millis()) {}

  bool shouldRun() {
    unsigned long now = millis();
    if (now - last_time >= period) {
      last_time = now;
      return true;
    }
    return false;
  }

private:
  unsigned long period;
  unsigned long last_time;
};

Then, you would use it like this:
Timer timer1(1000);    // period = 1000 ms
Timer timer2(2000);    // period = 2000 ms
Timer timer3(3000);    // period = 3000 ms

void loop() {
  if (timer1.shouldRun()) Serial.println(1);
  if (timer2.shouldRun()) Serial.println(2);
  if (timer3.shouldRun()) Serial.println(3);
}

Thank you for the input. It is very helpful. I understand classes and objects, but not so much pointers. The main reason I have 3 separate timer functions is because I tried with one single function, however, it would not work correctly, as it only printed the one second timer. Can you at least explain how pointers would work to get around this and allow all 3 timers to function properly? Also, if you don't mind, I would like to see how you wrote the class

If your single function version did not work, that was a bug. You may want to post that buggy code here if you want people to explain what was wrong. If you do not understand pointers, well, this is a big topic that requires some good book or tutorial, some patience, and careful study. Not the kind of thing that can be easily explained here. I edited my answer to include a version with pointers and a class.

I have experience using industrial controllers. Can i ask, is it similar to "indirect addressing" or "indexed addressing"?

I have no experience with industrial controllers, but pointers are related to “indirect addressing”, in the assembly sense of the term.

You can simplify a lot by using arrays. The example code below just uses a single variable (array) to store all the time intervals you are interested in.
const int NUMBER_OF_TIMERS = 5;

unsigned long intervalStarted [NUMBER_OF_TIMERS];

void resetTimer (const int whichTimer)
  {
  if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
    return;   // sanity clause
  intervalStarted [whichTimer] = millis ();
  }  // end of resetTimer

// interval in milliseconds
bool timeUp (const int whichTimer, const unsigned long whatInterval)
  {
  if (whichTimer < 0 || whichTimer >= NUMBER_OF_TIMERS)
    return false;   // sanity clause
  return  millis () - intervalStarted [whichTimer] >= whatInterval;
  }  // end of timeUp

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Starting ..."));
  }  // end of setup

void loop ()
  {

  if(timeUp(0, 1000))
    {
    Serial.println(1);
    resetTimer (0);
    }  // end of if timer 0 up

  if(timeUp(1, 2000))
    {
    Serial.println(2);
    resetTimer (1);
    }  // end of if timer 1 up

  if(timeUp(2, 3000))
    {
    Serial.println(3);
    resetTimer (2);
    } // end of if timer 2 up

  }  // end of loop

I have allowed for 5 "timers" in the code but only used 3 to be consistent with the original post. You can see that you can have as many as you want (until you run out of RAM) with only an overhead of 4 bytes per "timer".
Two functions are provided. One checks if a nominated interval is up, the other one "resets" the timer by setting its start time to now. The checking function should work correctly even during millis() wrap-around, providing you are not trying to time more than 4294967296 milliseconds in one hit (49.71 days).
Note that the timer numbers are zero-relative, so the first timer is timer 0. You could make them one-relative if you prefer that with a slight adjustment to the two functions.
You could also, if you chose to, put the resetTimer function call inside the timeUp function (if the time is up) so that the timer automatically resets. I didn't do that because I think starting timing, and detecting the end of a period could be two different things. For example, when you boil an egg, you start timing from the time the egg goes onto the boil, not from when you last cooked an egg.

I do not think an array significantly simplifies the code unless you are going to loop through it... which you could do if you attach a callback to each “timer”. Anyway, +1 for providing a rollover-aware example!

It depends on what kind of efficiency you want. In coding we can often between better execution speed and less memory required. And in the case of Harvard-architected machines such as the AVR devices, which have separate memories for code and data, there may be a further balance between those, too.
But it looks like you're trying to reduce your code space requirement. So notice how alike your three timer functions are. I'd combine those into one, and pass another argument that indicates which timer value to operate on.
Secondly, (and this is probably a bug more than an inefficiency), you have three globals that are not being used (in your example, anyway): long currentMillis1, ..2, & ..3. You have redeclared each of those names as a local variable in the respective timer function, which, within that function over-rides (hides) the global declaration. There is no code that uses those globals.

Happened across this page which explains Arduino timer interrupts with out using any libraries.  The Atmel timer hardware is discussed and the sketches not only control the hardware directly but also include the actual interrupt service routine.  So addresses the OP's question very well.

Those lines like
currentMillis1;
are completely useless
You do not really have "timers", especially if your goal is to be more efficient. What you have done is to create some convoluted way to perform a test that could be done as:
int PERIOD = something;
for (int target = millis() + PERIOD; millis() < target;);
If you really care about efficiency and timed actions, check some library that deals with timer interrupts.
Start reading the code of existing libraries and try to understand it.
Chances are that who wrote them knew a great deal more than you know. You will learn much more from first reading the code than trying to accomplish something that is clearly too much beyond your current knowledge (the fact you think what you did is an optimization proves it).

First of all, yes, I took the lines that are useless out.
Second of all, I am highly offended by your last comment. You obviously did not read my statement and question above ASKING if there was a way to optimize it. I never stated that I optimized anything.
Lastly, isn't this what stack exchange is for? To ask questions? Not everyone is a professional at programming.

I really didn't mean to offend you.But to me, your question shows that you are lacking some concepts. Interrupts, for example. Writing your own optimised ISR would be a way to optimize for real. But is it worth? What you did is likely to be used in a busy loop, doing polling on millis().
Not very optimized, generally speaking. Is it good enough for you? You are the only one who knows, until you say more. So you get the same answer: check if any of the existing libraries works for you, understanding what it does. If it doesn't work for you, come back explaining why it doesn't work for you.

Your single line example not only does something completely different from the OP's code, its also broken: think about what happens when the first call to millis() yields something bigger than INT_MAX.

I agree with @EdgarBonet here - your answer is incorrect and even offensive, for no good reason.

authors: الاسم الاول اية


text:
Simple question about && vs ||
I want to skip all '\r' and '\n' chars and I have IF statment:
char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

VS
char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
   mAnswer[mAnswerLength] = c;
   mAnswerLength++;
}

What is better and what is the difference?

Think about it "logically" (pun intended...):
You read a character.  Say it's "A".  You then compare it to both '\r' and '\n'.
char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR or A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR or CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  If it's OR, then if either part is true then it will be true.  So since CR is not LF it will add it.
Now:
char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR and A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR and CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  Just as before.  However, if it's AMD, then if BOTH parts are true then it will be true.  So since CR is CR it won't add it.
In summary, the first one will ALWAYS be true since one half is always going to be true.  The second one will ONLY be true if BOTH parts are true.  So the first one just plain isn't going to do what you want.

Thanks for this. Just needed someone explain this :) My head is overflowed...

You can rewrite first condition to be more obvious
if (c != '\r' || c != '\n') {

as
if (!(c == '\r' && c == '\n')) {

Which is always true (c have only one value), i.e. it makes no sense.

|| means logical OR
&& means logical AND

Thanks, i know the meaning.  I want to know the difference and which one is better in this situation. My head is not working properly at the moment;)

source: Stack Exchange

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

sort: votes


text:
Parallel connection to Wiegand 26bit RFID readers
I have situation where I need to read RFID cards. There is already installed Roger security system, Roger gate control board and two rfid readers in parallel. By default board and RFID readers communicate in RACS(some sort of coded protocol) but at the moment system is configured to communicate in Wiegand26. Earlier I used chinese wiegand26 reader with Arduino with no problem.
With Arduino I need to read card read by RFID readers.
Then I process data and make HTTP POST request.
Arduino is supplied from Roger board ~13.5V DC I do not get anything in arduino, even if I connect RFID readers directly to arduino.

CLK is D0 to Arduino Nano pin 2
DTA is D1 to Arduino Nano pin 3

This question is not related only to Arduino.
I want to ask is it possible to do? To read data maybe I need some additional electronics?
What i also noticed that when Arduino is connected in parallel the Roger board not always reads the card from RFID readers.
Roger PR402-BRD
And two readers PRT62LT

This is copy of Electronics.stackexchange

It looks to me like the Wiegand interface is an open-collector interface (like I2C), which is why they can be wired in parallel like that.
As long as the Arduino has both connections set to INPUT (not INPUT_PULLUP and certainly NOT OUTPUT) it shouldn't interfere at all.
By the way, for Wiegand, the two signals are DATA0 and DATA1.  To transmit a 0 the DATA0 line is pulled low. To transmit a 1 the DATA1 line is pulled low.
You should also check that the idle voltage on the lines is indeed 5V as it should be.  Anything more than that could cause the Arduino to chip the voltage to 5V through its internal ESD protection diodes.
Also you must ensure that the Arduino has its ground pin connected to the ground connection of the Wiegand system (which it should be since you are powering it from that).

i am using https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino library pinMode(D0Pin, INPUT);     // Set D0 pin as input
pinMode(D1Pin, INPUT);     // Set D1 pin as input
attachInterrupt(0, ReadD0, FALLING); // Hardware interrupt - high to low pulse
attachInterrupt(1, ReadD1, FALLING); // Hardware interrupt - high to low pulse

As you can see pinMode(D0Pin, INPUT);. Checked the voltage and for my surprise its ~11,5V DATA0 - GND -> 11,5V and same with DATA1 - GND -> 11,5V and yes as you said Arduino chips it to 5V when connected

That could be your problem then - the Arduino would be trying to clamp that to 5V which would cause problems I would guess.  It could also damage the Arduino.  You would probably need to isolate the Arduino from those lines.  Optocouplers would probably be your best bet.

Hmm, but if i will put optocouplers then led in optocoupler will lower the voltage too? I mean resistor+led in series.

Depends on the amount of pullup resistance.  Another option could be to use MOSFETs.  You can calculate the pullup resistance by measuring the current to ground then using Ohm's law - you can then work out a suitable resistance for the LED.  Or with a MOSFET you just need to ensure the threshold level is in the right region to switch on/off at the right times. There's all sorts of ways of doing it.  Op-amps could even be used to apply a fractional gain.

With optocoupler i would need this circuit http://i.stack.imgur.com/edSjI.png ? Will it work and not interfere Wiegand?

Also i am thinking that MAX232 chip should work here?

If the resistor is high enough (which also relies on the pullup resistor being low enough) then it may not interfere, but chances are it will.  The MAX232 is a great idea!  Certainly worth giving it a go.  Could be the best bet all round really.

Let us continue this discussion in chat.

So i will need to invert the signal on Arduino? If i put +12 to MAX232 pin 8 on pin 9 i read 0V. attachInterrupt(0, ReadD0, FALLING); line will have to be changed to attachInterrupt(0, ReadD0, RISING); ??

Yep.  The MAX232 inverts.

If you would like to use more than 1 Wiegand reader, technically it should be possible to use AVR pin change interrupt. In this case you can use ANY 2 pins, even analog pins.
For example, see http://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/
UPD: There is informationon Wiegand timing, might be useful:
http://proxclone.com/wiegand.html

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


text:
CAN Bus without Transceivers
I am trying to set up a CAN-bus with its two nodes on the same Arduino. By Using an Arduino DUE without any transceivers. As my first experiment, I want to send a message from one CAN unit to the other. But so far I have not been successful to see any signal on the bus. (I am using an Oscilloscope)
Here is the detail of my effort:
I have used this(1) library, and I want to run the CAN_EchoTest example(2).
As for the physical layer, I have created a circuit, according to a Method that is suggested here(3), here(4), and here(5). I set the transmission rate to 5Kbps, (lowest possible value provided by the library), to make sure that noise and propagation effects are minimal.
I implemented this mentioned Method to the Arduino board, using the Board's Schematics(6). In other words, I assumed that:
CANTX1 in the schematics, refers to PIN with the label '53' on the board.
CANRX1 in the schematics, refers to PIN with the label 'DAC0' on the board.
CANRX0 in the schematics, refers to PIN with the label 'CANRX' on the board.
CANTX0 in the schematics, refers to PIN with the label 'CANTX' on the board.

And I assumed the library that I am using configures the mutual PINS (DAC0 and 53), in a way that CAN controllers will be using them exclusively. I am not sure about the pair of diodes that I used: Vishay SS34A.
what is missing/wrong? Please be patient regarding any rookie mistakes. I can Provide further information if requested.
Thank you in advance
(1) github.com/collin80/due_can
(2) github.com/collin80/due_can/tree/master/examples/CAN_EchoTest
(3) www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf
(4) electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus
(5) www.keil.com/download/files/canprimer_v2.pdf
(6) www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

You might wanna look at this question. http://electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus. And you should check weather an atmega328p-pu has support for it.

Thank you man, That was supposed to be link number 4, I have made a mistake of copying the same link for number 4 and 5.

I see... I'm not that familiar with CAN so I won't be able to help you out a lot. I've only repaired and modified an existing CAN system with transceiver. Though, I've edited your question by making them actual links. It needs to be approved now.

Ensure diode polarities are correct. Method should work ok. Using voltmeter measure RX pin voltage when no "traffic" - should be "high". Measure when sending - should drop. SS34 diodes are OK. Resistor can probably be say 10k but 3k3 should be OK.

SS34 datasheet here Ensure line side goes to TX pins. Use meter diode-test or Ohm test.

I made it work. I guess the problem is that the library acts irrational when you try to set a frequency other that the library's default frequency: CAN_DEFAULT_BAUD. (defined in due_can.h).
for changing the frequency I just change the default value itself.

You will have to play some games to make it work.  CAN is a bus with dominate and recessive states.  This is how it arbitrates.  When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive.  At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.
You can simulate this with a few transistors (not real CAN but will work).  Monitor the bus with the receive side and drive it with the transistor with a pull up resistor.  When the transistor is on that is the dominate state when the transistor is off that is the recessive state.  This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send.  Transceivers are very cheep on eBay and they have the Maxim chip which is very good.
Good Luck,
Gil


text:
Arduino Micro + Max4466 - Noise on A0
I've got an Arduino Micro, and a MAX4466 ECM / AMP breakout board (https://www.adafruit.com/product/1063). I'm powering the Arduino Micro from the USB port.
On the MAX4466 (to the Arduino), I've wired VCC to 3.3v, GND to GND, and OUT to A0. I've also wired 3.3v to AREF.
Using the following code, I'm noticing significant noise spikes on the output, as shown in the graph below.
I'm not entirely sure what I've done wrong here, and would appreciate any input / criticism that could lead to getting a clean signal.

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

void loop()
{
   Serial.println(analogRead(0));
}

And if you sample at exactly 50Hz or a multiple thereof?

@IgnacioVazquez-Abrams I've just taken another sample, both with the above code, and with the above code, with addition of a call to delay by 20ms per sample. This screenshot shows the result: http://s21.postimg.org/4fplz8g8n/Screenshot_from_2015_06_27_06_00_54.png. As you can see, the noise is much lower now, and I'm not seeing such massive peaks any more..although there are still some peaks, at a much lower amplitude.

You could average the samples to get a lower noise. But it kind of depends on what you are trying to achieve. As you notice the noise only produces values lower than expected, not higher. So if you want to e.g. detect a clap, this kind of noise doesn't really affect your program, as you'd measure peaks. (PS try increasing the baudrate of the serial connection and see what that does.)

You could try adding a resistor between 3.3v and AREF or even better an inductor.

@Gerben thanks for the comments. I've actually got a sketch with 4 frame averaging ready, just haven't had a minute to test it yet :) RE the resistor, I've read the same about between A0 and GND. I'll see if I can pick up a few different resistors later and give them a try :) Will report back

Try this: Aim is to isolate mic module from any Arduino or supply noise. | Measure module current with a milliammeter. Data sheet here for 4466 - likey current uncertain but seems likely to be < 1 mA. Maybe not. Add a series R that drops about 0.3V (Vcc min = 2.4V) R max = 0.3V/mA_drawn. eg if I = 1 mA the Rn=max = 0.3/.001 = 300 Ohms - > use 270 Ohms or less. Add a largish capacitor at module from Vcc to ground and feed Vcc via Ras above. C = 100 uF probably OK. Higher does not hurt.

Thanks @RussellMcMahon for your input. I wasn't able to get anything from my local Maplins as they were closed, but I'll drop in either tomorrow or Monday. I'll also update this question with a photo of my (surely dreadful) layout. I don't have a millammeter available to me, but I'll see if I can acquire one. This was meant to be a simple little audio recorder experiment, so if the cost of the equipment is going to be relatively high, I'm not sure I can warrant it right now..we'll see. I'll be back!

@Seidr   "milliammeter" can be almost any modern DMM (digital multi-meter) -  essentially any of these can measure up to 200 mA and cost can be modest and they are utterly invaluable when doing anything with electronics. | Aim overall is to feed clean power to module and to get clean signal back. Ground paths should be direct and if a number of things are powered use "star" grounds - all grounds radiate from a single point - no loops formed.

Pulled out my ollllld multi meter, and it's reading a current of 2mA. I'll try going shopping for parts again tomorrow. Thanks :)

My thanks for all your input. I believe I've discovered the cause of the noise - the serial port. The higher the baud rate goes, the higher the frequency of the noise. I've also tried the same setup on a friends Arduino Uno, and could not detect any noise. I'm going to try this with a stand alone power supply tomorrow, and see if that resolves the noise issues or not. Using a small capacitor to ground did help slightly also :)

Ok - so I suspected that it was the Arduino at fault.. Turns out it's a cheap Chinese clone. After purchasing an official Micro, and wiring up the same component, I'm getting a nice clean signal (bar a small amount of acceptable noise), which is reflecting input tones accurately. Thanks again for all the input!

I copy-paste your last comment as an answer. Please, accept it to close your question.

The OP itself solve it:

Ok - so I suspected that it was the Arduino at fault.. Turns out it's
  a cheap Chinese clone. After purchasing an official Micro, and wiring
  up the same component, I'm getting a nice clean signal (bar a small
  amount of acceptable noise), which is reflecting input tones
  accurately. Thanks again for all the input!

Interesting plot. Gives me the impression that your reference is sagging, consider adding some local storage (tant/ceramic capacitors) across the cpu's power in pins and across the cpu's Reference pin. Would also be interesting to know if adding more delay between measurements would improve performance. Thanks for sharing you issue.

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


text:
Is it possible to control the speed of DC motors with Arduino's analogWrite() using analog pins?
I'm trying to control the speed of two DC motors that are connected to a dual H bridge. I always used digital PWM pins with analogWrite() to change the speed, but since I'm making a project that will be using most of the digital pins, I wonder if I can use analog pins instead.
P.S. I know I can use analog pins as digital pins to free the digital PWM pins, but I'm not interested in doing that.

Well, I am confused. The Arduino reference page, the "Description" of analogWrite() also states: "Writes an analog value (PWM wave) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. " So can it or can it not?

analogWrite() is for writing to the pins that support PWM.  As far as I can tell you can't use it for writing to pins A0, A1, etc...  Its a really confusing name for a function

No, you can't.  As it says in the Arduiuno reference page for analogWrite(): "The analogWrite function has nothing to do with the analog pins or the analogRead function."
You can use the "analog input pins" (A0..A5) of Arduino for analog input, or as digital inputs or outputs.  They cannot be used for PWM(digital)-output.  Only digital pins, and only those specifically stated for PWM-output, can actually be used for PWM output (unless you go down the path of software-PWM, though I would hesitate to do that for an H-bridge).

depends on if the OP means an "H-bridge" with a control input stage that takes a single PWM input. I agree it would be a bit dicey to go that route with two inverted SoftPWM signals coming from the AVR.

You can't do it with the analogWrite function as that is reliant on physical binding beween certain pins and hardware timers inside the AVR. But you can always use SoftPWM because the the analog pins can generally be used as digital pins just as well.

Yes, multiwii project does 'bit banging' software pwm on analog pins, but a library would be faster to implement

You can use multiplexers if you are running out of digital pins or SPI PWM drivers for the motors. There are many multichannel drivers out there like TLC5940, put a power stage after them and you're done.
*Use Soft SPI on the analog pins to control the driver.

The TLC5940 is designed for LEDs, would it be adequate for motor control?


text:
Testing tri-state pin - erroneous results with internal pullup
I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a status pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.
The algorithm I wrote is very simple:
Set pinTest to input, no pullup.
Is pinTest high?
    Yes - pinTriState is HIGH, done.
Set pinTest to input with pullup.
Is pinTest high?
    Yes - pinTriState is HiZ, internal pullup causes high reading.
    No - pinTriState is LOW, 'cancelling out' internal pullup.

However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno->Micro and Micro->Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time pinTriState stays at in a given state to keep pinTest guessing, but it's ultimately only an elaborate way of cycling through the three states.
#define pinTest 2
#define pinTriState 3

int state = 0;
char stateCh = '?';

int sect1;
int sect2;
int sectMax;

void setup()
{
    Serial.begin(9600);
    randomSeed(analogRead(A0));
    sect1 = random(1, 20);
    sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
    sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
}

void loop()
{
    // PART (1) Code to toggle three states of a tri-state pin
    if (state == 0)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, HIGH);
        stateCh = 'H';
    }
    if (state == sect1)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, LOW);
        stateCh = 'L'
    }
    if (state == sect2)
    {
        pinMode(pinTriState, INPUT);
        stateCh = 'Z';
    }

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be
    pinMode(pinTest, INPUT);
    if (digitalRead(pinTest))
        Serial.println(" - HIGH");
    else
    {
        pinMode(pinTest, INPUT_PULLUP);
        if (digitalRead(pinTest))
            Serial.println(" - HiZ");
        else
            Serial.println(" - LOW");
    }

    (state == sectMax ? state = 0 : state++);
}

The necessary pins are connected with a single wire. If I upload the code to two boards I remove PART (2) on the 'triState' board and PART (1) on the 'testing' board. In this case, stateCh has no function.
For a single-board setup, I get the following output:
H - HIGH
H - HIGH
...
L - LOW
L - LOW
...
Z - HiZ        <-- the first Z is correct 95% of the time
Z - HIGH
Z - HIGH       <-- the remaining Zs are a mixture, biased heavily towards HIGH.
Z - HiZ
...
H - HIGH       <-- H always gives HIGH
...

It makes no difference if I change the operating order of pinState. I've thrown in delay(100); between almost every other line, again to no avail.
I tried with a 22k, a 33k, and a 47k external pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. Part (2) becomes:
// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be
pinMode(pinTest, INPUT);
pinMode(pinPullup, INPUT);    // connected to pinTest via resistor
if (digitalRead(pinTest))
    Serial.println(" - HIGH");
else
{
    //pinMode(pinTest, INPUT_PULLUP);   <-- not anymore
    pinMode(pinPullup, OUTPUT);
    digitalWrite(pinPullup, HIGH);    // pulls pinTest to Vdd
    if (digitalRead(pinTest))
        Serial.println(" - HiZ");
    else
        Serial.println(" - LOW");
}

Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!

"but HiZ returns a mixture of HiZ and HIGH". That's exactly what you expect for an input pin with no pull-up, and a high-impedance (or no) connection. I would be surprised if it didn't alternate between LOW and HIGH somewhat randomly.

@NickGammon: But the input is pulled up - pinMode(pinTest, INPUT_PULLUP) is the first line in the else block. And that doesn't answer why it works with an external pull-up resistor that's turned on at the right time in leiu of the internal pull-up.

Yes, but setting the pin to input with no pull-up or pull-down (your first test) gives meaningless results. See my code example in the amended reply. It works.

I understand your point know. However, that doesn't explain why using an external pullup doesn't exhibit the same problem - bearing in mind that the 'up' leg of the resistor is switched between a HiZ and HIGH source, i.e.  it is switched in and out the same as the internal one would be. Please note that I'm not disagreeing - I'm happy that I can solve this with a simple pull-down. Is it that the leakage of pinPullup happens to be biased towards Vcc, keeping the resistor slightly pulled up at all times?  Why never pulled down by a leakage?

A pin which is input connected to a high-impedance source is undefined. So I won't try to explain why undefined is more often high than low. Maybe right now an adjacent pin pulls it high. In another scenario it might be pulled low. Your external pull-up solution is, if I remember correctly not at all the same thing because the pin always has a defined state.

No, pinPullup (connected to pinTest through the external resistor) is set to an input (HiZ, so undefined, n'est pas?) except for the second digitalRead(pinTest), at which point it's output HIGH. In my view that copies the electrical characteristics of the internal pullup. I've edited the question to add the code for PART (2) when using an external pullup, in case it's still not clear. Ultimately it's a moot point; your reasoning for the error with the internal pullup is enough to assuage my hair-pulling confusion, and your solution to the problem is a suitable answer.

The internal pull-up is around 50k. So, install an external pull-down (to ground) of a somewhat higher value, like 1M.
Now:
Go to input mode, no pull-up. Get a reading. Turn on the internal pull-up. This should overpower the pull-down. If the reading changes, it was tri-state. Otherwise, if the reading doesn't change the external device is overpowering both pull-up and pull-down and you have the actual reading.
You may need a slight delay to allow the low-value pull-down to change the pin state.

Amended code to demonstrate:
// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be

pinMode(pinTest, INPUT);
delayMicroseconds (100);
byte firstReading = digitalRead(pinTest);
pinMode(pinTest, INPUT_PULLUP);
delayMicroseconds (10);
byte secondReading =  digitalRead(pinTest);

if (firstReading != secondReading)
  Serial.println(" - HiZ");
else if (secondReading == HIGH)
  Serial.println(" - HIGH");
else
  Serial.println(" - LOW");

(Only showing the part that detects the pin state, the rest is the same).
Output:
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH

As you can see, working perfectly. I needed a longer delay after turning the internal pullup off because the fall time was around 100 µs. This actually sounds reasonable, because the 1 megohm resistor will take time to discharge the capacitance on the pin.
So:

10 µs delay after turning the internal pull-up on
100 µs delay after turning the internal pull-up off

Theory for the delays
The Atmega328 pin is specified as having a maximum capacitance of 10 pF (10e-12). It is considered charged/discharged after 5 time-constants, where T = R.C.
Thus for an internal pull-up resistance of 50k and a capacitance of 10 pF, charging should take:
50e3 * 10e-12 * 5 = 2.5e-006 (0.0000025) -> 2.5 µs

And to discharge through 1M (1e6) ohms, discharging should take:
1e6 * 10e-12 * 5 = 5e-005 (0.00005) -> 50 µs

My observed results were about 2.5 µS for the charge, but more like 100 µs for the discharge, however I probably had considerable stray capacitance in the wires used in the test circuit.

Testing shows that with a 1 megohm pull-down resistor, it takes around 5 µS for the pull-up to change the pin's state. So a delayMicroseconds (10) or thereabouts should be plenty, to allow the pin time to react to the HiZ situation.

However discharging the pin through the 1 megohm pull-down takes somewhat longer. 100 µS or more. So the code above shows the longer delay after turning off the internal pull-up. The sensible thing to do would be to turn the internal pull-up off right after testing it, then it could be discharging while the code did something else.

Another option is to use an analog input pin instead of a digital input pin.
Create a balanced voltage divider using equal high value resistors (say 100KΩ each).  Attach the mid-point to the ADC pin, and one end to each of Vcc and GND.  The incoming status signal goes to the ADC pin:

Perform an analogRead() on the pin.  You will get one of 3 results:

Close to 0 = LOW
Close to 1024 = HIGH
Close to 512 = HiZ

When the pin is in HiZ the resistors will hold the voltage at around 50% of Vcc.  When the pin goes HIGH it will pull the pin up and override the resistors, giving a high value reading.  Similarly, when the pin goes low, the resistors will be overridden and a low value reading will be given.

+1; This would have been my solution if I had a spare ADC input. Alas, the Pro-Micro isn't blessed in the pins department.

For the 1M pulldown solution, turning off the internal pullup at the end of the pin check routine MIGHT give enough time for the pin to discharge, and it might not if the code can conditionally do very little else between pin checks.  If you want to leave out the 100 us delay, take care to ensure that your code will always do something that takes sufficient cycles for the pin to discharge between checks.

Nick Gammon's answer seems the most straightforward solution to your
problem, given that you cannot spare an analog input. It has however the
drawback of needing a delay of ≈ 100 µs. This may not be an
issue, but I just figured out a scheme that allows a faster read, and
may be of interest to some: instead of pull-ups or pull-downs, put just
a 10 kΩ resistor in series between the MPC73831's output and you
Arduino input. When you want to read the state:

Take a first reading with the pin in INPUT mode:

if you read HIGH, then your MPC is either HIGH or HI_Z
if you read LOW, then it's either LOW or HI_Z

Now, switch the pin to OUTPUT, write the opposite of what you just
read, switch back to input and take a second reading:

if you read what you just wrote, then your MPC is in the HI_Z state
if you read the same as before, then it's either HIGH or LOW.

Here is the implementation of this scheme:
#define HI_Z 2

/*
 * Read a 3-state pin.
 * Put a 10 kOhm resistor between the output and input pins.
 */
int read3state(int pin)
{
    int reading1 = digitalRead(pin);
    pinMode(pin, OUTPUT);
    digitalWrite(pin, !reading1);
    pinMode(pin, INPUT);
    int reading2 = digitalRead(pin);
    if (reading1 == reading2)
        return reading1;
    else
        return HI_Z;
}

I have tested this a few 104 times with an Arduino sending to
itself a pseudo-random sequence of LOW, HIGH and HI_Z. It works
reliably for me.
Caveat: This scheme relies on the pin being capacitively coupled to
GND or Vcc, and this coupling being stronger than couplings with other
signals in your circuit. If you fear this might not be the case, you can
put something like 100 pF from the pin to ground, but then you
should better wait a couple of microseconds before taking the second
reading.


text:
Uno Ethernet shield and TMP36 reading
I am just getting started with my Uno via the Vilros Ultimate Starter Kit. I've done all of the sample circuits and played around with a few other things.
Today I connected the Ethernet shield with the intention of building a temperature logger. I am finding that the output I get from the included TMP36 temperature sensor is much different with the Ethernet shield installed.
The kit's sample circuit #7 for the temperature sensor connects the sensor directly to 5V and GND and the sensor output to A0. The loop code (compressed a bit for pasting here) looks like this:

float voltage, degreesC, degreesF;
voltage = analogRead(temperaturePin) * 0.004882814;
degreesC = (voltage - 0.5) * 100.0;
degreesF = degreesC * (9.0/5.0) + 32.0;
// Write to serial; omitting for brevity
delay(1000);

Without the Ethernet shield installed, a typical output I get from this looks like:
voltage: 0.81  deg C: 30.57  deg F: 87.02

That might be a little high but it feels close enough for what I'm going for at the moment (I don't have a reliable thermometer with me, but it's a warm day here). It's close enough, and is stable across readings.
With the shield installed, the exact same circuit and sketch outputs this:
voltage: 0.96  deg C: 46.19  deg F: 115.14

It's still very stable across readings but obviously way off. What could cause this and how can I fix it? I am not expecting the sensor to be perfectly accurate but the major discrepancy I'm seeing makes this unworkable.

Well, three years later I have the same problem. Did you eventually find a solution?

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


text:
Can't drive long NeoPixel strips with Due or Duemilanove?
I spent a significant part of today developing a sprite movement library for a 30-pixel NeoPixel strip using my Arduino Duemilanove (ATmega 168). It works like a charm. However, if I change N_LEDS to a significantly higher value, the program seems not to run. I can't get it to run on the Duemilanove for a strip of longer than 50.
In fact, (see the below code) a relatively high N_LEDS value won't even allow the test patterns to run as defined in setup(). This leads me to believe that inexplicably the constructor for Adafruit_Neopixel is failing.
A friend of mine (who has the ultimate application for this) is hoping to drive a strand of 750 LEDs using this code on an Arduino Due. I can't imagine memory would be an issue with the Due, so what's going on here?
Headers:
#include <Adafruit_NeoPixel.h>

#define PIN    6
#define N_LEDS 30      // <-- If this number is > ~50, nothing happens
#define MAXSPRITES 5
#define MIN_UPDATE_INTERVAL_IN_MS  15
#define MAX_UPDATE_INTERVAL_IN_MS  40
#define SENSOR_TIMEOUT_IN_MS  2000
#define SCANNER_WIDTH  9

Strip declaration:
Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

setup() and loop():
void setup() {
    randomSeed(analogRead(0));

    strip.begin();

    darkenStrip();

    manager = new SpriteManager();
    manager->Add(new TestPatternSprite(0, 0xff0000));
    manager->Add(new TestPatternSprite(5, 0x00ff00));
    manager->Add(new TestPatternSprite(10, 0x0000ff));
}

loop() {
    ...
}

Are there any coding mistakes in the above that wouldn't allow us to run this code on the Due? Or is this a known limitation?

Your question doesn't make it clear that you have tried the above code on a Due, and it failed. I thought you were saying that you tried it on a Duemilanove and it failed after a certain number of pixels. So you really have two problems? The number of pixels on the Duemilanove, and the fact that it doesn't light any (significant number of) pixels on the Due? Is that right?

Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.
750 LEDs sounds like pushing it for the low-RAM Arduinos.
You might want to look at NeoPixels Revealed: How to (not need to) generate precisely timed signals The author managed to drive over 1000 NeoPixels with a Duemilanove.
I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.

Ok, but upon reading my post, I think I wasn't entirely clear. Our desired configuration is on the Due -- we were only using the Duemilanove for testing. Any reason this wouldn't work on the Due?

The fact that it works up to some magic number would appear to indicate that RAM, and not something else, is the problem. So quite possibly it would work on the Due. Since the Due has 3.3V on its pins you would need to check this is adequate to drive the Neopixels, or maybe get a level shifter. Since the Due has 96k of RAM that may be enough to drive your intended number of pixels. There may possibly be some subtle issues in the library, regarding addressing that large an array, I couldn't say for sure. You would have to try it. :)

Thanks! But it doesn't. :-/  Perhaps the voltage is an issue; I believe the tests we had done on the strip only illuminated one pixel at a time. It's possible that maybe the voltage drop of lighting up multiple LEDs is enough to drop the voltage below some critical threshold for pixels. Still, I'd expect to see some kind of partial effect at least. Thanks for the help!

What is powering the Neopixels? Assuming they are running at 5V the 3.3V from the Due may be marginal in terms of being considered HIGH. I would try the level-shifter to see if that helps.


text:
LCD-Display showing wrong numbers
Hy guys,
I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.
I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.
Here's my code
// ESC_Calibration.ino
#include <Wire.h>
#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>
#include <Servo.h>

#define WHITE 0x7

Servo firstESC;
Servo secondESC;
int throttlePin = 2;
int firstESCPin = 2;
int secondESCPin = 3;

Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

    lcd.begin(16, 2);
    lcd.setBacklight(WHITE);
    lcd.setCursor(0, 0);
    lcd.print("throttle:");

    firstESC.attach(firstESCPin);
    secondESC.attach(secondESCPin);
}

void loop() {
    int throttle = analogRead(throttlePin);
    throttle = map(throttle, 0, 1023, 0, 179);

    lcd.setCursor(0, 1);
        Serial.println(throttle);
        lcd.setCursor(0, 1);
    lcd.print(throttle);

    firstESC.write(throttle);
    secondESC.write(throttle);

    delay(500);
}

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?
Thanks for your help in advance! :-)

As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.
That means, as the numbers increase you get, say,
4
10
48
89
194
309

etc.
When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:
309 (309)
194 (194)
894 (89 - the 4 remains from before)
484 (48 - the 4 remains from before)
104 (10 - the 4 remains from before)
404 (4 - the 04 remains from before)

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.
To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay.  There's two common ways of doing this:

Append enough spaces after the number to force an overwrite:

lcd.print(throttle);
lcd.print("   "); // 3 spaces should be enough for 3 extra digits

Format the data with snprintf():

char temp[5]; // enough room for 4 numbers and one NULL character
snprintf(temp, 5, "%4d", throttle); // %4d = 4 digits, right aligned
lcd.print(temp);

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned.  Also arbitrarily adding spaces after the number could overwrite things you want to keep.
You could also achieve a similar result doing it manually:
if (throttle < 10) lcd.print(" "); // 0-9 add one space
if (throttle < 100) lcd.print(" "); // 0-99 add one space
if (throttle < 1000) lcd.print(" "); // 0-999 add one space
lcd.print(throttle);

Just like with cats, there's many ways to skin this problem...

Alternatively call lcd.clear() to clear the entire screen and start adding text again.

@Gerben As has already been mentioned in both the question and my answer - that is very very bad since it makes the whole display flicker.


text:
What is the Arduino Nano maximum wattage?
Hello,
I am currently working on a DIY project and I would like to know the Maximum Wattage of a Arduino Nano with a ATmega328 processor. If anyone know what it is it would be a great help.
Ricky

Look in the datasheets for all the major components, and add them together. There's your answer.

A typical Arduino consumes around 40-50mA. Not sure of the Nano, but it'll probably be somewhere in that ballpark.  It depends what it's doing, of course, and even if you're running it as 5V or 3.3V.  The most accurate answer you can get is to actually measure the current as it enters the board.


text:
PS4 controller too touchy on the arduino RC car i built
I recently built an RC car from scratch and I am using a PS4 controller to control it.  I have an ESC of course but my problem is I barely touch the joystick and the motor is going so fast I cannot control the car. Here is the code and any help would be much appreciated.
/*
 Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
 For more information visit my blog: http://blog.tkjelectronics.dk/ or
 send me an e-mail:  kristianl@tkjelectronics.com
 */

#include <PS4BT.h>
#include <usbhub.h>
#include <Servo.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
//USBHub Hub1(&Usb); // Some dongles have a hub inside
BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
Servo servo1;  //Steering Servo
Servo servo2;  //DC Motor

/* You can create the instance of the PS4BT class in two ways */
// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
PS4BT PS4(&Btd, PAIR);

// After that you can simply create the instance like so and then press the PS button on the device
//PS4BT PS4(&Btd);

bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); // Halt
  }
  Serial.print(F("\r\nPS4 Bluetooth Library Started"));

  pinMode (3, OUTPUT);
  pinMode (5, OUTPUT);
  servo1.attach (3);
  servo2.attach (5);
}
void loop() {
  Usb.Task();

  if (PS4.connected()) {

    {
    servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
       //map values from the x-axis of the right analog stick
    servo2.write(map(PS4.getAnalogHat(LeftHatY), 0, 255, 0, 180));
       //map values from the y-axis of the left analog stick
    }}

    else

    {
      servo1.write (25);  // set servo motor to 0 point
      servo2.write (90);  // Turn DC motor off
    }


text:
Smart Chess-board (possibly using RFIDs?)
I'd like to make a chess-board with the ability to detect the position of each piece.
The solution that occurs to me would be to put an RFID reader under each square and put RFID tags on the bottoms of each piece.
However, apart from the obvious cost (64 readers!) I'm concerned that:

Maybe RFID readers are too large for the squares of an ordinary chessboard
RFID reader range is too large, so a reader might pick up pieces on neighbouring squares
How the hell would I connect 64 readers anyway? Could an Arduino handle it?

So, questions.
Is this just stupid? And is there a better technology to use for this kind of application?
If RFIDs are basically a sane solution, what are the issues/suggestions? E.g. which RFID readers should I go for? (Based on size, energy, convenience for this application). What boards would let me handle this number of them?

I think the RFID range is probably too high for accuracy, plus managing 64 readers would be hard (somehow you would need to multiplex 64 serial ports). What might work would be to have a single reader, and 64 fairly small aerials - one under each square. Then somehow organize to use each aerial in turn and check for the chip. Maybe all but one aerial could be grounded, for example. With small aerials the range might not be too large.

As I read your post an idea came to me that must be obvious in its simplicity.  Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base.  Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field.  We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.

I like the idea, it seems too simple, but maybe it would work perfectly. :)  There have been chess boards around for years that detect where the pieces are, they can't all have 64 RFID readers in them, so perhaps they use a system like what you propose. For that matter, what about a simple light detector, when you lift the piece, light hits the square underneath, so you know it has been lifted?

Yes. That might actually be a good, simpler solution.

Some early ones actually had buttons under the squares.  You'd have to push the piece you were about to move first, then move it to the other square and push it again.  Crude, but cheap and effective.  You can also add some sanity checking to your system.  "I know the piece moved to here. I know the pieces are in this position, so only these three pieces could possibly move to that position.  Which one did?  That one!"

A light-detector based solution would allow the players to use their own chess pieces rather than a specific set with magnets in the base. Furthermore, not having to rely on a particular set of pieces means you don't even have to play chess - you could implement a Draughts (Chequers) alternative software, or anything else played on an 8x8 board.

@chaaarlie2 - I like that idea however it would require that the board be modified (or already be somewhat transparent) to insert photo detectors beneath the board.  While I agree that needing a magnetic based for the pieces may be undesirable, so too might modifying the board.  I wonder how thin and small magnets could be?  I wonder if there are disc magnets with little width that might be easily attached to the base of pieces?

I'd say that constructing a board with light sensors is easier than constructing one with hall sensors + modifying pieces. Plus, if you're going with semi-transparent board topping, why stop at a passive interaction? You could add an LED beneath each square: when the player lifts a piece of the board, all the possible destination squares light up. Could be a great aid to teaching chess!

Neodymium magnets are tiny, at least when considering volume-to-strength ratio. Most chess piece sets would allow you to drill a small (5mm?) hole in the base and glue  a magnet into it. Not sure on the cost of those magnets though!

Brilliant idea but with one flaw: What happens when a pawn gets to the end of the board? How does this system know what someone has chosen to be?


text:
Breadboard Arduino not loading sketches
I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.
I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

GND -> Breadboard GND
5v -> Breadboard + rail
TXO -> IC pin 2
RXI -> IC pin 3
GND (GRN) -> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.
Any ideas on what might be the problem?

Do you have an actual USB-UART bridge or just a bare USB port?

Im using an FTDI breakout board from sparkfun
https://www.sparkfun.com/products/9716

Since you have 5V already, did you skip the power supply part?

No i still have the voltage regulator and the capacitors on the power rails

You used everything described on that page? Decoupling capacitors? The 16 MHz crystal? GND (GRN) - is not ground - hopefully you have that connected to DTR on the board (not GND). Try manually resetting the board by hitting the reset button on the breadboard, immediately after attempting the upload.

yeah, that was a typo, its not ground its DTR and yeah, everything in that tutorial, plus the .1μF cap

Your board configuration may well not match the baud rate of the boot loader (if any) allegedly present in your chip.

No need to put the italics on the "allegedly" I know it has the bootloader because pin 13 will put out a pulse when you first upload. On top of that its a part from sparkfun that is advertised to have the bootloader and the likelihood of 2 bootloaders going bad is pretty low.

Make sure you have a 16Mhz crystal attached to your board at the XTAL locations properly.
If you dont have one already, connect a 0.1uf capacitor (ceramic or metal film) to the reset pin for auto reset capabilities.
The avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00 issue is probably due to reset problems, where the arduino is not communicating to the computer. However, there are other possible reasons for this error. http://forum.arduino.cc/index.php?topic=28223.0
Double check that TX on the arduino is connected to Rx on the computer and Rx on the arduino is connected to Tx on the computer

If problems keep persisting, post more information so we can help you more.

Yeah, I have checked all of those, including a few solutions on the forum you recommended. Occasionally I the pin 13 light will blink while it is uploading, but its not every time and it is unpredictable. I think my 16mhz crystal might be bad or something. Im going to order a few of them and see if that helps.

Yeah, you should try that.

Do you have a picture or schematic of your design? That would help

To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial  connection:

you need to have a bootloader flashed on the chip
you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader
your programming software must use the same baud rate as the bootloader is expecting
you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader.  The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno.  You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.


text:
Attiny88 programming with Arduino
I want to program Attiny88 with Arduino IDE 1.6.5. I chose Attiny88  because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins. I found a library that support Attiny88 (https://github.com/TCWORLD/ATTinyCore) but it seams it does not support IDE 1.6.5 and generates errors when I burn bootloader or during ISP.
Is there any library to program Attiny88 with Arduino 1.6.5?

The older versions of Arduino are still available for download. Why not use an older version?

Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy  Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.
https://github.com/SpenceKonde/ATTinyCore

I went through the same problem finding the cores for the attiny 88 and found this
http://forum.arduino.cc/index.php?topic=320742.0
programming attiny88 & attiny828 with arduino
However, I have not yet found the core for the attiny88 at 12mhz (http://co.mouser.com/ProductDetail/Atmel/ATTINY88-AU/?qs=sGAEpiMZZMvqv2n3s2xjscfa4zIkTHJI8r77%252bczQD%252bE%3d)

Different speeds don't use different cores. Simply copy the existing entry in boards.txt and modify the clock rate there.

The above links don't lead to a working core. The bootloader does not work correctly.


text:
Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization
Hey all I am trying to convert a string into a uint8_t with the following code:
String data = "#255101987";
String tmp1 = data.substring(1, 3);

uint8_t first  = (String)tmp1;

I am getting the error of:

cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

Any help would be great as I thought adding (String) in front of the varible would solve the issue but it hasn't as you can tell.

Do you want the ASCII value of the character or do you want to parse the string contents as a number?

I presume from the substring call s/he expects to find 255 in the variable.

@NickGammon is correct. I am looking for the 255 within the string and needing to convert that to the uint8_t.

uint8_t first  = atoi (tmp1.substring(1, 3).c_str ());

Or even:
String data = "#255101987";
uint8_t first  = atoi (data.substring(1, 3).c_str ());

That worked great. Thanks for the help, Nick!


text:
How to read AC Voltage in arduino uno with 12V adaptor and usb cable.?
i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF.
I have Arduino, usb cable, external power supplier(adapter of 12V).
Can any one please suggest me how do i proceed for this ??

If your battery voltage is lower than 12 but sufficiently high to power the arduino (let's say 9V), you could put a white LED on the 12V line and a red LED on the battery line, like this:
         WHITE       RED
  _______|>|_________|<|________
 |             |                |
_|_          Arduino           _|_
 - 12V         |                -   Battery
 |_____________|________________|

This should work, as long as the LEDs can withstand the reverse voltage.
And you do not need to drive them from the Arduino.
If you still want to know the status fro mthe Arduino (mains or battery) you can sample the voltage level across the Arduino.


text:
Capacitive Sensor gets stuck
I want to use CapacitiveSensor library in order to make my own aluminum keys piano. I have seen many videos online showing projects like the one I'm trying to do, but for some reason mine doesn't work.
Here's my cuircit:

Here's my code:
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);  // 10M resistor between pins 7 & 6, pin 6 is sensor pin

void setup()
{
   //cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);
}

void loop()
{
    long start = millis();
    long total1 =  cs_7_6.capacitiveSensor(5);

    Serial.print(millis() - start);        // check on performance in milliseconds
    Serial.print("\t");                    // tab character for debug windown spacing

    Serial.print(total1);                  // print sensor output 1
    Serial.println("\t");

    delay(10);                             // arbitrary delay to limit data to serial port
}

This happens whenever I touch the aluminum foil:

First nothing happens (for ~1 sec), then it prints -2 as the capacity value, and when I release my finger from the foil it prints a very high value.
Anyone knows the reason for it? I'm searching for an answer for a long time and still can't find a solution...

The method that library uses is incredibly crude and shouldn't be considered reliable.  It's not proper capacitative touch sensing.  To do it properly you need four things that you don't have with that library: 1. a constant current source. 2. an analog input pin. 3. MOSFET switching for charge/discharge circuits. 4. a ground plane integrated with the touch sensor.  While under some circumstances it may appear to give capacitative touch sensor-like results, I certainly wouldn't use it for anything more than making an LED light up. Certainly never anything that controlled any motors or similar.

By the way, "-2" is "timeout" (something you'd never get with a proper CTMU).

Oh, and have you read all the things on the Arduino Playground page for the Capacitive Sensing Library?

The problem is that you're touching the foil.
The "capacitive sensing" used in that library is crude at best.
If you read the Arduino Playground page for the Capacitive Sensing Library it discusses a lot of the problems with the library, including grounding.  Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.
Also they talk about the value of resistor and the sensitivity.  With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil.  That's the value you're seeing as you remove your finger.  While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current).  For "absolute touch" it recommends no more than 1MΩ.
Of course, as I mentioned, that method is rather crude.  To do it properly you need to:

Discharge an analog input pin through a MOSFET to ground (low impedance).
Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
Remove the current and measure the voltage on the ADC input.
Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - Charge Time Measurement Unit.  If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.
Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them.  The sensor should also be insulated from direct touch.


text:
Highly sensitive light sensor to calculate number of times each color LED blinks
I am working on a project and got stuck on a point, and I hope somebody will guide me. I have a hardware device which has different color LEDs (green, red and yellow) and I have to calculate how many times each color LED glows for each mode of operation.
The LEDs that are connected to the device are pretty small and will blink only for a couple of seconds, ao I am looking for a very sensitive light sensor.
So what kind of light sensor do I have to use with Arduino UNO to achieve this?
Should I go for BH1750 or do you have any other suggestion?
Thanks in advance.

You don't need something that advanced. Simple LDRs or Phototransistors will do just fine. Just make sure you add some back tape, so no outside light can come into the sensors, as that will make it a lot easier for you. Just attach the sensors to the analog pins, with appropriate resistors.

@Gerben, I think you should add that as an answer. It is what I would use, too.

Thank you so much for your suggestion Garben , I will try to use Simple LDR , will you be able to suggest any specific model name related LDR's, So i that i can go and buy those particularly.

Like the OP wrote, you can use very simple sensors, like a phototransistor.
Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.
edit:
A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.
3DU5C ebay link  and  datasheet
It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.
OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.

Thank you so much for your suggestion Igor , I will try to use Simple LDR , will you be able to suggest any specific model name related LDR's, So i that i can go and buy those particularly.


text:
Arduino C++ library syntax
I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address.
Now onto the question. The library's .h file has the following statement:
#define H3LIS331DL_MEMS_I2C_ADDRESS     0x18//0x32
Is the 0x32 simply commented out or am I missing something here?
Thanks,
Emach

It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.


text:
RC servo misbehave using arduino and MPU6050
I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050.
I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

Serial.print("ypr\t");
Serial.print(ypr[0] * 180 / M_PI);
Serial.print("\t");
Serial.print(ypr[1] * 180 / M_PI);
Serial.print("\t");
Serial.println(ypr[2] * 180 / M_PI);

pitch_angle = (ypr[1] * 180 / M_PI) + 90;
roll_angle = (ypr[2] * 180 / M_PI) + 90;

Serial.print(pitch_angle);
Serial.print("\t");
Serial.println(roll_angle);

pitchServo.write((int)(pitch_angle));
rollServo.write((int)(roll_angle));

Without servo being connected everything works well.
But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted.
100 95
ypr 12.21   10.51   5.49
100 95
ypr 12.23   10.31   5.48
100 95
ypr 12.25   10.15   5.45
100 95
ypr 12.27   10.02   5.45
100 95
ypr -13.31  30.81   55.76
120 145
ypr 20.53   -21.36  -52.59
68  37
ypr 64.96   35.38   10.25
125 100

I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.
EDIT:
Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base.
Wiring is very simple:

Any idea? Thanks

Is the mpu6050 mounted on the servos or in a fixed position?

Please show your wiring. If it stops when the servo is connected it sounds like it is not getting enough power. If you tried a different power source, did you connect the grounds together?

I have just edit my question.. Thanks for effort.

As far as I can see from the photo, if you have the different power source connected (out of photo) it is also connected to the Arduino power (it is hard to tell). The external power should go to the servo only, not the Arduino. However the grounds need to be connected.

sorry for the photo - there is no external power source .. breadboard is connected straightly to the arduino

At the end two pull-up resistors and one capacitor solved the problem.
I followed instruction here:
http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/
Now it works well.. Thank you all.

Just FYI that particular mod is unique to what clone 521 board you have. Some clone makers (all that I have received) chose better pull up resistor values to begin with.

So a couple of ideas.
1) you need to be real careful with the MPU and overflows. You do not show all your code, but you must check for overflows, and ignore the data if one has occurred. I see in your print a stray negative value, that tells me you are not skipping bad data.
2) I dont know how 'tight' your loop is. You need to service the MPU a lot. In fact the sample you used, uses an interrupt to do so. I think the default update rate is about 100 times per second.  That may be too fast to make large changes in servo positions.  You will need to think about moving slower from point A to B if the difference is more than the servo can handle at that speed.
3) You are adding 90. With the numbers you have shown that is probably ok, but in your final code you need to be careful you do not exceed a servos range, 0 to 180.  the map() function is probably something you will want to use, instead of just adding 90.
4) My guess is that since it works for a second or 2, it is indeed over flowing data, and then goes to heck. Especially since you do not skip errors.
5) it takes the 6050 30 seconds or so to settle - so you will see large gyro drift (including PitchRollYaw) until it does. Probably not what your code is expecting.


text:
programming attiny88 & attiny828 with arduino
I found some information that the attiny88 and attiny828 can be programed from an arduino, similar to the programing of the attiny85/45, simply connecting the right pins. https://electronics.stackexchange.com/questions/98970/how-to-program-atmel-attiny88-not-45-or-85
However, what I have not been able to find out are the arduino cores (drivers) for the attiny88 and attiny828.
I wonder if the cores (or drivers) to program the attiny88 and attiny828 from an arduino are available somewhere or would they have to be constructed?.

I have never come across cores for them (not that I've been specifically looking for them though).

88 support seems to exist. See http://arduino.stackexchange.com/questions/12977/attiny88-programming-with-arduino

I would suggest you look into getting a real programmer. As @Gerben says there seems to be support for it, but if you buy an Atmel Programmer or a 3rd party programmer, you will make your life easier. If you plan on doing AVR programming you will eventually graduate from Arduino. There are a number of programmers that can program the ATTiny 88. http://www.atmel.com/tools/STK500.aspx?tab=devices.


text:
Error compiling code (tv-b gone)
I have been getting started with the Arduino and found a great project online called TV-B-Gone. It includes some code which I cannot compile. Yes I have included main.h and worldcodes.cpp.
/*
TV-B-Gone for Arduino version 0.001
 Ported to Arduino by Ken Shirriff, Dec 3, 2009
 http://arcfn.com

 The original code is:
 TV-B-Gone Firmware version 1.2
 for use with ATtiny85v and v1.2 hardware
 (c) Mitch Altman + Limor Fried 2009
 Last edits, August 16 2009

 With some code from:
 Kevin Timmerman & Damien Good 7-Dec-07

 Distributed under Creative Commons 2.5 -- Attib & Share Alike

 This is the 'universal' code designed for v1.2 - it will select EU or NA
 depending on a pulldown resistor on pin B1 !
 */

#include "main.h"

void xmitCodeElement(uint16_t ontime, uint16_t offtime, uint8_t PWM_code );
void flashslowLEDx( uint8_t num_blinks );
void quickflashLEDx( uint8_t x );
void tvbgone_sleep( void );
void delay_ten_us(uint16_t us);
void quickflashLED( void );
uint8_t read_bits(uint8_t count);

#define putstring_nl(s) Serial.println(s)
#define putstring(s) Serial.print(s)
#define putnum_ud(n) Serial.print(n, DEC)
#define putnum_uh(n) Serial.print(n, HEX)

/*
This project transmits a bunch of TV POWER codes, one right after the other,
 with a pause in between each.  (To have a visible indication that it is
 transmitting, it also pulses a visible LED once each time a POWER code is
 transmitted.)  That is all TV-B-Gone does.  The tricky part of TV-B-Gone
 was collecting all of the POWER codes, and getting rid of the duplicates and
 near-duplicates (because if there is a duplicate, then one POWER code will
 turn a TV off, and the duplicate will turn it on again (which we certainly
 do not want).  I have compiled the most popular codes with the
 duplicates eliminated, both for North America (which is the same as Asia, as
 far as POWER codes are concerned -- even though much of Asia USES PAL video)
 and for Europe (which works for Australia, New Zealand, the Middle East, and
 other parts of the world that use PAL video).

 Before creating a TV-B-Gone Kit, I originally started this project by hacking
 the MiniPOV kit.  This presents a limitation, based on the size of
 the Atmel ATtiny2313 internal flash memory, which is 2KB.  With 2KB we can only
 fit about 7 POWER codes into the firmware's database of POWER codes.  However,
 the more codes the better! Which is why we chose the ATtiny85 for the
 TV-B-Gone Kit.

 This version of the firmware has the most popular 100+ POWER codes for
 North America and 100+ POWER codes for Europe. You can select which region
 to use by soldering a 10K pulldown resistor.
 */

/*
This project is a good example of how to use the AVR chip timers.
 */

/*
The hardware for this project uses an Arduino:
 Connect an IR LED to pin 3.
 Connect a visible LED to pin 13 (or use builtin LED in some Arduinos).
 Connect a pushbutton between pin 1 and ground.
 Pin 0 is floating for North America, or wired to ground for Europe.
 */

extern PGM_P *NApowerCodes[] PROGMEM;
extern PGM_P *EUpowerCodes[] PROGMEM;
extern uint8_t num_NAcodes, num_EUcodes;

/* This function is the 'workhorse' of transmitting IR codes.
 Given the on and off times, it turns on the PWM output on and off
 to generate one 'pair' from a long code. Each code has ~50 pairs! */
void xmitCodeElement(uint16_t ontime, uint16_t offtime, uint8_t PWM_code )
{
  TCNT2 = 0;
  if(PWM_code) {
    pinMode(IRLED, OUTPUT);
    // Fast PWM, setting top limit, divide by 8
    // Output to pin 3
    TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(WGM22) | _BV(CS21);
  }
  else {
    // However some codes dont use PWM in which case we just turn the IR
    // LED on for the period of time.
    digitalWrite(IRLED, HIGH);
  }

  // Now we wait, allowing the PWM hardware to pulse out the carrier
  // frequency for the specified 'on' time
  delay_ten_us(ontime);

  // Now we have to turn it off so disable the PWM output
  TCCR2A = 0;
  TCCR2B = 0;
  // And make sure that the IR LED is off too (since the PWM may have
  // been stopped while the LED is on!)
  digitalWrite(IRLED, LOW);

  // Now we wait for the specified 'off' time
  delay_ten_us(offtime);
}

/* This is kind of a strange but very useful helper function
 Because we are using compression, we index to the timer table
 not with a full 8-bit byte (which is wasteful) but 2 or 3 bits.
 Once code_ptr is set up to point to the right part of memory,
 this function will let us read 'count' bits at a time which
 it does by reading a byte into 'bits_r' and then buffering it. */

uint8_t bitsleft_r = 0;
uint8_t bits_r=0;
PGM_P code_ptr;

// we cant read more than 8 bits at a time so dont try!
uint8_t read_bits(uint8_t count)
{
  uint8_t i;
  uint8_t tmp=0;

  // we need to read back count bytes
  for (i=0; i<count; i++) {
    // check if the 8-bit buffer we have has run out
    if (bitsleft_r == 0) {
      // in which case we read a new byte in
      bits_r = pgm_read_byte(code_ptr++);
      // and reset the buffer size (8 bites in a byte)
      bitsleft_r = 8;
    }
    // remove one bit
    bitsleft_r--;
    // and shift it off of the end of 'bits_r'
    tmp |= (((bits_r >> (bitsleft_r)) & 1) << (count-1-i));
  }
  // return the selected bits in the LSB part of tmp
  return tmp;
}

/*
The C compiler creates code that will transfer all constants into RAM when
 the microcontroller resets.  Since this firmware has a table (powerCodes)
 that is too large to transfer into RAM, the C compiler needs to be told to
 keep it in program memory space.  This is accomplished by the macro PROGMEM
 (this is used in the definition for powerCodes).  Since the C compiler assumes
 that constants are in RAM, rather than in program memory, when accessing
 powerCodes, we need to use the pgm_read_word() and pgm_read_byte macros, and
 we need to use powerCodes as an address.  This is done with PGM_P, defined
 below.
 For example, when we start a new powerCode, we first point to it with the
 following statement:
 PGM_P thecode_p = pgm_read_word(powerCodes+i);
 The next read from the powerCode is a byte that indicates the carrier
 frequency, read as follows:
 const uint8_t freq = pgm_read_byte(code_ptr++);
 After that is a byte that tells us how many 'onTime/offTime' pairs we have:
 const uint8_t numpairs = pgm_read_byte(code_ptr++);
 The next byte tells us the compression method. Since we are going to use a
 timing table to keep track of how to pulse the LED, and the tables are
 pretty short (usually only 4-8 entries), we can index into the table with only
 2 to 4 bits. Once we know the bit-packing-size we can decode the pairs
 const uint8_t bitcompression = pgm_read_byte(code_ptr++);
 Subsequent reads from the powerCode are n bits (same as the packing size)
 that index into another table in ROM that actually stores the on/off times
 const PGM_P time_ptr = (PGM_P)pgm_read_word(code_ptr);
 */

uint16_t ontime, offtime;
uint8_t i,j, Loop;
uint8_t region = US;     // by default our code is U

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

  TCCR2A = 0;
  TCCR2B = 0;

  digitalWrite(LED, LOW);
  digitalWrite(IRLED, LOW);
  pinMode(LED, OUTPUT);
  pinMode(IRLED, OUTPUT);
  pinMode(REGIONSWITCH, INPUT);
  pinMode(TRIGGER, INPUT);
  digitalWrite(REGIONSWITCH, HIGH); //Pull-up
  digitalWrite(TRIGGER, HIGH);

  delay_ten_us(5000);            // Let everything settle for a bit

  // determine region
  if (digitalRead(REGIONSWITCH)) {
    region = US; // US
    DEBUGP(putstring_nl("US"));
  }
  else {
    region = EU;
    DEBUGP(putstring_nl("EU"));
  }

  // Tell the user what region we're in  - 3 is US 4 is EU
  quickflashLEDx(3+region);

  // Indicate how big our database is
  DEBUGP(putstring("\n\rNA Codesize: ");
  putnum_ud(num_NAcodes);
  );
  DEBUGP(putstring("\n\rEU Codesize: ");
  putnum_ud(num_EUcodes);
  );
}

void sendAllCodes() {
  // We may have different number of codes in either database
  if (region == US) {
    j = num_NAcodes;
  }
  else {
    j = num_EUcodes;
  }

  // for every POWER code in our collection
  for (i=0 ; i < j; i++) {
    PGM_P data_ptr;

    // print out the code # we are about to transmit
    DEBUGP(putstring("\n\r\n\rCode #: ");
    putnum_ud(i));

    // point to next POWER code, from the right database
    if (region == US) {
      data_ptr = (PGM_P)pgm_read_word(NApowerCodes+i);
    }
    else {
      data_ptr = (PGM_P)pgm_read_word(EUpowerCodes+i);
    }

    // print out the address in ROM memory we're reading
    DEBUGP(putstring("\n\rAddr: ");
    putnum_uh((uint16_t)data_ptr));

    // Read the carrier frequency from the first byte of code structure
    const uint8_t freq = pgm_read_byte(data_ptr++);
    // set OCR for Timer1 to output this POWER code's carrier frequency
    OCR2A = freq;
    OCR2B = freq / 3; // 33% duty cycle

    // Print out the frequency of the carrier and the PWM settings
    DEBUGP(putstring("\n\rOCR1: ");
    putnum_ud(freq);
    );
    DEBUGP(uint16_t x = (freq+1) * 2;
    putstring("\n\rFreq: ");
    putnum_ud(F_CPU/x);
    );

    // Get the number of pairs, the second byte from the code struct
    const uint8_t numpairs = pgm_read_byte(data_ptr++);
    DEBUGP(putstring("\n\rOn/off pairs: ");
    putnum_ud(numpairs));

    // Get the number of bits we use to index into the timer table
    // This is the third byte of the structure
    const uint8_t bitcompression = pgm_read_byte(data_ptr++);
    DEBUGP(putstring("\n\rCompression: ");
    putnum_ud(bitcompression);
    putstring("\n\r"));

    // Get pointer (address in memory) to pulse-times table
    // The address is 16-bits (2 byte, 1 word)
    PGM_P time_ptr = (PGM_P)pgm_read_word(data_ptr);
    data_ptr+=2;
    code_ptr = (PGM_P)pgm_read_word(data_ptr);

    // Transmit all codeElements for this POWER code
    // (a codeElement is an onTime and an offTime)
    // transmitting onTime means pulsing the IR emitters at the carrier
    // frequency for the length of time specified in onTime
    // transmitting offTime means no output from the IR emitters for the
    // length of time specified in offTime

#if 0

    // print out all of the pulse pairs
    for (uint8_t k=0; k<numpairs; k++) {
      uint8_t ti;
      ti = (read_bits(bitcompression)) * 4;
      // read the onTime and offTime from the program memory
      ontime = pgm_read_word(time_ptr+ti);
      offtime = pgm_read_word(time_ptr+ti+2);
      DEBUGP(putstring("\n\rti = ");
      putnum_ud(ti>>2);
      putstring("\tPair = ");
      putnum_ud(ontime));
      DEBUGP(putstring("\t");
      putnum_ud(offtime));
    }
    continue;
#endif

    // For EACH pair in this code....
    cli();
    for (uint8_t k=0; k<numpairs; k++) {
      uint16_t ti;

      // Read the next 'n' bits as indicated by the compression variable
      // The multiply by 4 because there are 2 timing numbers per pair
      // and each timing number is one word long, so 4 bytes total!
      ti = (read_bits(bitcompression)) * 4;

      // read the onTime and offTime from the program memory
      ontime = pgm_read_word(time_ptr+ti);  // read word 1 - ontime
      offtime = pgm_read_word(time_ptr+ti+2);  // read word 2 - offtime
      // transmit this codeElement (ontime and offtime)
      xmitCodeElement(ontime, offtime, (freq!=0));
    }
    sei();

    //Flush remaining bits, so that next code starts
    //with a fresh set of 8 bits.
    bitsleft_r=0;

    // delay 250 milliseconds before transmitting next POWER code
    //delay_ten_us(25000);
    delay_ten_us(10000);

    // visible indication that a code has been output.
    quickflashLED();
  }
  while (Loop == 1);

  // flash the visible LED on PB0  4 times to indicate that we're done
  delay_ten_us(65500); // wait maxtime
  delay_ten_us(65500); // wait maxtime
  quickflashLEDx(4);

}

void loop() {
  if (digitalRead(TRIGGER) == 0) {
    sendAllCodes();
  }
}

/****************************** LED AND DELAY FUNCTIONS ********/

// This function delays the specified number of 10 microseconds
// it is 'hardcoded' and is calibrated by adjusting DELAY_CNT
// in main.h Unless you are changing the crystal from 8mhz, dont
// mess with this.
void delay_ten_us(uint16_t us) {
  uint8_t timer;
  while (us != 0) {
    // for 8MHz we want to delay 80 cycles per 10 microseconds
    // this code is tweaked to give about that amount.
    for (timer=0; timer <= DELAY_CNT; timer++) {
      NOP;
      NOP;
    }
    NOP;
    us--;
  }
}

// This function quickly pulses the visible LED (connected to PB0, pin 5)
// This will indicate to the user that a code is being transmitted
void quickflashLED( void ) {
  digitalWrite(LED, HIGH);
  delay_ten_us(30);       // 30 millisec delay
  digitalWrite(LED, LOW);
}

// This function just flashes the visible LED a couple times, used to
// tell the user what region is selected
void quickflashLEDx( uint8_t x ) {
  quickflashLED();
  while(--x) {
    delay_ten_us(DELAY);  // 150 millisec delay between flahes
    quickflashLED();
  }
}

When I try compile and upload to my Arduino Mega 2560, I get this error
In file included from main.h:9:0,
                 from TVB.pde:21:
TVB:78: error: variable 'NApowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
TVB:79: error: variable 'EUpowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
variable 'NApowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

Is there any way I can fix this?

"Is there any way I can fix this?" Yes.  You can change NApowerCodes and EUpowerCodes to be const like the error tells you.

As @Majenko suggested, add const. Recent versions of the compiler enforce this. When that code was written they did not.

Try:
extern  PGM_P * const NApowerCodes[] PROGMEM;
extern  PGM_P * const EUpowerCodes[] PROGMEM;

The definition of PGM_P is:
#define PGM_P const char *

which gives "const const" and gives "error: duplicate 'const'". But it is the variable that should be const.
Cheers!


text:
How to add .h file in library
I am trying to make an ultrasonic distance meter using Arduino. For this I added the ultrasonic library. But on compiling it shows this error "ultrasonic.h
not available". Please tell me how to add this .h file.

You can literally just create one. Usually they are config files so where you initialise variables etc.

Unless this is a module that you have installed from somewhere? In which case it should have one already. If not then try putting an empty one in and see what happens.

How did you add your library ? Have you follow these steps shown on the arduino site ?

In you Arduino Sketch folder there is a folder called Libraries, create a folder there and put your header file in that folder and restart the Arduino IDE.
For example (PC):
Documents/Arduino/Libraries/ultrasonic/ultrasonic.h

You can now use it in all your projects.
If you only want to use with a particular sketch, place in in the same folder as you  sketch and restart Arduino IDE.


text:
2 way communication between Arduino with XBee and Computer
I have an Arduino Uno with a Wireless SD Shield and XBee S1 and a PC with another XBee S1 connected to it. What I'm after is for me to be able to send a message from my computer and receive a message back from the Arduino (For now let's just say if the Arduino receives a "1" I want it to send an "A" back)
Here is the code I have been practicing with (courtesy of SparkFun)
#include <SoftwareSerial.h>
SoftwareSerial XBee(0, 1); // RX, TX

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

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

(I have changed the pins from 2,3 to 0,1 as the latter is on the Arduino itself)
I have set my Xbees up and have been able to get them to talk to each other when both connected to separate PC's, but I am having trouble getting the Arduino to send information to the other XBee. When I try and send data from the Arduino IDE both RX and TX Led's flash.
Could anyone steer me in the right direction?

I have changed the pins from 2,3 to 0,1 - change it back, no wonder it doesn't work. You can't have HardwareSerial and SoftwareSerial on the same two pins. It doesn't make any kind of sense.

You don't need to declare an extra (software) serial port because the wireless shield connects the Arduino TX and RX on pins 0 and 1 directly to the TX and RX of the Xbee. So, Serial.available, Serial.read and Serial.write directly addresses the xbee. Just leave out the software serial from your code and it should work.

Pin 0 and 1 are the Hardware Serial of Arduino you cannot use it as the software serial and I also used that code once use pin 2 and 3 its issue regarding the configuration of your XBEE? Check your XBEE configuration XCTU


text:
How to reset arduino Mega 2560 code automatically?
I am working on the temperature project using arduino to collect temperature. But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. I do not when it is going to hang up again. So I decide to do some research on the internet but no luck for that. Here is the article I read about resetting arduino code with watchdog timer library.(unfortunately, it only work for arduino uno) If someone has any idea how to reset arduino mega 2560 code. Please help !!

You can still use the watchdog without the library.

@IgnacioVazquez-Abrams  Do I need to wire anything to my arduino or other like what they called bootloader (I do not know what is that) ? The watchdog is a library, right ?  how to define it without the library ? I am guessing it is going to give me an error.

The watchdog is a MCU peripheral. You enable it by setting the registers appropriately. See the ATmega2560 datasheet, "System Control and Reset" section, "Watchdog Timer" and "Register Description" subsections.

avr-libc already has the appropriate functions created for you. Just include <avr/wdt.h>.
Sample usage
#include <avr/wdt.h>

void setup()
{
   wdt_enable(WDTO_8S);
   ...
}

void loop()
{
   wdt_reset();// make sure this gets called at least once every 8 seconds!
   ...
}

how to know the aruduino is resetting. I have it run for 10 mins. no sign see the display is resetting .

You can detect resets using the MCUSR register. But it's probably easier to add a Serial.print('startup') to the setup function and keep the serial console open. If 'startup' appears more than once a reset has occurred. Alternatively add a buzzer that beeps on startup(/reset).

I add Serial.print('startup')  at the setup. It did not reset the program .

@Yang: It won't reset unless the code fails to reset the watchdog.

I tried Gerben's suggestion with a display:
#include <avr/wdt.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println (F("Code starting ..."));
  wdt_enable(WDTO_8S);
  }  // end of setup

void loop()
{
//   wdt_reset();// make sure this gets called at least once every 8 seconds!
}

That does indeed print "Code starting ..." every 8 seconds or so.

But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino.

You are better off working out why. There is probably a bug. Fix the bug rather than just restarting the Arduino.

let me tried to run the code for several weeks to see if there temperature go off. By the way, i think the code has no problem but maybe somehow the temperature hit "0" or even crazier "99999", I still cannot figure that out is the hardware problem or something else. So that is why I tried to reset my code automatically.

You could also use an external circuit to reset the arduino when 'heartbeat' pulses are missed. You can even detect when a reset has occured and report accordingly. See here for an example

What is the advantage of this circuit over the build-in watchdog timer?

You can know when it's happened and record the event which is difficult if not impossible to do using the internal watchdog

You can check the MCUSR register (The MCU Status Register provides information on which reset source caused an MCU reset.).

Yes (and I'm admittedly getting out of my depth here) doesn't the boot loader also use the internal watchdog so you wouldn't know if it was caused by the reset switch/power on or a watchdog event