text:
Removing Element From Array While Keeping Order
I'm building a wireless mechanical keyboard. There is an array of 6 elements that stores the keys pressed by the user (since 6 is the max number of keys you can send at once over Bluetooth). An example would be 02-05-03-00-00-00. Notice the "00" at the end, these are just "placeholders" and don't have a meaning other than to indicate that there are no more keys pressed. When the user releases key 05 for example, the array should become this 02-03-00-00-00-00. I don't know how to do this however, since you can't just remove and item from an array and there doesn't seem to be a polished option for lists in Arduino.
Does anyone have any idea for an algorithm that finds the 0's in an array, places them at the end of the array and keeps the order of the other elements?

You need to compact the vector: First search for the first non-zero element and then move all non-zero elements. It could look something like below:
void setup()
{
  Serial.begin(57600);
  while (!Serial);

  char vec[] = { 2, 5, 3, 0, 0, 1 };
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));

  vec[1] = 0;
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));
}

void loop()
{
}

void compact(char* vec, size_t len)
{
  int i = 0;
  for (; i < len && vec[i] != 0; i++);
  if (i == len) return;
  int j = i;
  for (; i < len; i++) {
    char c = vec[i];
    if (c != 0) {
      vec[j++] = c;
      vec[i] = 0;
    }
  }
}

void print(char* vec, size_t len)
{
  for (int i = 0; i < len; i++) {
    unsigned c = vec[i];
    if (c < 16) Serial.print(0);
    Serial.print(c, HEX);
    if (i + 1 < len) Serial.print('-');
  }
  Serial.println();
}

This give the following output:
02-05-03-00-00-01
02-05-03-01-00-00
02-00-03-01-00-00
02-03-01-00-00-00

Cheers!

Remove Zeros
void removeZeros(uint8_t array[], size_t length) {
// Sanity check.
if(array != nullptr && length > 0) {
    for(size_t i = 0; i < length; i++) {
      if(array[i] == 0) {
        for(size_t j = i + 1; j < length; j++){
          if(array[j] != 0) {
            array[i] = array[j];
            array[j] = 0;
            break;
          }
        }
      }
    }
  }
}

Usage:
uint8_t keyBuffer[] = { 2, 0, 3, 0, 4, 0 };
removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0]);

New value of keyBuffer: { 2, 3, 4, 0, 0, 0 }

Remove a single indexed value
void removeIndex(uint8_t array[], size_t length, size_t index){
  // Sanity check.
  if(array != nullptr && length > 0) {
    for(size_t i = index; i < (length - 1); i++){
      array[i] = array[i + 1];
    }
    array[length-1] = 0;
  }
}

Usage:
uint8_t keyBuffer[] = { 2, 5, 3, 0, 0, 0 };
removeZeros(keyBuffer, sizeof(keyBuffer)/sizeof(keyBuffer[0], 1);

New value of keyBuffer: { 2, 3, 0, 0, 0, 0 }


text:
Clock drift - is the precision of the crystal the only culprit?
I've a wall clock (sorry, code's a mess, look for updateClockVars) which makes use of the Timezone library (and ultimately Time). Nothing fancy, call millis() every loop; turn to Hrs, Mins, Secs; display on LEDs.
The magnitude of the drift I am seeing on my 2 Arduino Pro Mini - compatible boards - up to ~8% lag, not a typo - blows my mind. Replacing the 16MHz quartz with one bought at a local retailer didn't help much (~33% improvement). Is something else at play here?

Can you please extract from the code only the part regarding time? There are 300 lines and it's difficult to understand everything.

Didn't check the whole code, but here is an idea: Since your LED strip is quite long, the NeoPixel library may be blocking interrupts for too long when you strip.show();. You may then be missing timer interrupts. Try with a much shorter strip and see if the problem persists.

Much better idea would be using a RTC module (the easiest way to be honest).

I get 40-60 loop iterations per second. I don't keep track of time on my own, I ask for millis(). RTC: even having read so many suggestions for it, I still didn't catch WHY that is better - it's a quartz either way, and if that's not the only relevant thing - than we have an answer to the original question. @frax93: updateClockVars(). All else is just setting the LEDs based on the acquired values.

I have read some things here that I didn't understand but may be relevant (or not even true). Author claims PWM can keep more acurate time that timers and main clock (!?), and having read that "Using the millis() creates issues using some functions such as delay()".

I would encourage you to have a look at the code behind millis(), micros() and the Timer Overflow ISR. Please notice the accumulated error and the leap milli-seconds. It is possible to adjust the Timer handling and get within better accuracy. Please see Cosa Clock and Calibration Tools. Start here: https://github.com/mikaelpatel/Cosa/blob/master/examples/Tools/CosaClockCalibration/CosaClockCalibration.ino.

@EdgarBonet Still trying to wrap my head around the PPM value. I deleted my comment, as was wrong.

The problem is the interaction between the interrupt handler that updates the value for the millis() function and the neopixels show() function.
To maintain the counter for the millis() function a interrupt is triggered approximately every 1.024 ms.
When the show() function is called all interrupts are disabled to get the precise timing needed to send the data to the neopixels.  For a 60 led strip this takes about 1800 microseconds (60 leds * 24 bits * 1.25 us per bit) so at least one interrupt is skipped each time you update the display.
This page has details about how the millis() function works.

“at least one interrupt is skipped each time you update the display”. This is incorrect. See my answer.

TL;DR You're doing it wrong. Use RTC.
Ok, longer explaination is required here. millis() is not accurate and here is why.
First, grab official Arduino source code from their Github repo.
The file Arduino-master/hardware/arduino/avr/cores/arduino/Arduino.h
contains few interesting macros (I'm pasting grep output here):
Arduino.h:#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
Arduino.h:#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
Arduino.h:#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )

At 16MHz clockCyclesPerMicrosecond() will evaluate to 16. Keep this number in memory.
Those macros are used in Arduino-master/hardware/arduino/avr/cores/arduino/wiring.c:
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

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

MICROSECONDS_PER_TIMER0_OVERFLOW macro is evaluated as (64 * 256)/16 -  a dodgy looking 1024. Look how they round it down to calcuate MILLIS_INC.
Let's assume that you run your Arduino with ideal main clock signal.
At 16MHz main clock, the timer frequency is 1.024kHz, not 1kHz. This results in 2.4% inaccuracy. You can get away with that in most cases, but not when you're building a clock.
This 2.4% error is best case. Your main oscillator is not 16MHz - it has it's own inaccuracy, that is unknown and it sums up.
You should use an external, accurate time reference provided by RTC module. When assembled properly, they guarante low time drift, temperature compensation and other goodies. Be smart - use RTC. :)
If you are scared of I2C RTC modules, you may find my tutorial
and another tutorial on MCP7940N RTC module. Know-how is applicable with other RTCs as well.

Thank you. I had assembled a DS1307 module, but only used it for sync on startup, as in the timeRTC example. Ditched it in favor of NTP via an ESP8266 (so the Arduino is I2C slave now).

I hope you aren't calling an NTP node every second. You might get IP blocked if you keep doing that. They are supposed to synchronize your clocks, not replace them.

−1 because you visibly do not know what you are talking about. The timer frequency is 1/1.024 kHz, not 1.024 kHz. (the period is 1024 µs). Most importantly, this does not imply millis() is inaccurate: the extra 24 µs are accounted for: see timer0_fract and FRACT_INC.

Expanding on my previous comment...
As I said before, I suspect the NeoPixel library to be blocking
interrupts for too long when you strip.show(). If a timer interrupt
fires while interrupts are blocked... it's not a big deal: the interrupt
request is put on hold and serviced as soon as interrupts are enabled
again. If two timer interrupts fire while interrupts are blocked...
you have a problem: the interrupt service routine will be called only
once, and your clock will miss a tick.
Craig has worked out the timings in his answer: the timer interrupt
fires every 1.024 ms, and NeoPixel blocks interrupts for
1.8 ms. So it is perfectly expected that, from time to time, you
will have two timer interrupts within this 1.8 ms window.
Here is a quick hack that could solve your problem: if you
strip.show() right after a timer interrupt is serviced, then only
one more interrupt should fire during the subsequent 1.8 ms window,
and you should be fine. So you could simply add this right before
strip.show():
/* Wait for a timer interrupt to be serviced. */
uint32_t lastMillis = millis();
while (millis() == lastMillis) /* wait */;

A possibly better solution would be to avoid blocking interrupts for so
long. NeoPixel blocks them in order to comply with the very tight timing
requirements of the WS2812 LEDs. But it turns out the WS2812s are not
nearly as picky about timings as their datasheet suggests. You can drive
them in a more relaxed way, with interrupts enabled except for 1-bit
durations, and they still work fine. For a detailed explanation and
sample code, see NeoPixels Revealed: How to (not need to) generate
precisely timed
signals.
A third solution would be to follow the general advice given here and
grab an RTC. However, although it certainly is a good and clean
solution, I have to admit I completely agree with your comment “I still
didn't catch WHY that is better – it's a quartz either way”.

Alternatively, you could use a second timer that ticks slower, and implement your own version of millis. This function could also implement some kind of calibration. By measuring how much the clock is of after a longer period, you can see if the 16mHz clock is too fast or too slow, and by how much. You could use this value in your millis implementation to get better accuracy.

source: Stack Exchange

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

sort: votes


text:
Adafruit DHT22 Library + Arduino Due not compiling?
i recently purchased a DHT22's and tried to get it to work using Adafruit's DHT library on Github.
When i compile it with a Arduino DUE, it gives me the following error:
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp: In constructor 'DHT::DHT(uint8_t, uint8_t, uint8_t)':
C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp:14:9: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]
   _port = digitalPinToPort(pin);
         ^
Error compiling.

It compiles on a Arduino Uno but not on the DUE.
What is the reason for this?
Edit: Below is the example code i use
#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

#define DHTTYPE DHT22   // DHT 22  (AM2302)

DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");
  dht.begin();
}

void loop() {

  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");
}

That library uses direct pin manipulation to make things faster.  However the Due is a completely different architecture to the Uno, so direct pin manipulation is done differently.
The library would have to be written specifically to do it in the two different ways and select between them depending on which board is chosen for the compilation.  This hasn't been done, and it's unlikely it would ever be done.
This is exactly why digitalWrite(), shiftIn(), shiftOut() et al exists, so that you don't get these kind of problems.  By choosing not to use them Adafruit have basically decided that their library will never work on a Due.

Thank you for your quick answer. I am aware that the port names on the DUE are completely different to the UNO.This might be a stupid question but, would it be enough for me to change the port name in the library manually to the DUE's port name?

@Darellon The whole way the ports work on the Due is completely different.  You would need to write completely different code to do the port manipulation.

I suggest you post on the Adafruit forum, asking for an update to their library, or suggestions about how to fix it to work on the Due.

There are several Arduino libraries for reading DHT22 and related DHT sensors.  The Adafruit DHT library does not compile for the Due since it uses AVR specific functions not available on ARM (Due).
For the Arduino Due use Rob Tillaart's DHTstable library available from his github page where you can download a zip file.  Note that his project also has a "DHTlib" library which does not support the Due.  There exists yet more DHT libraries which Rob has listed on the DHTLib page on arduino.cc.

The same library works with the Due if you use the older version 1.1.13 from the same Github repo, which is the last version that officially supported the Due.
Here are the changelog entries that show the relevant changes:

update: 0.1.13 added support for DHT33 and DHT44 - LAST DUE VERSION
update: 0.1.14 replaced digitalRead with faster code (AVR ONLY!!! better support for lower Mhz devices)

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


text:
What is the circular gold pad on arduino mega 2560 v2 and above?
Could someone point me to the documentation that describes the gold dot and surrounding gold circle on the front of my arduino mega v2 board. It is right above the ICSP header and reset button, and directly underneath the letter 'U' in the silk screened word 'communication'
I've not been able to find any reference to it anywhere. Is is a jumper, a test pad, RF pad???

That is most likely a Fiducial Mark for the vision system of a pick-and-place assembly robot to key off of in order to more precisely place the components on their pads.
If you look carefully, you will see a second one located below the DC barrel jack.
Boards like this are manufactured in a gridded panel having a number of copies in each direction, and only cut apart after they are largely complete.  With such a large workpiece, any linearity error in the manufacturing could result in a high-density component being misplaced far enough to cause problems.  Having a pair of fiducials on each individual board in the panel can help calibrate out errors not only which might otherwise accumulate over the large dimensions of the entire panel, but also rotational skew of the panel in its holder.

You can see both on this picture of the Arduino Mega 2560 from the arduino.cc site

To add to Chris's answer: fiducials appear at three levels. First there are fiducials at the panel level, which contains one or more PCBs, depending on their size. Next there are fiducials for the PCB, acting as a position reference for component placement. Sometimes you can see component fiducials close to some fine pitch components, to make sure they are placed with high precision. You'll sometimes see these latter fiducials on opposite corners of QFP (Quad Flat Package) parts. (The AVR controller on the Arduino Mega 2560 is in QFP.)


text:
Connecting a USB 3.0 Flash Drive
Is it possible to connect the nine pins from a USB 3.0 memory drive to the corresponding GPIO pins of the arduino (intel Galileo is what I am using, but it is very similar) and access the drive's memory through the implementation of the USB's protocol? I have searched around and have not been able to get a clear idea on how to do this or if it is even possible.

An arduino has no USB host function for as far as I know

@Handoko The Galileo and Due both do.

@Annonomus Ok, that's new for me. But I'm only familiar with the Arduino Uno, Leonardo and Mega.

If you want to economically hang a large storage device off an Arduino-type board, use an SD or uSD card, which can be bit-banged in software off of arbitrary GPIO pins if no specific controller is available.  You can then insert that card into a USB reader if a different system needs to pre-load or analyze the data on it.

Since this is going to be a long post, I'll post the summary above the fold to save some of you the effort of scrolling...
tl;dr: No, it's not possible to do so with GPIO pins. There is another way to do this, but IDK if the rest of the Galileo will be a bottleneck (and it's pretty pricey). The stereotypical AVR Arduino is simply too underpowered (both from a MCU and amperage standpoint) to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

Basic corrections/things to note (before I begin):

Note: I'm no expert on the Galileo, I'm just doing this all from what I remember from what I've read in the past. If you spot an error, feel free to post a comment with a little explanation and I'll fix my post. However, I doubt that there will be any major errors, and the overall content (i.e. the tl;dr) should be fine.
These figures are maximum that I'm posting:

Speed: if speed is near maximums, or even 10%, what's the point of 3.0?
Power: you never know with this one, so account for it being near limits, unless externally powered. Still, don't risk it.

If it's a USB thumb drive, you're going to either get a breakout board for 3.0 and/or break open your device and solder wires onto it. Note that there doesn't seem to be a USB 3.0 breakout board (from a very quick search on Google). I'm also concerned that the wires you would use might not be high enough grade for extreme data transmission.
Only 7 of the 9 lines are used for data. The other two are 5V and GND.
On a Galileo, you'll have to use the 5V selection for the IO pins.
On a Galileo, there's a Mini-PCIe port (although I can't seem to find it in the photos myself). You could add a Mini PCIe to USB 3.0 card. However, that will cost you almost $50 to do so, and by that time it might be better just to seek out another solution.
Photo of it:

Ask yourself do I really need the speed?

No: don't waste the money and the headache.
Yes: consider either another platform or buying this product.

Keep in mind that, although it fits, it probably won't be able to get enough power for true USB 3.0 that your disk needs and drivers will be rare. You for sure will want to research this more before shelling out the cash to buy this card.

Galileo doesn't run a full OS, so I'm highly doubtful that there's drivers.

Like I mentioned before, I'm not quite sure about the Galileo supplying enough power... again you need to check into this and maybe add an external voltage regulator (if all the other issues are resolved). USB 3.0 can provide up to 2x the power per port of 2.0, so when I say almost an amp, it's technically almost two amps (although I think at this point you'll just have to remember not to use the second port and call it one amp).

Technical problems:
I stated this before in the post:

The stereotypical AVR Arduino is simply too underpowered to host USB 3.0. You need a shield to host USB 2.0, and even with that, I doubt that you can use 2.0 at it's full potential.

The Galileo has native 2.0 support, so I'd recommend just getting a fast USB drive and using that.
Anyway, think about it: the Galileo can handle roughly 400,000 instructions per second. USB 3.0 can send up to 5,000,000 bits in the same amount of time! Like mentioned before, it is the maximums, but still. AFAIK on the AVR boards it it takes multiple instructions to read one GPIO pin (for some reason I want to say 3, but that seems too low). I'd imagine that it'd be the same situation on the Galileo. I'm not quite sure about the instructions it takes to read a pin, correct me if I'm wrong anyone. Anyway, assume it takes four instructions per pin, and your device only sends 1 Gbps. That's still 1,000,000 times that a pin needs to be read when you can only read 100,000 in that time. Even so, you can't even use the data, nor can you implement a loop or other code that combines bytes to read the data in the first place! Plus, you wouldn't have enough RAM!
I'm not a USB expert, but IIRC it only asks the device for data as needed, but still, that'd be pointless to create your code for this and spend the extra money for 3.0 cables and devices. This paragraph is all from memory, I don't really know; don't cite this paragraph.
Also, you'd have to implement your own code for sending data to/from the device. No such code exists without hardware for 2.0, let alone 3.0.

Conclusion:
It's near impossible to do so, and you'd need a lot of extra parts and have to read up on the USB 3.0 specs. I think it would take a great engineer 50+ years to accomplish this without developing an IC (which would cost money). Do you really need the speed? If not, you can buy USB 2.0 host shields and communicate via SPI. That isn't very fast, but still, it's possible.

Sources:
Info and photos are scattered on the following sources:

http://en.wikipedia.org/wiki/USB
http://arduino.cc/en/ArduinoCertified/IntelGalileo
http://www.amazon.com/StarTech-com-Express-SuperSpeed-Adapter-MPEXUSB3S2/dp/B004NO0LK8

Thank you for the explanation; this project wasn't about getting the maximum speed out of the USB 3.0 but more of a learning experience to see if I could do it. I was planning on pulling the 9 pins from USB drive into GPIOs. But you said this was impossible because of current and voltage. So my question now is would it be possible to do with an external power source? I wanted to write the low level driver code myself as well, now is this also impossible? If not USB3.0, is USB2.0 feasible?

@Akash Although an external power supply would solve some problems, it simply isn't feasible to do direct USB connections. A separate chip is ideal for this, and you can purchase them online. Even so, you'd still have to find the appropriate datasheets and code things like the handshake. This alone would be a huge undertaking, and you'd still need more code to even inference with the USB drive. You can buy 2.0 host shields fairly cheap, but that's really your only option.


text:
Button to optocoupler to fire camera 4 times
Ok, this is my first project where I've not had @forsvunnet close by to help.
I've got a camera connected to an optocoupler, that just fires HIGH then LOW.
I can't get a button working with it, so when I push a button, it fires opto 3 times.
This is my sketch.
 // Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, LOW);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
  } else {

  }

}

Anyone point me in the right direction? It's driving me mad.

What camera are you using? What hardware? Can you provide more information by editing your question? Thanks!

Why do you use digitalWrite() on an input pin (buttonInput) in setup()? Should it be opto instead? Also, do you use a pullup (or pulldown) resistor to force a level on buttonInput when the button is not pushed?

First of all, the loop (if it worked well) would only fire twice. It should only fire when you turn it on/off in a cycle (unless it's a rising/falling edge circuit (i.e. a pull down button/a falling edge interrupt), but I won't get into that). In your code you toggle it twice. The third one? I suspect that your camera only fires when it's given a low signal. This means that, when you set it to low in setup(), it takes a photo. To fix this, switch all the HIGHs and the LOWs for the opto pin.
This is the code which I think should work for you:
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int opto = 12;
int buttonInput = 2;     // the number of the pushbutton pin
int buttonState = 0;         // variable for reading the pushbutton status

// the setup routine runs once when you press reset:
void setup()
{
// initialize the digital pin as an output.m
pinMode(opto, OUTPUT);
pinMode(buttonInput, INPUT);
digitalWrite(buttonInput, HIGH);}

// the loop routine runs over and over again forever:
void loop()
{
  buttonState = digitalRead(buttonInput);
  if (buttonState == HIGH) {
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
      delay(1000);               // wait for a second
      digitalWrite(opto, LOW);
      delay(1000);               // wait for a second
      digitalWrite(opto, HIGH);
  } else {

  }

}

Without much info about your camera, I'd imagine that the HIGH/LOW discrepancy is the issue. Another note: this code doesn't protect against bouncing. It's fine if as it is because the delays will cause the bounces to not be picked up. If you do a "blink without delay" type of sketch using millis() and a loop, you might need to fix this. Like I said, it'll work fine now, but it's kind a crude fix since it could cause problems later if mixed with other code.

Thanks for getting back to me. I think you're right with the LOW being the trigger here, it's a CANON 350D (Pretty old, it's all I had around that I could rag about) But it works like most canons, using a 2.5mm jack + 3 wires. GND, Focus and Trigger.

Would there be benefits for using blink without delay? My original intentions where to have it play the loop once when you push a button. Which made me wonder if it would be worth setting a separate void() with my camera behaviour in to clean the code. but might just be arbitrary

@Andrew Did you test the camera yet? From the wires you posted, it only makes sense to have it be pulled down to ground. If so, did it work right? As far as the blink without delay, I personally wouldn't implement it if you don't change any features. The only reason I could see implementing it is to have a "cancel" button. If you want the experience, go ahead, just remember to debounce the button. EDIT: I found a problem with your code that I didn't notice. I'm editing my answer right now.


text:
Horse racing game
Basically i would like to create a horse racing game, (5 horses starting all to a point A and finishing in a random position to a point B).
I did an animated GIF for you to understand it more clearly :
https://i.sstatic.net/oOZvB.jpg
This exactly what i want to do, but in real.
I was thinking of using 5 motors (one for each horse) with a string they pull where the horse is attached on it (like this : https://www.youtube.com/watch?v=NjuoCS9-pCY), and to create randomness at each race, do a random speed for each motors every 1 or two seconds and then stop when each horse hit the finishing line (by pushing a sensor ?). Finally when all horses hit the finishing line, the motors goes backward and get the horses back to the start line.
The horses will be tiny like 1 inch (2.5cm) and the distance from start to finish line will be like 20inch (50cm) and i need the race to last at least 5-10 sec so motors don't need to turn too fast.
I don't know if it is the best way or if it is even possible (and how ? with what components?)
I have been searching for solutions to my project but didn't found anything suitable yet so here i am..
Thank you a lot for you help

What is your question exactly? You want a solution to your project (would that be "assignment") - is that it?

I'd use some simple stepper motors for that. Using those, you will always know where all the horses are precisely, have precise control of speed, and negating the use of buttons at the finish.

Thanks @Gerben this is a start :) and yes nick i'm looking for help to know what component to use


text:
Mouse.move values
I understand that Mouse.move move the mouse from its current position, example:
Mouse.move(100, 100);
Will move the mouse to 100 pixels right and 100 pixels down.
But in reality it will move to somehting like 150 pixels right and/or 150 pixels down..
I already tested without cursor precision/acceleration and it doesn't change a thing.
What unit does the function use ?
I know about the 127 -127 limit, and i respect it, but still... when i ask to move 100,100 it doesn't move 100,100.

The mouse coordinates are not pixels. They are a proportion of the physical minimum/maximum parameters of the report descriptor. Since those aren't specified in the report descriptor they are taken to be the same as the logical: -127 to 127.
So moving 100 "units" is moving 100/(127-(-127)) of 100%, which is about 40%.
But 40% of what?
Well, 40% of an inch. Or what your OS believes that an inch is on your current screen.
In the HID specification:

While Logical Minimum and Logical Maximum (extents) bound the values
  returned by a device, Physical Minimum and Physical Maximum give
  meaning to those bounds by allowing the report value to be offset and scaled.
  For example, a thermometer might have logical extents of 0 and 999 but
  physical extents of 32 and 212 degrees.The resolution can be determined
  with the following algorithm:
if ((Physical Maximum == UNDEFINED) || (Physical Minimum == UNDEFINED) || ((Physical Maximum == 0) && (Physical Minimum == 0))) {
    Physical Maximum = Logical Maximum;
    Physical Minimum = Logical Minimum;
}

If (Unit Exponent == UNDEFINED)
    Unit Exponent = 0;

Resolution = (Logical Maximum – Logical Minimum) / ((Physical Maximum – Physical Minimum) * (10^Unit Exponent))

it makes sense, thanks!

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


text:
Having problems with HC-05 and three relays
I'm trying to control three relays with the Arduino Uno rev3 and a HC-05 bluetooth module from Elecfreaks.
I've wrote this code:
// the comments are the part of the code that I use to replace the Serial by default to be able to use the HC-05 module
//#include <SoftwareSerial.h>
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay1estatus = 0;
int relay2estatus = 0;
int relay3estatus = 0;
char command;
//SoftwareSerial bluetooth(5,6);

void setup() {
 Serial.begin(9600); //bluetooth.begin(9600);
 pinMode(relay1, OUTPUT);
 pinMode(relay2, OUTPUT);
 pinMode(relay3, OUTPUT);
 digitalWrite(relay1, LOW);
 digitalWrite(relay2, LOW);
 digitalWrite(relay3, LOW);
}

void loop() {
 while(Serial.available() > 0){ //bluetooth.available()
  command = (byte)Serial.read(); //(byte)bluetooth.read();
  Serial.println(command); //bluetooth.println(command)

  if (command == 'a'){
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   }else{
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }
  }

 if (command == 'b'){
  if (relay2estatus == 0){
   digitalWrite(relay2, HIGH);
   relay2estatus = 1;
  }else{
   digitalWrite(relay2, LOW);
   relay2estatus = 0;
  }
 }

 if (command == 'c'){
  if (relay3estatus == 0){
   digitalWrite(relay3, HIGH);
   relay3estatus = 1;
  }else{
   digitalWrite(relay3, LOW);
   relay3estatus = 0;
   }
  }
 }
}

The problem is that this code works perfectly using the Arduino IDE serial monitor, but when I try it using instead of the default serial methods, the SoftwareSerial ones it doesn't work.
Doesn't work in a very strange way because I can switch one by one the relays between on or off but, when I have two of them activated seems like freezes, I can't switch the third one on or off and neither I can switch the other two again.
To send the 'commands' through bluetooth I use the Bluetooth Terminal app available in the PlayStore.
(I've just posted the same question in stackoverflow but now I think here's the best place to ask it)

I don't see a problem with the code indicated for bluetooth; if that code is indeed ok, then probably you should look for hardware issues;  first, look for low +5V when multiple relays are turned on.  (Attach a voltmeter or a scope to +5, see if it changes when a second relay comes on, etc.)  Second, look (with a storage scope) for glitches when the relays switch.  If you don't have a storage scope, try testing with a separate power supply for the relays.  (Tie the grounds of things together, but give the Arduino and the HC-05 +V that's isolated from relay +V.)
More seriously, your code is overweight.  For example, replace
   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   } else {
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }

with
    relay1estatus = 1 - relay1estatus;
    digitalWrite(relay1, relay1estatus);

Thanks a lot! This issue have been driving me mad for some days because I was sure it wasn't a software problem.. also I had the module connected at 3V and that cause some problems with the power as I saw, so I've connected the relays and the bluetooth in  parallel to 5V and I've also added two capacitors just in case.


text:
read AM signal only with an Arduino
Some people have managed to send simple AM signals with just a bare Arduino. An example is here.
This works thanks to the fact that the PWM can reach high frequencies and, setting the divider properly, it is possible to broadcast a 1337 kHz carrier over a short distance with just a wire acting as an antenna.
I know it's not that useful, but it's really nice as an educational tool.
I was wondering if it would be possible to apply the same concept, but for the receiver. For instance simply using a pulseIn() detection on a pin connected to an antenna. Would it be possible to detect the carrier, and, maybe, even demodulate a message, eg, in morse code?
If not, would just a adding an amplifier be sufficient? Any recommendations for the amplfier and the circuit?
Thanks very much for your suggestions.

Generating an AM signal is child's play compared to detecting one.
To generate a signal you just need to create an oscillation and vary the amplitude, which can very crudely be done with PWM.
That's simple.
To receive a signal you first need to isolate that signal. There's a huge number of signals and noise around all the time, and you need to tune in to the signal that you are interested in. That's what you are doing when you twiddle the dial on a radio. You're selecting which frequency to listen to.
And to do that requires a tuned circuit - a kind of band-pass filter which isolates and amplifies the frequency you are interested in.
Imagine you are in a large hall filled with people. Every single person there is just standing around talking out loud - everyone is saying something different. Some are even just screaming, or whimpering in the corner. It's just a cacophony of noise. Impossible to know what is going on. That's what the air waves are like. You need some way of "tuning in" to one person's voice so you can understand what they are saying. As humans we often do that using sight, to watch a person's lips and our clever brains link the movement to the sound and help us pick out their voice. Coupled with our ability to select on the tonal qualities of a voice as well, we can pick out a single voice in the noise. That's what the tuned circuit does. It picks out one voice from the mayhem.
The Arduino can't do that. It would need to use some fairly sophisticated filtering algorithms, and it just doesn't have the power for that. Firstly you'd need to sample  the raw RF noise at a minimum of twice the frequency you are interested in (so multi-mega-samples per second), and then you'd need to do digital filtering to isolate that one frequency. From then you'd need to do more filtering to demodulate the original signal from the modulated signal.
It's all possible to do in software, but not with an Arduino. It takes a good ADC and a DSP to do all the hard work.
Easier to just build a small tuned circuit from a few passive components.

thanks. Would it be possible to use Arduino PWM as oscillator for tuning the circuit? That would save some components maybe.

No. Maybe for FM as a reference clock for a PLL, but not AM. A tuned circuit is very very simple. About 3 components. All passive.

do you have an example circuit? it would be good for my educational purpose!

Ask Google. I am away from my desk at the moment.

AM (Amplitude Modulation) varies the amplitude of the carrier based on the input signal. So, assuming you had some circuitry (LC circuit) to receive a particular carrier frequency and managed to boost the voltage so that it was in the range 0-5v then you would able to feed this to an analog input on the Arduino.
AnalogRead requires around 100uS per sample, so your max sampling rate would be 10K/s, which might just cut it for voice (up to 3.4Khz, sampling at least 2 * the highest freq).
However, you then need to do something with the sample value (in code) and depending on how long that 'something' takes, your actual sample rate will be reduced.

thanks for this explanation, my question was really related to if I could avoid the LC circuitry and just read the antenna directly (maybe with some amplification first)

Not possible. You'd be able to read the carrier frequency sure (depending on actual freq.) but the frequency never varies, it's the amplitude of the frequency that contains the coded signal.


text:
Gradual change of PWM motor control
Can someone please tell me what I'm doing wrong?
The motor's not turning at all, never mind changing speed.

Please post your code (copy and paste) - not a screenshot of it. That we we can try it ourselves, or copy an offending line. Format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

It looks like you are attempting to perform hardware PWM on an Analog Input Pin.
Assuming that you are using an Arduino Uno, try changing your first line of code to use one of the digital output pins which support PWM. You can use any of pins 3, 5, 6, 9, 10, or 11. Then connect that pin to your motor. (Note that you will likely have to use a transistor or driver circuit between the pin and the motor since the motor may well require more current to operate than the Arduino output can directly supply.)
If you are using a different Arduino other than the Uno, look at the documentation to find one of the PWM pins and try using that.

It's a pretty small motor that I took from an old printer. It runs off of the 5v and the 3.3v pins and from the analog pin when I analogWrite 255 or a bit lower. Admittedly it won't run at low analogWrites like 50. It's a clone Arduino Mega.

@GarionBracken: If you try to analogWrite() to a pin that is not PWM-capable, you will get either 0 (if writing less than 128) or 5 V (if writing something ≥ 128). What you wrote is essentially equivalent to digitalWrite(motorPower, motorVoltage >= 128 ? HIGH : LOW);

You should copy and paste the text of the code into your question, not a screenshot of it. Then we can copy and paste the problem lines into the answer.
You are varying up and down the variable motorVoltage in two loops. However you are not then doing an analogWrite with the new value. It should be more like this:
while (motorVoltage <= 255)
  {
  analogWrite (motorPower, motorVoltage);
  motorVoltage++;
  delay (200);
  }

A0 is an analog input. You can't output from it. You can only output on analog input pins by using defining them as 14,15,16...
For the best result, try changing the motor pin to something like pins 9, 10 or 11. They are my favorite PWM pins.

Guys I've moved the pin to one of the PWM pins and it's still not giving me any gradual changes. Also weirdly I'm able to manually set the analogWrite for my analog in pins and get lower output voltages. Noone seeing anything wrong with my code?

Yes, you are not doing the analogWrite inside any of your loops. All you are doing is changing a variable.


text:
Append to .h file through arduino code
I'm at the stage where I can #include headerFiles.h into my arduino sketches.
I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?
It'd make the arduino a lot more portable and would negate having to buy an SD card module.
How would the data be extracted? EEPROM is too small for datalogging past what you'd rack up in text over a reading every minute for a few hours.
Any clever clogs got ideas for this?

Header files only exist on your development machine, not on the Arduino, so can only be modified with the involvement of the former, and the changes only take effect when you rebuild and reflash the sketch.

There are external serial EEPROM/flash memory chips which may be easier to deal with than an SD card (from the Arduino side); search for "spi flash". And then there's also OpenLog.

How much memory do you need? Kilobytes? Megabytes? Gigabytes?

Header files are used to "encapsulate" functionality of your code. When you #include a header file, what you are actually doing is, as perhaps an oversimplification, "pasting" the code from that header file into your sketch above where the main code you've written in that file resides. You can then call on functions defined in the header file. Usually, at this level, you are using header files to include useful code that other programmers have contributed to a "library" that has some functionality that makes your life easier -- UART or Wire for communication, or perhaps being able to write to one of Adafruit's LCD displays with a single function call.
Programmers will also write their own header files to improve readability of their code -- for example, by encapsulating all code related to a particular functionality, perhaps troubleshooting, in one file. Another header file in the same program might, a bit ironically, be dedicated to input/output functions (but in the sense that it handles the reading and writing of data on some storage medium, such as an SD card). Header files can also #include other header files (if you're careful about how you do so).
However, header files are not usable "input/output." The compiler will read it all as one program and flash it to the Arduino just like any other code you have written.
http://www.learncpp.com/cpp-tutorial/19-header-files/

I'm just beginning to wonder whether it's possible to append strings that are concatenated from integers which are analogRead from sensors to a .h file?

No, you have the wrong end of the stick here. You can't write to a .h file, certainly not on the Arduino, because it is running independently of the development environment.

It'd make the arduino a lot more portable and would negate having to buy an SD card module.

An SD module, like the one below, only costs about $US 15, and then you can write gigabytes of data to it, and then easily move the SD card to your PC to process it.


text:
Arduino I2C long string
I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.
I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?
Master makes request for string that could be about 180 bytes max - ever.
Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
while (Wire.available())
{char c = Wire.read();
cmdInStr.concat(c);
}

Slave sends
int len = cmdOutStr.length()+1;
char ascii_num[len];
for (int i=0; i<len; ++i)
{ Wire.write(ascii_num[i]);
}

You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.
There's a number of ways around it though:

Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.
For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.
If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.
You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.

I may be being lazy but the data string is passed to other nodes on the network so getting it all the same meant I can manipulate it with common functions in my own project Library file. I wonder if there is a better or different Wire Library. This one shows four functions for directly sending Int/long but no "read" counterpart that I have found.

There is no maximum length for sending/receiving in I2C. It is the Wire library BUFFER_LENGTH 32 macro, causing this limitation.
You can either copy some code from Wire library and implement your own requestFrom function which will store data directly to your cmdInStr string buffer or you can change Wire.h to have bigger BUFFER_LENGTH.
Or another way is to extend Wire.h like this:
#ifndef BUFFER_LENGTH
#define BUFFER_LENGTH 32
#endif

and in your sketch:
#define BUFFER_LENGTH 180
#include <Wire.h>

All depends on your preferences, but implementing own requestFrom and storing it directly into your cmdInStr buffer will be little bit more efficient than copying it into Wire buffer and then into your own buffer again.
And do you really need all these data in one string, isn't it possible to proceed it on the fly?

Thanks before posting, I had tried changing the buffer size in Wire.h file but it had made no difference. I may need to go looking for specific buffer definitions as it seems that the Receive buffer was not set. But, I will try the second suggestion as that might fix it.

Well, there can be more hardware directories. Depends if you've upgraded boards. I've usually editted wrong one...


text:
GPS detecting stationary?
can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,
uint8_t speedZero() {
uint8_t spd = gps.speed.mph();
  if (spd < 5) {
    return 0;
  } else {
    return spd;
  }
}

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.
I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.

Just add accelerometer sensor to your device. It's just around 1USD and it will easily detect lack of movement.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone. - find a function that gives you a distance between two lat/long points, the remaining math is trivial

I gave an answer in PHP a few month ago, maybe it can help: https://stackoverflow.com/questions/7222382/get-lat-long-given-current-point-distance-and-bearing/26938066#26938066

Only log the values when they've significantly changed?

I found this to get me started.
http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/

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


text:
Two flow sensors, one ESP32, LCD and/or Arduino
I want to build a flow meter but the Gal/Min rating of something like this flow meter is too low. I am thinking of strapping two side by side with suitable plenums for In and Out.
I have found some sketches like this but wondering how to use the two inputs to aggregate the results to GPM and Gallons total for display on an LCD screen. I am unsure what happens if two Hall-results arrive at or about the same time but on different Data Pins.
I have priced some single sensors with a higher flow rate for the pipe size but they run to several hundred dollars. Gallons are not critical as long as I can be within about 5% error over ten minutes, our average tank fill time.
Can someone please point me at some code to get me started for an ESP32 and LCD. I'd even consider adding a Nano if that makes things easier. I imagine that would certainly prevent collision issues. Basically I need to be able to handle the flow rate to a single LCD.
Thanks

A Hall Effect Sensor like that just gives you a pulse every rotation (or two pulses per rotation, etc) of the internal vanes.
If you use interrupts to count the pulses then two pulses arriving at the same time will be handled sequentially. The interrupt flag indicating a pulse has arrived is set in hardware the moment the pulse arrives, and the CPU checks all the interrupt flags between instructions. Each flag is handled sequentially, the order determined by interrupt priority settings and a "natural" order determined by the internal wiring of the CPU.
However there is a better way on the ESP32, and that is the Pulse Counter peripheral.  This is designed to count pulses like the signals from Hall Effect sensors.
You can just leave the Pulse Counter counting your pulses, then periodically read and reset the pulse count to see how much water has flowed in that period. It looks from the documentation that you can have two inputs both making the same counter increment, so it will do the aggregating for you.

Great, thanks, but reading those docs and the example code it is a little out of my programming league. Would the 2-Inputs go to the same pin or different pins? I am not sure why they say that that two ports need to be shorted. I need to find some existing code. I seem to be able to understand it better by reading code than docs. I am old. :)

There is an example linked from that page. It's not for the Arduino IDE, but you can take most of it. The whole of the IDF SDK is included with the ESP32 core in the IDE, so all the function calls they detail there work fine.

Thanks again, that was the "code" I was referring to above. I looked at the .c page, but still unsure where and how the second input goes for it to be amalgamated in the count. I have a small version flow sensor arriving a few days to test, but would like to find some code that already uses two inputs. I am not that smart --yet.

TBH I only just found that peripheral exists. I have no clue how to use it. It seems that each counter has two "channels" which can be either count up or count down. Each channel is associated with one pin (no idea what pins). The ESP-IDF is much better documented than many frameworks though, so it shouldn't be too hard to work out.

Cross referencing that documentation with the code and the ESP32's datasheet should reveal clues.

I found a YT video that explains some uses of the PCNT and it doesn't seems to be what I am looking for. It appears to be more like a trigger system that will flag an event at a count milestone. https://www.youtube.com/watch?v=vk5QZnWdlAA but thanks for your help anyway. I guess it is back to using Interrupts and given you comments above about them being handled sequentially I think I can make that work for what I need. Thanks again for taking the time to explain stuff.

I would recommend you spend a few hours watching basic electronic tutorials than double that time watching Arduino Tutorials.


text:
Can't get Ubuntu to see FTDI cable for breadboarding Arduino project
I am in the process of breadboarding an Arduino for a project and am using my FTDI Serial cable Adafruit FTDI Cable (tested working on Windows 7). I have also tested the breadboarded Arduino successfully on Win7.
When I plug the FTDI Serial cable into my Linux (Ubuntu 14.04 with Mint Desktop) laptop and the other end to my project (exactly as I did for Windows and it works for Win7), the Tools, Port is grayed out when in Linux.
I have tried running Arduino as root, with no success.
The output of : dmesg | tail is
sudo dmesg | tail
[  729.069015] usb 4-1.2: New USB device strings: Mfr=1, Product=2,     SerialNumber=3
[  729.069019] usb 4-1.2: Product: TTL232R-3V3
[  729.069022] usb 4-1.2: Manufacturer: FTDI
[  729.069024] usb 4-1.2: SerialNumber: FTF50VXW
[  729.487689] usb 4-1.2: USB disconnect, device number 4
[  729.615330] usbcore: registered new interface driver usbserial
[  729.615384] usbcore: registered new interface driver usbserial_generic
[  729.615432] usbserial: USB Serial support registered for generic
[  729.621997] usbcore: registered new interface driver ftdi_sio
[  729.622057] usbserial: USB Serial support registered for FTDI USB Serial Device

When I type "lsusb" into the terminal, there is no difference between when the FTDI is plugged in and not plugged in.
I have tried switching ports with no success.
Any suggestions?

Is there a /dev/ttyUSB0 file entry with the cable plugged in?

If it is not in the lsusb output, there should not be a device node - if there is, it is not connected to anything.  By appearances, the USB connection has failed after briefly being recognized - try a different port, try it with the logic end of the cable not connected to anything, try it with a hub or without one if you were using one.

Check if the driver is loaded, in Terminal type:
lsmod | grep  ftdi_sio

If you get no answer then it's not loaded, load it using:
sudo modprobe ftdi_sio

I hope this helps.

lsmod | grep ftdi-sio
shows that the driver is already loaded.

lsmod | grep ftdi-sio
shows that the driver is already loaded.
The device is appearing in the /dev/ folder
Now when I try to upload code I get a avrdude out of sync error. I have confirmed I have the correct device (UNO) selected. As the Arduino is breadboarded, I press the reset button just as compilation completes (I use this same timing successfully when downloading from my Win7 machine).


text:
Arduino Leonardo bugs and lack of removable microcontroller
Following one of the article from 2013 :

Before you start hammering that “add to shopping cart” button, note
  that the general impression around the web seems to be that the
  Leonardo still has a few bugs that need ironing out, and isn’t quite
  as beginner friendly as the Uno. For builders already familiar with
  Arduino, this is the better deal.

The question is if Leonardo is still buggy and may cause any confusion to newbie Arduino programmers. Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

The question is if Leonardo is still buggy

Probably.

and may cause any confusion to newbie Arduino programmers.

Definitely.  The whole way the Leonardo works is very different to the likes of the Uno. Transitioning from one to the other, if you don't know what the differences really mean, can be confusing.

Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

You build your circuit on a PCB and you provide an ICSP header.  ICSP stands for In Circuit Serial Programming.  You then use a hardware programmer to install either the Leonardo bootloader, which can then be used to install sketches through USB, or install a sketch direct without the bootloader.
Or, if you're making thousands of them you send your code to Atmel and they burn it to the chip in the factory for you - at a price of course.


text:
"avrdude: stk500_recv(): programmer is not responding" when uploading sketch
When I try to upload any sketch to my arduino uno r3, the code compiles, the board resets and the RX light blinks 3 or 4 times.I have nothing from the TX light.
The uploading progress bar in the IDE stucks at it's end for a period and then gives me "avrdude: stk500_recv(): programmer is not responding" 10 times.
I've done the loopback test and it works well so, what should i do ?
thanks for help.

Are you sure avrdude is using the correct baud rate for the bootloader version? Has this board uploaded successfully for you before? Are you using the same avrdude settings you used then? Has any hardware been changed; the cable, for instance? Can you try uploading to another board, or to this board using another computer?

yes, it has worked before. I guess the problem isn't in my PC, I guess it's in the atmega328p-pu chip. uncorrect bootloader or something,,...

yes, it has worked before. ... uncorrect bootloader or something,,...

Does the last program you successfully uploaded write anything to the serial port? If you just run the Arduino (no upload attempt) with the Arduino IDE's serial terminal open, can you see that output? It's pretty hard to damage the boot-loader without actually writing a new, bad one to the chip.
If the current program seems to running but not writing to serial when it should, a likely cause of upload failure is the code in 16U2 processor (or the chip itself) that handles the USB to serial conversion; it's the square 32-pin chip between the 16 MHz crystal and USB connector. Its firmware can be re-loaded - search here for how to do that. If the chip itself is damaged it is probably not worth attempting a repair.
Update: Is the +5v pin on the power header (left edge of the board, if the USB connector is pointing up) reading 5v? You'd expect the output pins to read 0v, 5v, or be noisy if they are floating. A steady 1v sounds strange. At this point it would be worth trying this board on another computer, and another board on your computer, and see which one fails.

No, there's no outputs in the serial monitor and all arduino pins'(2:13) outputs are 1v , which wasn't written in last code. it's like the arduino is completely new


text:
Trouble using a TSSP77038 with an Arduino
I have a Vishay TSSP77038 IR receiver that I would like to read the output of. It is connected as shown in the picture - Vs to 5V, GND to GND and the output to a pin on the Arduino.
My problem is that the reading is constantly low (it is active low so says it is receiving a IR signal), even when i completely cover the sensor or I am in a dark room. Can someone please tell help? Thanks a lot in advance :)

All my IR receivers require a pull-up resistor on the OUT pin.

Are you sure you don't have it wired up backwards?  This package would be easy to turn around.   It can also be mounted with the lenses either upright or to the side, adding additionally possibilities for confusion.

Gerben is correct it looks like you need a pull up resistor so that the pin is high unless the receiver drives it low.
I found this, which was the closest to useful information I found. Have a look at the proximity sensor section, it is similar to what you are using.
You'll want to know a value, I haven't got a clue.  I use 4.7K for I2C pull ups. It's probably easier to start high (weaker) and work your way down, because if you put a 100K resistor in and the signal is low, then the resistor is too strong and you need a smaller one.

From the datasheet, it looked like there was already a 33kOhm pull-up in the component itself. 4.7K is probably fine. The value doesn't really matter that much.

If there's a Pull up resistor inside it already, why does it need  another? Is there anyway to get around needing an extra one?

My first thoughts were its either to week or its disabled by some configuration option, but I doubt either of those would be the case here.
Is it possible that the internal one is suitable when VCC is at the lower end of the range (1.8V) and not suitable at the upper end of the range?

You should not need an external pullup resistor unless you have something else loading the line or are running the Arduino at a substantially higher voltage than the sensor.  In theory a very high data rate could cause that to be needed, but the sensor can only respond so fast to begin with, so that is probably not an issue.

Because this part has an internal pull-up resistor, seeing the data line consistently low is most likely cause by one of:

Reversed installation on the circuit board.  This part can actually be installed in two orientations, with the lenses up or to the side, so there are more opportunities than usual to get the orientation of the contacts wrong.
Electrical damage from past misuse
A wiring problem, short, or additional device holding the data line low


text:
Why does the current drop through a multiplexer?
I am trying to control 64 leds through a number of 8:1 analog multiplexers. The input is from pin 11 on the Arduino which is giving 40mA (maximum) and it is pulsed at 38kHz. Then I use other pins to select one of 64 leds to control. For testing, I am just trying one of those leds. The problem is that the current across the led is just 2mA, which means it is very dim. Using a multimeter, the current after the first multiplexer seems to be 4mA and after the second just 2mA. How can I get the current to increase? Thanks in advance!

Please add circuit. Guess you are using 4051. The internal resistor is approx. 70 ohm. Please see http://www.ti.com.cn/cn/lit/ds/symlink/cd74hc4051-ep.pdf

Analog multiplexers are a silly choice for a digital signal. Be sensible.

Don't depend on a digital output to provide you 40mA. That is the maximum current it can provide before getting damaged.

Analog multiplexers are not a good design choice for switching digital signals.
You should instead choose a digital solution. Maybe the 74HC138 would be a better choice? That's a 3-to-8 decoder with 3 enable inputs.
You could use 9 of them to reduce pin usage on the Arduino, or 8 of them if you have pins to spare.
One of the enables on the first-stage can be a "mater enable" - or tie one of the enables of all 8 of the second-stage together for a "master enable". Another enable to all the 8 second-stage muxes can be the PWM signal. The third is driven by the Arduino or the first stage as a MUX selector.
Something like this arrangement:

Note that the outputs are active low, so you would connect the anode of your LEDs to +5V and the cathode, through a suitable resistor, to the output.
Another option would be to use a set of shift registers that have an output enable pin. Drive that pin with the PWM signal and you can have any combination of LEDs enabled at once.


text:
Absolute noob looking for troubleshooting help
My 10-year-old son went to a "Robotics Camp" and came home with a non-functional Arduino robot. I figured it shouldn't be too much trouble to get it working. He swears he had it operating at the camp, but our best efforts notwithstanding, we were unable to reproduce his successes at home to any degree at all. Currently we seem to have an ungainly, $400 paperweight.
I'm a .Net web-developer by day, but I'm completely uninitiated when it comes to Arduino. I did enough research to learn how to upload a basic sketch- the "Blink" sketch- to our board an verify that the board is functional. Upon uploading the Blink sketch we got a flashing red LED. I was able to go into the sketch and modify the the variable values and see the results in the duration of the LED flash after uploading the sketch again. So I'm confident that we have a good connection to the PC and a functioning Arduino board.
But beyond that I'm stumped. When I attempt to upload the program that my son brought home, the robot does nothing. I can see a red LED blink a few times on the Arduino, but other that that, nothing happens.
Here's some photos of our setup:

Here's the sketch that my son brought home:
/***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 16 servos, one after the other

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These displays use I2C to communicate, 2 pins are required to
  interface. For Arduino UNOs, thats SCL -> Analog 5, SDA -> Analog 4

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
#include <QueueList.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
// you can also call it with a different address you want
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos you
// have!
#define SERVOMIN  300//150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  400//600 // this is the 'maximum' pulse length count (out of 4096)

uint16_t servoMins[] = {160, 200, 500, 150, 150, 150, 0};
uint16_t servoMaxs[] = {600, 600, 700, 600, 600, 600, 0};
uint16_t servoHomes[] = {380, 400, 300, 340, 375, 375, 0};

enum GroupType {WithPrevious, NewGroup};

#define PAUSE_COMMAND 6
#define NUM_TRANSITIONS (PAUSE_COMMAND+1)

unsigned long currentTime;

class transition
{
  private:
    unsigned long startTime;
    unsigned long totalTime;
    uint16_t pulseLenStart;
    uint16_t pulseLenEnd;
    uint16_t currentPulseLen;
    int id;
    bool transitioning;

  public:
    void init(int id, uint16_t current)
    {
      this->id = id;
      currentPulseLen = current;
      totalTime = 0;
      startTime = 0;
      pulseLenStart = current;
      pulseLenEnd = current;
      transitioning = false;

    }

    uint16_t calculate(unsigned long currentTime)
    {
      float t = 1.0f;
      if (totalTime > 1e-3f)
        t = (currentTime - startTime) / (float)totalTime;
      t = (t > 1.0f) ? 1.0f : t;
      currentPulseLen = (uint16_t)(((float)pulseLenEnd - (float)pulseLenStart) * t + pulseLenStart);
/*      if (transitioning)
      {
        Serial.println("transitioning");
        Serial.println(id);
        Serial.println(t);
        Serial.println(currentTime);
        Serial.println(startTime);
        Serial.println(totalTime);
        Serial.println(pulseLenStart);
        Serial.println(pulseLenEnd);
        Serial.println(currentPulseLen);
      }
*/
      if (t >= 1.0f)
        transitioning = false;
      return currentPulseLen;
    }

    void createTransition (uint16_t pulseLen, unsigned long time)
    {
/*      Serial.println("create Transition:");
      Serial.println(id);
      Serial.println(pulseLen);
      Serial.println(time);
*/
      pulseLenStart = currentPulseLen;
      pulseLenEnd = pulseLen;
      totalTime = time;
      startTime = currentTime;
      transitioning = true;
    }

    bool isTransitioning()
    {
      return transitioning;
    }
};

transition transitions[NUM_TRANSITIONS];

struct Command
{
  uint16_t pulseLen;
  unsigned long totalTime;
  int commandType;
  GroupType groupType;

  void execute()
  {
    transitions[commandType].createTransition(pulseLen, totalTime);
  }
};
QueueList<Command> commandQueue;

void program ();
void restoreHomePositions (double seconds);

void setup()
{
  pwm.begin();

  Serial.begin(9600);
  Serial.println("Hello world");

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

  for (int servoNum =0; servoNum < NUM_TRANSITIONS; servoNum++)
  {
    //pwm.setPWM(servoNum, 0, servoHomes[servoNum]);
    transitions[servoNum].init(servoNum, servoHomes[servoNum]);
  }

  restoreHomePositions (0);
  program();
  restoreHomePositions (.75);

  yield();
}

void processCommandQueue();

void loop()
{
  currentTime = millis();

  processCommandQueue();

  for (int servoNum = 0; servoNum < NUM_TRANSITIONS; servoNum++)
  {
    if (transitions[servoNum].isTransitioning())
    {
      uint16_t pulselen = transitions[servoNum].calculate(currentTime);
      if (servoNum != PAUSE_COMMAND)
      {
        pwm.setPWM(servoNum, 0, pulselen);
        Serial.println("setPWM");
        Serial.println(servoNum);
        Serial.println(pulselen);
      }
    }
  }
}

bool isTransitioning()
{
  for (int servoNum = 0; servoNum < NUM_TRANSITIONS; servoNum++)
  {
    if (transitions[servoNum].isTransitioning())
      return true;
  }
  return false;
}

int frame = 0;
void processCommandQueue()
{
  if (!commandQueue.isEmpty())
  {
    Serial.println("Frame");
    Serial.println(frame);
    frame++;
  }
  if (!commandQueue.isEmpty() && !isTransitioning())
  {
    do
    {
      Command top = commandQueue.pop();
      top.execute();
    }
    while (!commandQueue.isEmpty() && commandQueue.peek().groupType == WithPrevious);
  }
}

void move (int commandType, uint16_t pulseLen, double seconds, GroupType groupType = NewGroup)
{
  Command command;
  command.groupType = groupType;
  command.commandType = commandType;
  command.pulseLen = pulseLen;
  command.totalTime = (unsigned long)(seconds * 1000);
  Serial.println("Command:");
  Serial.println(groupType == NewGroup ? "NewGroup" : "WithPrevious");
  Serial.println(commandType);
  Serial.println(pulseLen);
  Serial.println(command.totalTime);
  commandQueue.push (command);
}

void rotateWrist (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[5], servoMaxs[5]);
  move (5, pulseLen, seconds, groupType);
}

void bendWrist (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[4], servoMaxs[4]);
  move (4, pulseLen, seconds, groupType);
}

void rotateForeArm (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[3], servoMaxs[3]);
  move (3, pulseLen, seconds, groupType);
}

void bendForeArm (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[2], servoMaxs[2]);
  move (2, pulseLen, seconds, groupType);
}

void bendUpperArm (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[1], servoMaxs[1]);
  move (1, pulseLen, seconds, groupType);
}

void rotateRobot (int percent, double seconds, GroupType groupType = NewGroup)
{
  percent = percent < -100 ? -100 : percent;
  percent = percent > 100 ? 100 : percent;
  uint16_t pulseLen = map (percent, -100, 100, servoMins[0], servoMaxs[0]);
  move (0, pulseLen, seconds, groupType);
}

void pause (double seconds)
{
  move (PAUSE_COMMAND, 0, seconds, NewGroup);
}

void restoreHomePositions (double seconds)
{
  rotateRobot (0, seconds, NewGroup);
  bendUpperArm (0, seconds, WithPrevious);
  bendForeArm (0, seconds, WithPrevious);
  rotateForeArm (0, seconds, WithPrevious);
  bendWrist (0, seconds, WithPrevious);
  rotateWrist (0, seconds, WithPrevious);

}

//This is where the program goes!

void program ()
{
    //Available commands
  /*rotateWrist (where, seconds, groupType)
  bendWrist (where, seconds, groupType)
  rotateForeArm (where, seconds, groupType)
  bendForeArm (where, seconds, groupType)
  bendUpperArm (where, seconds, groupType)
  rotateRobot (where, seconds, groupType)
  pause (seconds)*/

  //example 1 -- rotates the wrist servo 100% over 2 seconds,
  //starting a new transition group.
  rotateWrist (100, 2);
  //example 2 -- bends the upper arm and the forearm at the same time
  //moving both 45% over 1.5 seconds.
  bendUpperArm (45, 1.5);
  bendForeArm (45, 1.5, WithPrevious);
  bendForeArm(45, 1.7, WithPrevious);

}

  //To start a new group, the groupType should be either NewGroup or left blank
  //Any call after that set to WithPrevious will start the transition at the
  //same time as the first transition in the group.
  //As soon as a new call is made with a NewGroup groupType, a new transition group is m
// End of your program

I wanted to include more photos, but I don't have enough reputation. :(

Plug the power pack in? What does the second board do? It is hard or impossible to help without some sort of schematic. Do you get any output in the serial monitor (eg. "Hello world"). I am guessing the second board is a motor driver board. You could get a cheap multimeter and start measuring voltages to see if anything is being sent to the motors.

It sounds like you have a working Arduino, so the money isn't wasted. This could be a good opportunity to disconnect the robot for now, and just bring yourselves up to speed with simpler sketches (programs). There are quite a few examples that ship with the IDE. Once you have a bit more confidence in how it all hangs together, getting the robot working should be simpler.

My first step would be to (after documenting the current connections!) disconnect everything and write a simple program to "wave" one of the servos. Then try connecting more parts from there. This sort of troubleshooting experience (when it works) is priceless by the way.

@NickGammon The second board is an Adafruit 16 channel PWM and Servo Driver

I'm still curious to know if the power pack is plugged in or not. Naturally it won't work if the servo driver is not powered.

@NickGammon Yes, of course the power adapter is plugged in when I'm trying to run the sketch. I left it unplugged for the photo, just so it would fit in the frame. I can verify that the servos are getting power, because when I first plug in the power adapter several of them do a little jerk. After that though, nothing happens.

@NickGammon regarding your suggestion to test the setup with simpler sketchs, I have successfully run the Blink sketch that is packaged with the Arduino IDE. I am able to use it the Blink sketch to power the red LED on the Arduino board on and off. I can change the values of the variables in the blink sketch and observe the effect this has on the duration of the LED flashes.

Here's the code for the Blink sketch: `// the setup function runs once when you press reset or power the board
void setup() {
// initialize digital pin 13 as an output.
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
delay(1000);              // wait for a second
digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
delay(1000);              // wait for a second
}`

@Majenko, My big question at the moment is whether or not I have the Arduino board wired up to the PWM servo driver correctly. How can I check this?

On my page about I2C I have a sketch that detects I2C devices (reply #6). It looks like the PWM board uses I2C, so run that sketch and see if it reports any devices (in particular 0x40).

For debugging, do you have a DVM (voltmeter)? Or even better yet, an oscilloscope? You mention seeing the servo twitch but not seeming to operate correctly, so I'm wondering whether the power supply voltage might be sagging under load. You might also verify whether the I2C SCL and SDA wires got swapped, or whether there is a missing GND connection.

I'm not familiar with the breadboard in your images. You didn't mention if you're familiar with how to use a breadboard and from what I can see I'm not even sure why its being used. It looks to me like you could just connect the jumper wires directly to the pins on the Arduino.
Was the Arduino ever unplugged from the breadboard after it was known to work properly?
Due to the angle of the photo it is hard to see which pins the wires are connected to. Can you identify which Arduino pins the six wires are connected to?

The breadboard is a standard one with lines of five connected terminals radiating away perpendicular from a center channel (which is covered in that photo). Typically this is used to allow standard jumper wires to be connected to the board's header pins rather than having to use jumper wires with a female socket at one end, and it also allows multiple jumper wires easily to be connected to a single pin.

Please consider the following to assist in your understanding of the Arduino and of the servo operation. I recently "instructed" a summer camp of teens to construct the MeArm robot arm, using inexpensive servos and an Arduino.
The servos you have will operate without the servo driver, enabling you to isolate the problem. Consider to connect the signal wire for each servo to an assigned pin on the Arduino and test each servo with the built-in Sweep sketch. Your off-board power for the servos should share the ground with the Arduino, while the +V would connect to the power lead for the breadboard and hence to the servos.
Pins 6, 9, 10, 11 are PWM capable and you can modify in the Sweep sketch to operate each one independently as a way of testing the base "kit."
The code for Sweep is simplistic, while the servo driver has a good bit of "middle-man" calculations to accomplish more refined control.
Example from the summer camp:
[in setup]
claw.attach(9);
inout.attach(10);
updown.attach(11);
rightleft.attach(6);
[in loop]
 - the following was placed in a for-loop:
claw.write(pos);
... and more code including delays and limits to pos to prevent servo chatter/slam.
This will likely show you that your servos are working (or not) and enable a better understanding of the basics, while perhaps increasing your chances of understanding the more complex and flexible servo board library of code.


text:
Serial.read() vs. Serial.readBytes()?
I'm trying to do some fairly simple serial communication and have things partially working, but am pretty confused about a couple results I'm getting.
For a little background, I'm using an Arduino Mega 2560 to try to communicate with a Dynamixel servo (MX-64) over TTL (half-duplex, asynchronous) with Tx1 and Rx1.  Basically I construct some byte arrays as instructions, send them over to the servo (with Serial1.write()), and then read back a reply.  I've actually gotten it to work pretty well if I use Serial1.readBytes(), specifying the length of the buffer (number of bytes I'm expecting).  I'm also reading back what I originally sent (first) as well as the response (second), since I have Tx1 and Rx1 tied together (required in my setup because this servo only has one data wire).
However I don't understand the difference between Serial.readBytes() and Serial.read().  If I do Serial.read() just prior to Serial.readBytes(), it comes back with -1, meaning no bytes to read... but then Serial.readBytes() gives me the byte stream I was expecting from the buffer!  What's going on here?
Similarly, Serial.available() seems sort of broken in that it tells me there are no bytes to read (returns 0), but then I can read the bytes I'm expecting with Serial.readBytes(). Additionally, I can do Serial.readBytes() after there's nothing left (or rather, there shouldn't be any bytes left...) and it will give me some bytes, but they're total garbage.
I think maybe there's something I don't understand about the way the serial buffer works, but can't find a good resource on it and the Arduino reference pages are kind of useless.  Any clues about the difference in how these operate would be much appreciated!

what IDE are you using. I recall that some of the 1.0.5'ish may be broke. I try to stick with 1.5.8 or 1.0.6

I'm using 1.5.8

readBytes is blocking until the determined length has been read, or it times out (see Serial.setTimeout()). Where read grabs what has come, if it has come in. Hence available is used to query if it has.
Note that it takes time for a message to go out and to receive either the echo or response. So simply checking the RX buffer immediately after sending something, is expected to be empty for some time. That is where readBytes sites and waits. And I bet the default setTimeout of 1s is sufficient, to get the response.
This is why you see the Serial.read() inside a while or if Serial.available. Hence I typically employ something like the following: Which emulates readBytes (for the most part).
    #define TIMEOUT = 3000;
    loop {
        char inData[20];
        unsigned long timeout = millis() + TIMEOUT;
        uint8_t inIndex = 0;
        while ( ((int32_t)(millis() - timeout) < 0) && (inIndex < (sizeof(inData)/sizeof(inData[0])))) {
            if (Serial1.available() > 0) {
                // read the incoming byte:
                inData[inIndex] = Serial.read();
                if ((c == '\n') || (c == '\r')) {
                    break;
                }
                Serial.write(inData[inIndex++]);
            }
        }
    }

Above code was quickly written and untested. But gets the idea across.

Thanks, I think that mostly answers what I was wondering about.  The servo should respond 500 microseconds after receiving its instruction (I can actually change that duration);  I've played around with adding delays but the resulting availability of bytes still seems to be somewhat unpredictable.  I will stick with using readBytes() because it seems to produce consistent results and I can predict the number of bytes I should receive back.


text:
Arduino program wont work properly for some reason
I have a arduino program that I wrote with my teammembers. We are working on a project and try to move a RC car. Here is our code.
int forward =12 ; //assign to correlating pin attached to TP06
int backward = 11; //assign to correlating pin attached to TP07
int left = 10; //assign to correlating pin attached to (left steer)
int right = 9; //assign to correlating pin attached to (right steer)

// TP09 & TP02 (don't remember which is left and right)

void setup() {
pinMode(forward, OUTPUT);
pinMode(backward, OUTPUT);
pinMode(left, OUTPUT);
pinMode(right, OUTPUT);
}

void move_Forward() {
digitalWrite(forward, HIGH);
digitalWrite(backward, LOW);
}

void move_Backward() {
digitalWrite(backward, HIGH);
digitalWrite(forward, LOW);
}

void turn_Left() {
digitalWrite(left, HIGH);
digitalWrite(right, LOW);
}

void turn_Right() {
digitalWrite(right, HIGH);
digitalWrite(left, LOW);
}

void stop_Completely() {
digitalWrite(forward, LOW);
digitalWrite(backward, LOW);
digitalWrite(right, LOW);
digitalWrite(left, LOW);
}

// loop will keep going while arduino has power
void loop() {
move_Forward();
turn_Left();
}

When we run this code, for some reason forward pin and left pins are becoming deactivated, which are the pin numbers 12 and 10. Like it does not supply voltage anymore for some reason. However right pin and backward pins, which are pins 9 and 11, which was not included in loop, works! I can run the RC car with these pins. I dont understand why this is the case. Shouldn't the left and forward pins work? If they are not working, how come? Sorry I am new to arduino programming language and its been very challenging for me and my group. Thanks in advance.

Can you show us your circuit?

On many Arduinos, those pins (10-12) are shared with the ICSP header - are you programming/testing with it plugged in or unplugged? If plugged in, you might be affected by what you're plugged into.
Here's a useful pinout: http://t.co/MKtmCILSdj
Here's a Nano pinout:
Note that the ICSP is electrically connected to pins D11, D12 and D13 - so if you have something plugged into the ICSP header, you have something connected to those pins which might be causing your problem.
If you're programming via serial port (TX/RX) and have nothing connected to ICSP, then this isn't your issue. If that's a case, it's possible to fry a few pins on a Nano and have it still appear to mostly work - trying another couple of pins might tell you more. (For instance, try D4 and D5 instead of D10 and D12.)

My arduino is nano. And the problem is that the forward and left pins are supposed to work and they dont, instead of the backward and right works. So what happens is, I upload this program to my arduino and get my circuit. I plug the any of the function cables, which are forward backward, left, and right to the pins 12 and 10, and they dont work. However, when I plug the any of the cables into pins 9 and 11 which are right and backward, they work! I even tried with LED for 12 and 9 and it did not work. However, LED flashes with the pins 11 and 10. So I dont really know what is the problem.

Have you tested this on more than one Arduino? My first Arduino board had a dead UART. Took me weeks and purchasing a second Arduino to figure it out. It worked well enough to not initially suspect the UART (I'm not a complete idiot). ;)

First: turn off the old direction before turning on the new one. Now you're doing it the other way around.
Then, in your main loop you're repeating forward and left over and over. I guess you want to move forward for some time, then turn left, then move forward again, etc.
But moving forward does deactivate the reverse, but doesn't change left or right. So you're always repeating commands which haven't been changed in the first place: forward will always be active, and so will left be. You'll go in a circle, I don't know if that is the idea.
If you want to go straight, you'll probably want to turn off both left and right? Then add a delay before turning; right now your commands occur within microseconds of each other.


text:
Documentation for creating a Board Manager profile for the Arduino IDE
I'd like to write a Board Manager profile for some Arduino boards that I have. So far I've struck out on finding the documentation on the format and contents of the files. Does anybody know where I can find it?

Documentation is kind of scarce.
Basically there are two aspects to what you want - the board definition and the board manager JSON file.
The first describes the board to both the IDE (entry in boards.txt) and to the API software (definition of what pins are what and what peripherals are where, etc).  The latter is in the file pins_arduino.h.
Then there is the JSON file that describes the whole package to the board manager and is what allows people to download the boards.txt and pins_arduino.h files (and anything else you may require) from your website.
As there is not much documentation you are best off taking an existing set of files that are close to what you want and modifying them.  Most of the time it will be a slight tweak such as re-ordering a few pins in some arrays, or changing the name of the board and maybe an upload command or baud rate setting.

Arduino has provided comprehensive official documentation. You may not have found it because, since this is developer documentation rather than something the average Arduino user needs, it is published in the wiki of the Arduino IDE GitHub repository rather than with the standard documentation on arduino.cc.
Hardware Package
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification
Boards Manager Support Files

JSON Index File: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification
Boards Manager installation archive: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#installation-archive-structure


text:
Can Android phone can be used instead of( or with) Arduino as controller?
I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

phone as controller (without arduino) - this option would be the
best
if phone cannot give commands maybe with arduino, while
using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?

In what way were you hoping to physically connect the phone to the sensors and control circuitry?

You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.
So for normal RC car you would need to have:
AndroidPhone -> Network -> AndroidPhone -> SerialInterface -> Arduino -> RC


text:
I2C: What is the difference between A4&A5 and SCL&SDA pins?
On tutorials are most people using the A4&A5 pins with the Wire.h library. But i have an arduino with dedicated I²C pins. How can i use them?

They are the same pins. They are physically connected to each other on the UNO board. (So SDA is connected to A4. SCL is connected to A5)


text:
i2c address instead of assigning pins
I found this sketch online and would like to reuse it. I do have a dot-matrix-display, that is accessable through an i2c with the address 0x70. How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?
#include <DS1307RTC.h>
#include <Time.h>
#include <Wire.h>
#include "LedControl.h"

//Pin definition constants
const int mDataIn=12, mLoad=11, mClk=10;  //Max7219 LED matrix

int h1, h2, m1, m2, s1, s2; // Each digit
int tChange; //Scratch used during change time via pushbutton

// Matrix library instance
LedControl lc=LedControl(mDataIn, mClk, mLoad,1); //Pin assignments and number of matrices (1)

void setup() {

  // Notify Arduimo that the RTC is the external time provider
  setSyncProvider(RTC.get);

  //Initialize the MAX72XX in power-saving mode.
  lc.shutdown(0,false);
  lc.setIntensity(0,1); // Set brightness to a low value
  lc.clearDisplay(0); // Clear the display
  delay(100); // Wait after initializing display

  Serial.begin(9600);
}

void loop() {

  //Isolate hours, minutes, seconds, one digit to each LED matrix column.
  h1=n1(hour());
  h2=n2(hour());
  m1=n1(minute());
  m2=n2(minute());
  s1=n1(second());
  s2=n2(second());

  // Cast as (change integer to) byte, write to LED row.
  // (Row runs from pin to pin on model used.)
  lc.setRow(0,7,byte(h1));
  lc.setRow(0,6,byte(h2));
  lc.setRow(0,4,byte(m1));
  lc.setRow(0,3,byte(m2));
  lc.setRow(0,1,byte(s1));
  lc.setRow(0,0,byte(s2));
  }

  int n1(int num) {  // Function to isolate first digit of 2-digit integer
    num = num / 10; //Integer division by 10 (discard remainder)
    return num;
  }

  int n2(int num) {  // Function to isolate second digit of 2-digit integer
    num = num % 10; //Modulo division by 10 (keep remainder only)
    return num;
  }

How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?

That is not possible as this is two totally different LED drivers. MAX72XX uses a protocol with those signals, while the dot-matrix LED display uses I2C.
You can always port the library to the dot-matrix. Or rewrite the sketch with the dot-matrix library.
Cheers!


text:
scroll text through multiple i2c connected dot matrix displays
I have 4 dot matrix displays, every one of them connected to an i2c and accessible with 0x70, 0x71, 0x72 and 0x73. All these work just fine when I address them apart. What I want to achieve is a scrolling text throughout all 4 displays. How can I do this? Are there any libraries around that already do this? (I did not find any).
Basically, this is my code:
#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

Adafruit_8x8matrix matrix[4];

void setup() {
  Serial.begin(9600);
  Serial.println("4x(8x8) LED Matrix Test");
  matrix[0].begin(0x70);
  matrix[1].begin(0x71);
  matrix[2].begin(0x72);
  matrix[3].begin(0x73);
}

Google is your friend; http://forums.adafruit.com/viewtopic.php?f=8&p=386183, for instance "nihil sub sole novum"

This is what I found behind the link @mikael-patel posted, and with a little configuration it does exactly what I want. Basically the scroll()-method handles anything neccessary.
#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

#define NUM_MATRICES 2
Adafruit_8x8matrix matrix[NUM_MATRICES];

void setup() {
  Serial.begin(9600);
  Serial.println("8x8 LED Matrix Test");

  for(uint8_t m=0; m<NUM_MATRICES; m++) {
    matrix[m].begin(0x70 + m);
    matrix[m].clear();
    matrix[m].setTextSize(1);
    matrix[m].setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
    matrix[m].setTextColor(LED_GREEN);
  }
}

void loop() {
  scroll("Hello World!");
}

void scroll(char* text) {
  int scrollPositions = (strlen(text) * 8) + 32;

  for (int x=(8 * NUM_MATRICES); x>=-scrollPositions; x--) {
   for(uint8_t m=0; m<NUM_MATRICES; m++) {
    matrix[m].clear();
    matrix[m].setCursor((x - (m * 8)), 0);
    matrix[m].print(text);
    matrix[m].writeDisplay();
   }
   delay(80);
  }
}


text:
Arduino Due with Atmel Studio 7
I was trying to switch to Atmel Studio for programming my Due project since it became more and more complex.
I managed to use the Arduino Importer Wizard to load a blink.ino file and included all the requested libraries more or less my hand that were marked as missing during compiling.
Now the compiling kind of works, but I still get this error:
Error       (inkerScript): No such file or directory    ECU arm-none-eabi-g++.exe   0

The (inkerScript): part is no typo. It is really like this in the console.
Taking a look in the Toolchain Options I have these settings (which I am not able to edit):

Going into the Miscellaneous Part of the Options I can edit these fields:

By editing the Linker Flags field, I can change the error message from (inkerScript): No such file or directory to e.g. HelloWorld: No such file or directory.
Is there anything wrong with my options? What is the correct setting for "Linker Flags" and what are they doing?
Unfortunately I am not a pro with C++ Compiling / Linker Errors / Settings.
Thanks.

I just encountered this.  After looking at other examples in the compiler command line options, it looks like it should be $(LinkerScript) instead of ($LinkerScript).
In Atmel Studio, go to project properties, toolchain, ARM/GNU Linker, Miscellaneous to find the option to change.


text:
FreeRTOS: Object not created properly from within task
I am encountering a very strange error using freeRTOS on an Arduino Mega2560:
In the setup block I can create an instance of my class:
MyClass* myClass = new MyClass(/*char*/ a, /*char*/ b, new Vector(42));
// new Vector(42) creates a new vector and pushes 42 in as first item

Using a print() method in this class, I get a legitimate output on the console, showing me all the chars and values in the vector.
Using the exact same line inside a task, causes the object not to be created properly. It seems like the fields are empty or there is something entirely wrong (like strange memory errors) with the instance. Printing it again results in an empty line (program doesn't crash) while printing a globally created instance gives the correct result.
Is there any trap in freeRTOS concerning the creation of new instances of an object inside a task? Below is the code for the task creation, increasing the task stack size doesn't help. For debug reasons this the only task running at the moment.
xTaskCreate(displayTask,
    "DisplayTask",
    configMINIMAL_STACK_SIZE + 300,
    NULL,
    tskIDLE_PRIORITY + 1,
    NULL);

'Strange memory errors' you seem to be describing values that have gone out of scope.
This is all based on your code, so I may have misunderstood.
The third parameter is causing a memory leak, unless you happen to be deleting it within MyClass (which is normally, not always, bad practice).
It sounds to me that you are trying to access values that have gone out of scope.
Its also possible that this OS requires you to do something to allow the memory to be shared between the tasks.

As I discovered just minutes ago, the FreeRTOS_AVR port only supports C and not C++. This might explain the error when creating a instance with the C++ "new" operator


text:
Failed to initialise SD card on Leonardo
I'm trying to connect SD card reader to my Arduino. For testing i'm running CardInfo example.
It seems like it runs ok when I'm running it on my Arduino UNO, but it fails to initialise SD Card while i'm running it on any Arduino with Atmega32U4 chip. I tried on two Leonardo's and Micro Pro.
This is my pinout:
CardReader       Arduino

CS          <->     4
SCK         <->    13
MISO        <->    12
MOSI        <->    11
VCC         <->    5V
GND         <->    GND

I'm using Library in version 1.2.1 if that's make difference.
Does anyone have any suggestions?

A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

And a Pro Micro has the SPI pins on 14, 15, 16.

I remember i used different pins on pro micro, but i really thought i used exactly same on Leonardo and Uno. I bit panicked after suddenly my card stopped working on both boards.