text:
Error compiling for board Arduino Uno
I am relatively new to Arduino and I am trying to code some neo pixels and every time I try to verify my code this error comes up:

Arduino: 1.8.12 (Mac OS X), Board: "Arduino Uno"
loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir >/Users/erinshankland/Documents/Arduino/libraries: open >/Users/erinshankland/Documents/Arduino/libraries: operation not permitted
Error compiling for board Arduino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

this is my code:
#include <Adafruit_NeoPixel.h>

#define PIN        6

#define NUMPIXELS 15

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRBW + NEO_KHZ800);

// this constant won't change:

const int  btnRed = 2;  // the pin that the pushbutton is attached to

const int  btnBlue = 3;  // the pin that the pushbutton is attached to

const int  btnGreen = 4;  // the pin that the pushbutton is attached to

const int  btnPurple = 5;  // the pin that the pushbutton is attached to

void setup() {

  randomSeed(analogRead(A0));

  // put your setup code here, to run once:

  pinMode(btnRed, INPUT);

  pinMode(btnBlue, INPUT);

  pinMode(btnGreen, INPUT);

  pinMode(btnPurple, INPUT);

  // initialize the LED as an output:

  // initialize serial communication:

  Serial.begin(9600);

  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)

    pixels.clear(); // Set all pixel colors to 'off'

    pixels.show();

    delay(1000);

}

void loop() {

if (digitalRead(btnRed)==HIGH){

    rndRed();

  delay(100);

}

if (digitalRead(btnBlue)==HIGH){

    rndBlue();

  delay(100);

}

if (digitalRead(btnGreen)==HIGH){

    rndGreen();

  delay(100);

}

if (digitalRead(btnPurple)==HIGH){

    rndPurple();

  delay(100);

}

}

void rndRed() {

  int led = random(0, 15);

  pixels.setPixelColor(led, pixels.Color(255, 0, 0,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndBlue() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(0, 0, 255,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndGreen() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(0, 255, 0,0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

void rndPurple() {

  int led = random(0, 9);

  pixels.setPixelColor(led, pixels.Color(171, 0, 255, 0));

  pixels.show();   // Send the updated pixel colors to the hardware.

  delay(500);

}

I am using a new library for the neo pixels but this has been downloaded and updated.
Hopefully someone can help me!

loading libs from /Users/erinshankland/Documents/Arduino/libraries: reading dir
  /Users/erinshankland/Documents/Arduino/libraries: open
  /Users/erinshankland/Documents/Arduino/libraries: operation not permitted

This is not an Arduino problem but an OS problem.
Either your /Users/erinshankland/Documents/Arduino/libraries is not accessible by your user (check the permissions) or it's not a directory.
You can try, from a terminal:
sudo chown -R erinshankland /Users/erinshankland/Documents/Arduino/libraries
chmod -R 755 /Users/erinshankland/Documents/Arduino/libraries

which will reset ownership and file permissions on the directory and everything underneath it.
If not, then delete your libraries folder (which may in fact be a file, not a folder) and recreate it and repopulate it with your desired libraries.

Thank you this worked! looked like it was a problem with my libraries!


text:
Global memory reduction when using SPI/SD
I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.
How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?
Edit:
According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:
Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.
My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.

First you need to understand the terms and measurements. If your memory "usage" figure comes from the Arduino IDE, then it does not include dynamic memory at all.  Only a very careful modeling or output from actual execution could measure that.  In terms of the static allocations you are probably measuring, buffers would be a likely suspect, not only for the those libraries, but also if you make use of Serial, etc.  If you want more precise control or optimization you may need to replace libraries with your own tuned code.

Sorry with dynamic memory I mean the SRAM usage internally within the Arduino Uno. The global data is 849 bytes. And the remainder (1150 bytes or so) is used for dynamic allocation..
And yes, the buffers is indeed something that needs to be tweaked. What would be the best way? To copy the library files to be changed within the project and use those instead of the original ones... I don't like the change the generic library files since it will affect all projects I might do in future.

What is your ultimate objective? At present you are using less than half the available RAM. What is the problem exactly? Any SD card interface is likely to require a disk buffer (probably 512 bytes) so you won't get much below that.

Thanks for your good question and remark about the SD buffer. I will edit the question.

Note that there are various ARM chips that cost no more than an ATmega but have substantially more RAM.  Some of them even have Arduino ports of various maturity.

@ChrisStratton I know (I thought they were more expensive though), but I think they use 3.3 V and I am really a beginner electronics wise, also I probably need to rely on common libraries/lots of support and for the Arduino Uno there is more 'help' available. Also since it will be my first real project I want to know what I can get maximum out of a (simple) Arduino before making it too 'easy'.

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.
There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index_p.html
Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.
Cheers!

Thanks for the answer. In that case I will keep the 512 bytes (it shouldn't be a sub-project just to overcome this problem.  However, if the Petit FAT works, maybe I can use it temporarily.
The last sounds interesting, but might be a bit tricky but workable.
Or maybe I try to dynamically create the 512 byte buffer and just remove it after use (which is after the copy).

To allow BMP images (from SD) to be written to LCD without a lot of buffer copying I introduced a callback in the Cosa Canvas handler in the  form of a virtual member function. Please see https://github.com/mikaelpatel/Cosa/blob/master/libraries/Canvas/examples/CosaCanvasBMP/CosaCanvasBMP.ino for an example.

Thanks, I will take a look into that, very nice to have an example, it might be similar with buffer copying to an SRAM

source: Stack Exchange

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

authors: Егор Пахомов

sort: votes


text:
Arduino PWM output cannot drive MOSFET 0-12V
On an Arduino Uno, the PWM pin 3 is connected to the gate pin of an N-channel MOSFET STP16NF06L. The source pin is connected to ground of a 12 V power supply and drain pin connected to a multimeter. The other end of the multimeter is connected to the positive terminal of the power supply.
Question: When Arduino varies its PWM output from 0 to 255, the multimeter reading goes from 11.50 V to 12.10 V. Why isn't it 0 to 12 V?
When the FET gate is connected to the Arduino pin that outputs either 0 V or 5 V, the multimeter reading is as expected at 0 V and 12 V respectively.

Because there is no current??????? Check this schematic: Add one side 10kOhm resistor to the +5V, attach multimeter to another. And other end of multimeter to GND. BOOM its ~5V. Why? Because no current! Add all variables to Ohms law

Connecting a load helps! Why is it that when using digitalWrite, the multimeter is able to read 0 or 12V, but not when using PWM with analogWrite?

Briefly: Current makes the voltage to drop. You should read some basic info: http://en.wikipedia.org/wiki/Voltage_drop or what ever.

Assuming you have a suitable FET You should have a circuit in line the following.
http://elinux.org/RPi_GPIO_Interface_Circuits#Using_a_FET
You should have some kind of load (a multimeter will have too high an impedance). Use a resistor 4.7k or smaller. You should also have a resistor on the gate

It works! Whats the reason for using a resistor at the gate?

Also put a LED with a resistor connected trough drain, then you read the voltage across the resistor and also have visual feedback with the LED. Resistor should be with 0V when your pin is LOW. It's easier to work with transistor knowing if there is current or not.

When the FET is saturated (pin 3 is high), I would expect the instantaneous voltage to be the full 12 v. When pin 3 is at 0v, there should be no connection across the FET; I would expect the voltage to fluctuate randomly. you might see the same if you measure voltage with nothing touching the probes, especially if the probes move relative to each other.
I'm fairly new to FETs, so I may be on completely the wrong track.

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


text:
How do I give the ENTER keypress?
I have a Teensy set up as a keyboard, joystick, and I'm giving keyboard commands. Letter and number keys are going fine. But when I try sending ENTER, I get some extra code in my Linux terminal:
$ 16424
16424: command not found

the code I have to give the ENTER key goes like this:
void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  Serial.begin(9600);
}

void loop() {
  // read the digital inputs and set the buttons
  Joystick.button(1, digitalRead(0));
  Serial.println(digitalRead(0));
  if(digitalRead(0)==0){
    Keyboard.println(KEY_ENTER);
  }
  delay(50);
}

where is this  "16424" coming from, and how do I send an ENTER keypress?
I am using a Teensy 2.0, on Linux, with Arduino IDE 1.6.7.

Keyboard.println((char) KEY_ENTER); might be the problem?

You can't just "print" a key like that. You use print for sending text.
When you use println it sends an enter key along with your text, so you can do :
Keyboard.println("ls -al");

and it will send the text ls -al and press enter for you.
If you want to do it in the 'raw' way you will need to press and then release the key:
Keyboard.press(KEY_ENTER);
Keyboard.release(KEY_ENTER);


text:
What is the datatype of the pinMode function?
I just tried it, but the Arduino IDE crashed, I hope its not related.
I want to declare a datatype like this:
int a = pinMode(pin, OUTPUT);

or something like that, but I'm not sure what datatype the pinMode function uses. I looked on the pinMode documentation page, of the Arduino website, and I see basic usage, but not a more clear definition of the source code for that function.

pinMode(pin, Mode); is a void. It doesn't return anything. It simply sets a pin as an OUTPUT or an INPUT.
It says it in the link you posted.

Returns
None

That means that the function doesn't return any value.


text:
how does an 8-bit AVR do 10-bit analog read?
I am building a pH meter and having a real close look into the analog components, and reading the Arduino documentation for analogRead().
https://www.arduino.cc/en/Reference/AnalogRead
I see it says the Arduino, in my case an 8-bit AVR ATmega328 Arduino Uno,
yields a resolution between readings of: 5 volts / 1024 units or, .0049.
My question is whether that is accurate, or even possible. How can an 8-bit MCU provide a 10-bit analog read? how does that work?
Shouldn't the analog read be 2^8 or 256?

It can do a 10-bit reading quite simply - because the ADC is a 10-bit ADC.  The CPU register size doesn't dictate what it can communicate with, either internally or externally.  The only thing it dictates is how big a number it can cope with at any one time.  Because of this the 10-bit result of the ADC is spread across two registers - 2 bits in the "high" ADC result register, and 8 bits in the "low" ADC result register.

...or two bits in the 'low' and 'eight' in the high. You can decide which within your code. The purpose of this is to allow you to easily 'downscale' your 10-bit ADC result to 8-bit : With the eight most-significant-bits in one register you can use one single read command to get your result. This can be useful if you don't need a 10-bit resolution, for example if the input is so noisy that the lowest bits become irrelevant.

@chaaarlie2 Also the left-alignment option gives you in effect a 16-bit value (though with 6 lowest bits static) which is very useful if using standard mathematical algorithms etc that expect a 16-bit value. Means you don't have to do any expensive shifting of each and every sample.


text:
Debugging a RadioShack Arduino motor/sensor shield
I bought a cheap "Make" kit at RadioShack, which includes some sort of proprietary Arduino Uno compatible motor/sensor shield. Naturally, the documentation is pretty bad. The documentation and Arduino code for the kit is here:
https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit
It includes a circuit schematic (2770168-CorePCB_schematic.pdf), but I'm still having trouble mapping the pins to the Arduino's pins. Can anyone help me make sense of this?
What I've made out so far is the shield's screw terminals appear to be connected to quadruple h-bridges. However, there are several other pin headers that I can't quite make out. I think it also directly exposes 4 of the Uno's ADC pins and 4 DIO pins. There are four pins for dual IR line sensors, but there's a lot of circuitry between these and any Arduino pins. Almost everything feeds into a DC6688F2SCN chip, but I can't find a datasheet anywhere, so I have no idea what it does.
The manual says jumpers on J16 need to be removed in order to connect to the Uno over USB, so it looks like I can't use the shield with the board and debug via USB at the same time. Is this board worth investigating or should I trash it?

http://www.dragonchip.com/TechDoc/DC6688.htm

@IgnacioVazquez-Abrams, Yeah, I found that too. It contains no documentation...unless you count a Windows exe as "documentation". When did people stop publishing datasheets as PDFs? Either way, that doesn't help me on my Linux box...

That seems to be a PDF in an encrypted SFX zip, but I haven't actually tried running it yet.

The DC6688F2SCN is clearly a microcontroller, so what matters is not really its data sheet, but rather its custom firmware.  The schematic appears to show it connected to Arduino Digital Pins 3 and 4, so you'd need a software serial on those to exchange commands with it, once you figure out its baudrate and language.  In the version of the schematic provided, there doesn't seem to be any cross connection to digital pins 1 and 2, but if there were that would interfere with the USB-serial (while allowing use of the ATMega's hardware serial to talk to the DC6688F2SCN).

Probably your most productive course of action is to see if there is example code somewhere.  Failing that, you could also cut the traces to U6 & U7 and wire those (through resistors) to digital pins instead of the DC6688F2SCN (which you would basically ignore).

@ChrisStratton, Actually, my link should also include some sample code. You're right, it does appear to be a microcontroller connected to the arduino via serial, which accepts commands encoded as specific bytes. However, the code's not very well documented either, so reverse engineering the pinouts from the commands and port mappings is still a challenge.

I fixed the broken link, carry on.

There is a bit of info on the DC6688F2SCN here: Chip Selection Guide, but Chris is 100%. Without the firmware, all you can do is look at the source code for the Arduino side.
If you look closely at the top of the board, you can see that one side of J16 goes to pins 2 & 3 and the other to 0 & 1. On the schematic, there are some other components hooked in there as well. The serial is definitely going using 0 & 1. I'm not sure why they have them wired to 2 & 3. It's probably a good idea not to put anything on any of these four pins.
That's pretty good though. Compare it to the SainSmart L293D shield, which is significantly cheaper but eats up eight digital pins when driving four motors. Also, the L293Ds can only put out 600 mA per channel while the Bs can do a full Amp.
The documentation isn't very good and the supporting code also has some issues; but, overall, this is a pretty decent package. It comes with the erector set pieces as well. You also get three IR sensor channels.

A google search for DC6688F2SC  returns spec sheet under Dragonchip (here). It's actually a rather nice chip when you look up the specs on it.

Unfortunately, this does not add much over the comments already made. Please see Ignacio's comment from last year. If you could expand your answer, then that would be great.

@Greenonline please see http://meta.stackexchange.com/questions/117251/what-should-be-done-with-questions-that-have-been-self-resolved-as-a-comment-ins. "Answer stealing" from a comment is considered okay on Stack Exchange

@AnnonomusPenguin -  Granted, but I was just trying to encourage thomas to expanded the answer somewhat, if at all possible. :-)

@Greenonline yes, the OP should expand the content of their post.


text:
How to monitor 12 V LiPo charging from Arduino
What's the safest way to determine a lithium-ion polymer battery's discharge and charging state using an Arduino?
I see a ton of 12 V LiPo batteries like this being sold on eBay and elsewhere.

They have a built-in charger, and I'd like to use one to power an Arduino, but the Arduino needs to know "when" the battery needs to be charged, and "when" the battery is fully charged. Unfortunately, the battery doesn't expose any pins or LEDs or other outputs that I could tap into.
I've found a few LiPo charging circuits specifically designed for the Arduino, but they all can only handle 3.7 V cells.
I'd like to avoid having to disassemble the battery or modify it to allow me to monitor its state. Is there an easier way, like connecting a battery lead to an analog pin and measuring voltage, or using a coulomb counter?

You can use 2 resistors to form a voltage divider, and safely measure the battery voltage using an analog pin.

I ASSUME they use an internal converter or regulator. 4 LIPO = 12V to 16.8V. 3 LIPO = 9V to 12.6V. ANY LIPO charger worth it's salt will charge the unloaded battery until full then stop. If it does not it's dangerous rubbish. | Something like this gives you access

Resistor divider allow current monitoring. If quiescent drain matters a high side transistor can turn off divider and a low side transistor drives the high side. 3 resistors and 2 transistors plus divider.

@Gerben, I'm not sure that'll reliably work in this case. It might work when the battery is unplugged from the charger, but when plugged in, the voltage will probably spike to 12V even if the battery isn't fully charged yet.

@RussellMcMahon, I agree, but I'm not concerned about the built-in charger being at fault. For my application, the device needs to take action depending on battery state. e.g. notify the user over wifi when charging is complete or when it needs to be charged.

@Cerin It will indeed only be reliable to measure battery-charge, while not charging.

@Cerin  Note my point above that you are probably dealing with a boost converter's  output  - if so the 12V will give minimal to no indication of battery state of charge or when charging is complete. ie you are trying to interpret battery state from the behaviour of a boost converter whose characteristics vary by manufacturer and/or wind direction. If you used ones like I linked to that have an separate low voltage power supply you could add a low-side sense resistor and easily monitor charging. This requires no battery pack modification. At worst an adaptor between plug pack and battery.

@RussellMcMahon, I don't understand. The battery I linked to likely does not have a boost converter. Google it. People have disassembled them. They're just 3 * 3.7V cells wired in series. The "12V" in the title is a misnomer, and most descriptions claim it'll output somewhere between 10-12V. Also, the product you linked to appears to be almost identical to the one I linked to, just at a lower mAh rating. When charging, won't the output cable will always read 12V, even if the battery is nearly depleted, since the power's then coming from an external source, making divider meaingless?

@Cerin The extra information is useful - providing it initially would have helped, and copying it into the question now would be a good idea. The photo you showed adumbrated that a mains AC power cord was the input. If it's the same as mine, and if it contains 3 x LiPo cells, then a complete solution is easy. | For voltage monitoring use a divider as I suggested above. | For charge monitoring use a low side sense resistor (as above). This allows you to measure CURRENT by dropping a small voltage across it. | And, no, charge voltage when fully 'flat' will start at 9V and rise to 12.6V max ...

... all at constant current (if the charger is any good at all) and will then taper to a reduced current and then stop charging. The transition from "some current" to "no current" signals end of charge. | Summary: Resistor divider of battery voltage to get V in ADC range. If desired a high side switch to turn off divider. Charging can be by monitoring a low side current sense resistor (some minor complications need addressing) OR charge will be easy enough to spot by watching battery voltage when charge terminates. A high side transistor can probably be used to detect some/no charge current.

The above could be made an answer with circuit etc if it was clear it would be worth the effort (attitude, not rep) and if all information was provided. The original "They have a built in charger" was wrong and majorly misleading. They have an external ~= 12V charger and that makes a vast difference. ... | The info re "~= contains 3 x LiPo cells, people have opened them" makes a vast difference too. Answer can only be as good as information available and the better the question the easier it is to give good answers.

@RussellMcMahon, Interesting. But what do you mean by "low side current sense resistor"? I understand what that is, but doesn't that  require a differential amplifier in order to measure the voltage drop? Is that another component I'd have to add or is there anything built-in to an Arduino that could fill the role? Sorry for the earlier confusion. And yes, this would be better placed in an answer :)

@RussellMcMahon, Also, if the true battery voltage can be measured while charging (and I'm still not completely convinced that'll be the case), then why would you want to also measuring current flow to determine when charging is over? Couldn't that be determined by battery voltage? e.g. if Vbatt=12.1V then charging is probably complete.

... (and I'm still not completely convinced that'll be the case)... ... ie nothing ever needs to be taken on faith, but if you do not want to take the advice as is you can easily do some web research to persuade yourself one way or the other.

Last try: Read this page from Battery University on Charging Lithium Ion batteries . Understand what it says about battery terminal voltage during CC (constant current) and CV (constant voltage) stages. Confirm as much as you wish from any reputable topically related site that this is THE standard way to charge LiIon (and LiPo are functionally identical).
| Read what I've written above in the light of what you have learned OR hold whatever theories you wish re spiking to 12V etc. Which would be a  shame.

@RussellMcMahon, Thank you. That link answered my question. I didn't realize that lipo voltage doesn't accurately reflect the battery's charging state, while current flow does. Although I'm still not sure how to easily measure this with an Arduino.

In the CC mode (1st stage of charge up to 70%+- (see their chart) the voltage is a good measure of charge. When you reach CV mode (usually 4.2V/cell) the V is constant and I tails UNDER BATTERY CONTROL until terminated by the charger at K x Imax where K is a design decision (see their page) but from 50% to 10% usually. 50% gives long life and slightly lower capacity. 10% give noticeably shorter cycle life and  slightly higher capacity. Stopping when V =just reaches 4.2V gives say 70%-80% of capacity but much greater cycle life. ...

...  If you put a very small resistor in ground lead of battery you can tell when the charger suddenly cuts off.Voltage drop must be very small. A Hall sensor can do this at minimal V drop or a resistor with mV range drop. Arduino 5V ADC 10 bits is about 5 mV/bit so a 50 mV drop at full current is detectable. ie need to allow say 5 counts to be safish as 0.0 V  will not read 0 count on ADC. There are other ways. .

@RussellMcMahon, So if I'm using a voltage divider to measure the battery's voltage, I could also use that to detect current drop/charge completion by detecting a very small voltage drop?

Note that what you hav suggested re charge completion is not what I suggested. The answer to what you suggest is maybe/probably.

If you want to buy something off the shelf that will provide power for an Arduino, try a power bank - they have USB out, and are also charged via USB. I found that I had to put a 100 Ohm resistor to stop mine going to sleep, but it's +5V native.
A 100 ohm resistor (0.25 watt at least!) draws 50mA, so a 5200mAH powerbank like http://www.dx.com/p/universal-5200mah-external-li-ion-battery-charger-power-bank-w-led-indicator-usb-cable-pink-362725#.VQneCnWjlIc would leak it empty in 104 hours. If you use at least 50mA at all times, then this isn't needed - I think an Arduino draws 35mA already, so you should get away with a 300 Ohm resistor, drawing 16mA. Some experimentation might be needed.

But again...these don't allow you to monitor the battery. Also, your link is to a case, not a battery...

Fixed link to point to battery, not case. You might be able to hack it, since it obviously has a monitor in there; at least you'd be able to pick up the status lights.

Use a 10V zener diode. Check it’s voltage drop, and use that in your analogRead logic.
Get the full voltage with a DMM, and also the low cut-off voltage.


text:
GikFun Arduino Nano locking up on serial I/O
I'm running into a problem with a GikFun Arduino Nano. The symptom appears when I'm reading the receive buffer to clear it after an operation completes. The unit just appears to stop somewhere in the loop function and never continues.
I know that this unit has a CH340 UART on it which seems to have issues.
Any suggestions on what I can do?
OP Edits
This code is more or less based on the code from this Make: article. I originally had this assembled through an Arduino Uno R3 with an HC-06 (Kootek BT2S) module. Everything connected via solderless bread-board.
This entire circuit works properly with the UNO, which I had it running on SoftwareSerial using pins 2, 3. After putting this on a perf-board in a project box using the GikFun Nano, it was not behaving. I had a number of wiring issues, which I resolved, but still had issues communicating on the HC-06/SoftwareSerial. I re-did the wiring using pins 0, 1 for the Serial and removed the SoftwareSerial references. The circuit worked as I expected with the HC-06 working as it had before. But if I issued more than 1-2 commands via Bluetooth the unit would just get stuck. I also tried this without the HC-06 connected and just used the Serial Monitor through the IDE same behavior. It would randomly lock up after clearing the receive buffer.
Code - as requested:
const int statusLED = 13; //the pin you connect your status LED to
const int desiredBaud = 4;//index of your desired baud rate 4 is 9600
char* myPin = "1234";//change to the pin of your choice

const int memRed=0;
const int memGreen=1;
const int memBlue=2;

const int redPin= 9;
const int greenPin= 10;
const int bluePin= 11;
const int cmdLed= 12;

// Max Red - 255
const int max_red = 255;
// Max Green - 90
const int max_green = 255;
// Max Green - 100
const int max_blue = 255;

int red= 255;
int green= 255;
int blue= 255;

unsigned int baudLookup[] =
{
  1200,  //code 1
  2400,  //code 2
  4800,  //code 3
  9600,  //code 4
  19200, //code 5
  38400, //code 6
  57600  //code 7
};

void setup()
{
  Serial.begin(9600);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(cmdLed, OUTPUT);
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(9600);
  delay(1500);//wait for reset to complete

  Serial.print("AT");
  delay(1500);//wait for reset to complete
  while(Serial.available()) {
    Serial.read();
  }
  delay(1500);//wait for reset to complete

  digitalWrite(statusLED, HIGH); //SUCCESS!

  digitalWrite(redPin, map( red, 0, 255, 0, max_red) );
  digitalWrite(greenPin, map( green, 0, 255, 0, max_green) );
  digitalWrite(bluePin, map( blue, 0, 255, 0, max_blue) );
}

void loop()
{
  digitalWrite(statusLED, LOW); //fast blink means success
  delay(200);
  digitalWrite(statusLED, HIGH);
  delay(200);

  String stat;
  char buffer[13];
  buffer[12]= 0;
  if( Serial.available() >= 3 ) {
    String stat = String("OK");

    Serial.readBytes(buffer, 3);
    buffer[3]= 0;
    String command= String(buffer);

    Serial.println(command);
    if( command == "GET" ) {
      char outBuffer[7];
      sprintf(outBuffer, " %02x%02x%02x", red, green, blue);
      stat += outBuffer;
    }
    else if( command == "SET" ) {
      if( Serial.available() >= 6 ) {
        Serial.readBytes(buffer, 6);

        int redVal= (getVal(buffer[0])<<4) | (getVal(buffer[1]));
        int greenVal= (getVal(buffer[2])<<4) | (getVal(buffer[3]));
        int blueVal= (getVal(buffer[4])<<4) | (getVal(buffer[5]));

        digitalWrite(redPin, map( redVal, 0, 255, 0, max_red) );
        digitalWrite(greenPin, map( greenVal, 0, 255, 0, max_green) );
        digitalWrite(bluePin, map( blueVal, 0, 255, 0, max_blue) );

        red= redVal;
        green= greenVal;
        blue= blueVal;

        char outBuffer[7];
        sprintf(outBuffer, " %02x%02x%02x", redVal, greenVal, blueVal);
        stat += outBuffer;
      } else {
        stat = "ERR";
      }
    }
    else {
      Serial.println("No Command");
    }
    Serial.println(stat);
    Serial.println("Clearing receive buffer");
    delay(1500);
    while(Serial.available()) {
      Serial.read();
      delay(100);
    }
    delay(1500);
  }
}

byte getVal(char c)
{
  if(c >= '0' && c <= '9') {
    return (byte)(c - '0');
  } else {
    return (byte)(c-'A'+10);
  }
}

You need to show code which experiences the problem.  Even it not happening to a board with a different USB-serial implementation would not be proof against invalid assumptions in the serial code broken by permissible behavior of the converter or its driver.  Of course, a hardware or driver issue is a possibility too, but don't jump straight to assuming that.

I'll post code shortly

This mix of delays and buffer flushing is exactly the kind of invalid assumption I was talking about... it is just asking for unreliability, and your  while loop that reads with delays could easily never terminate.  Instead you should end your commands with something distinct, like a newline, and read until that.  Generally you want to avoid flushing - or at least, only flush until a defined endpoint.  Also, your description of what you were ultimate doing sounds like trying to use the hardware serial pins for both the USB-serial and the bluetooth, which isn't really workable.

@Chris I appreciate your feed back on this and yes assumptions are a total foul up on my part. As for the serial, I disconnected the HC-06 when using the monitor

@Chris ... looking back over this you are 100% spot on with the possible infinite. I'm going to try and gut out some of the stupidity I introduced on this and give it another go. Would you please post an answer so I can at least give you credit for your feedback?

The mix of delays and flushing in your code has a high chance of leading to unreliable operation.  Consider for example:
Serial.println("Clearing receive buffer");
delay(1500);
while(Serial.available()) {
  Serial.read();
  delay(100);
}
delay(1500);

As the loop there can only consume about 10 characters per second, it would be quite easy for something on the far end to produce inputs faster than they are consumed, essentially making the loop infinite.
Time-based delineation of serial messages tends to be quite risky; better reliability is usually had by using a defined delimiting condition - for example, ending each message with a newline character and reading until that is seen.
USB-serial conversion also introduces added challenges for time-based schemes, as it introduces a sense of grouping into packets into a stream which in its native form does not have any.

Chris - again thank you for your help on this - I redid the logic gutting out all of the stupidity and got the program stable. This also included adding a serialEvent() implementation and remembering how to properly use the stdc library. Everything was going swimmingly until I think I accidentally shorted out my HC-06 and fried it. It was working fine before that happened and I've got a replacement on the way.

Glad you made progress and sorry to hear about the accidental toasting.  Just as a last caution, keep in mind that serialEvent() is not an interrupt or thread of its own - it runs only between calls to loop() so doesn't differ much other than visually from checking availability at some point within your loop.

Thanks for the heads up. I took the code that is detailed in the serial event documentation and it was behaving.

The issue would be with whatever you did in your loop() - serialEvent() can only run when that is done taking up time, and so it can only make data available for the next iteration of loop().

And that is exactly what I want


text:
Arduino IDE crashes without any warning
I'm a beginner in Arduino. I just installed Arduino IDE (arduino-1.0.5-r2-windows) but when I try to run its not responding and crashes after few minutes. I tried re-installing it and removing the temporary files but none of those helped.
Can anyone tell me what causes this problem and how to debug it?

It might be helpful to know some more details about your system, e.g. what version of Windows are you using? Is it 32 or 64 bit?

Additionally, what does "crash" mean? Any error messages? Slows down? After a specific action?

Not really a fix, but you might want to try an older version of the IDE.

And if you run it from a terminal?

The ide was slow and closes after sometime without any notice. I didn't try running it from terminal. But I switched to arduino 1.5.6 , it works fine. Thanks.

Installing Arduino 1.5.6 solved the issue.


text:
How can I connect the Tamiya double gearbox to Arduino Uno?
I'm working on building my first robot. this is my first foray into DIY electronics. I already have an Arduino Uno, and I have ordered the Tamiya double gearbox here. My goal is to control the gearbox to move the robot, but from what I've already read, I need to have something between the Ardiuno and the motors. It seems like people have trouble doing that because the included motors are low voltage, so the Arduino motor shield won't easily work.
I'm looking for a clear solution to making this thing run, in the simplest way possible. One thing I'm considering is replacing the motors in the gearbox with these motors. If I do that, am I right in thinking I could run them from the Arduino motor shield?
If there is a simpler (or cheaper!) way of making it work than being stuck on the Arduino Motor shield, I'm game for that. I've just gravitated to that solution because it seems simpler as an electronics noob. (I haven't bought that shield yet.) But I'm really open to other solutions, so if you can, I'd appreciate the advice!

Here's what I've found about both the motor shield and the motors:

Motors are 3-6V and will use a lot of amperage. This may be a problem with a mobile robot. You'll have to figure out a power source that can provide 4+ amps... on battery power that's a lot. Personally, I would go with a continuous rotation servo for a compact, light robot.
Motor sheild can provide 2x 2A channels at 5-12 V (Source) using the two + and - terminals on the bottom left side of the shield. You must connect external power, because USB can't provide enough power. I can't find if the motor shield will limit current if it goes over, but if you do use the gearbox, I'd recommend another route for control that's 1/6rd the price.

This chip was recommended by Pololu on the product page.

Time to whip out your soldering iron! Really, soldering is a great investment and you'll get to a point soon where you'll need one; there will be no other alternative. Luck for you, you only have to solder 16 joints. Headers are included.
Diagrams from Pololu's site:

  *(Click to enlarge ^^^)**

*I added a little text to this image.

Thanks! For clarification, if I use the controller you mention above, then I can just use the included motors, correct?

Glad I could help! Yes, @Steven, you can use the included motors. Also, the controller is linked from the motor product page FYI.

Great. One last question—if I'm following the controller's datasheet correctly, in code on the arduino I simply set the pin connected to Ain1 to HIGH to go forward. Do you think that's correct? One of my reasons for trying to stay within official Arduino stuff earlier was that I'm a bit intimidated by going off-reservation code-wise! You've emboldened me, though!

@Steve Glad I could help. Umm for the datasheet, it says on page eight, table two, that one pin does forward, the other one backward, and both is to brake. If no power is applied to either pin, it'll be free to rotate randomly.

The FA130 type electric motors in the Tamiya Double Gearbox Kit (No. 70168) are 1.5v-3v DC motors with current ratings of 0.20A (no load), 0.66A (@ max. efficiency) and 2.2A (stall), see 1.5-3V DC Motor 6990 RPM. They are not high current motors.

Hi Andre, and welcome to Arduino:SE.  'High current' is very much a relative term.  That stall current of 2.2A may be too much for a 2A line on a motor shield.

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


text:
What's the difference between different Ethernet Shields?
I am working on a project with Arduino and I need an Ethernet shield. but after searching in some electronics shops I found there isn't only one but a lot. I don't know which one is better and what are the differences.
Arduino Ethernet with PoE module
Ethernet Pro
Ethernet Shield for Arduino - W5200
Arduino Ethernet Rev3 Without PoE Module
Ethernet Shield W5100 For Arduino
in DFRobot Online Shop.

What one that is the best is highly subjective.
Though my personal experience is that arduinos original is the one with the best support. Where you can find alot of documentation about the other ones, you might need to do some legwork updating the code to the latest version of the arduino ide or use an older ide.
Be aware that some Arduinos has integrated ethernet, and others are SHIELDS, you recognize the arduinos with ethernet by the power-connector, and the shields by the distinct name containing "Shield", though shields require an arduino to work. The arduino with integrated ethernet does not.
Also be aware that not all shields fits arduinos boxes if you want to encase it. And of cause, buying arduinos original products, cost a bit more - but you support the arduino foundation, and further development of the products.

Clearly the 'best' one is the one that meets your requirements (or is the most expensive - that's always the best, right?).
You say you need an ethernet shield - can you explain why? Without that information, it's almost impossible to tell you which is the most suitable.
If you are looking at IoT applications, it may be that an Ethernet shield isn't the 'best' thing for you. If you just want access to the local IP network, you could use any of those. If you want the 'best' library of functions to support your application, that may affect which module you use.
For me, I think the best module is the cheapest one that gives me connectivity: http://www.aliexpress.com/item/Hot-Sale-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-51-AVR-STM32-LPC/32254842414.html
The W5100 is also a good choice, but only if it is under $7


text:
How to store/get MIDI SystemExclusive data?
In the MIDI library from the Arduino (FourtySeven MIDI library), there exist a function to get the length and bytes of a System Exclusive message:
Functions
getSysExArray()
template<class SerialPort , class Settings >
const byte * MidiInterface< SerialPort, Settings >::getSysExArray

getSysExArrayLength to get the array's length in bytes.

However, since the Arduino Mega (in my case) has only 8 KB of memory, how can I get a MIDI SysExclusive message which is longer?
Also, I even have added a 128 KB SRAM (23LC1024), but that doesn't help me if I cannot store it in pieces.
Ignacio Vazquez-Abrams mentioned I should 'read' the message, however what message do I get if the system exclusive message is too large to be stored in (internal) SRAM? The read message (see here also does not have a partial read.
Update:
After a test with a large message, it seems the message is not received by the Arduino MIDI library.

That's why you have to do it on the fly instead of relying on a function for it.

And how do I do it 'on the fly' ... can I get to the raw data anyhow?

You read the message.

@IgnacioVazquez-Abrams I should rephrase my question, thanks

If you really, really want to do this, you'll need to rework the library internals to make use of your external memory, or else extract what you actually care about on the fly.  Realistically you have chosen the wrong board for this task.  You should look into using something with ample directly mapped memory instead, if you anticipate wanting to deal with very large messages.   Possibly a large Cortex-M part (maybe a high end Teensy?) or perhaps a small embedded Linux board with megabytes of dynamic RAM.

Well I can (for now) live without support of large sysex messages ... my project will already going to contain one STM32/F7 in the future for one device, maybe for the MIDI device I will also move towards a STM32. Probably system exclusive message will not even be received (but I will test it).
I want to stay away from Linux (not that I don't like it), but I also need quite fast latency which Unix might not be able to provide.

That may depend on what exactly you mean by fast latency and how far into the kernel you can push the critical parts.  Though a very good architecture can be to have a small MCU that does simple fast tasks and is supervised by a larger "embedded computer" which does more data intensive communication ones.

I need to some simple actions on a MIDI message (not system exclusive messages, on a Arduino Mega, for now), send it by RF (probably 2.4 GHz, max 10/20 meters) to a STM32 which will further process it, send it back (by RF) and sent by MIDI Out. All within 20 ms, my idea is to have a loop that can handle several messages in 5 ms by the Arduino Mega.

Do realize that anything coming over midi streams in byte by byte over the serial link - if you have logic to find the start and end of regions of interest, you can start writing that out to memory as received, and then return to ignoring what you don't care about.  It's also at a slow enough rate to do some processing as the data arrives, and should not be a problem for an embedded operating system as long as you use a real serial port and not one tunneled over a laggy USB connection.

Let us continue this discussion in chat.

For minimum latency try to avoid sending the data on a round trip over RF.  Instead, use commands sent via RF to alter an algorithm which processes it locally.   That said, you can just stream the serial data over the RF link, process it there, and send it back.  Midi data rates are pretty slow compared to what 2.4 GHz digital radio modules support.  It's only if you need to allow retries or have a bad packetization algorithm that you hit latency problems.

I hope I can prevent retries/wrong packets, since the distance is around 10-20 meters max, maybe for the MIDI device even much less (< 1 m). For future devices distances might be more. I thought about locally processing it, but that would much more complicate what I want. So I want to optimize it only when needed. I did some calculations and I think I can handle a lot of messages within reasonable time getting the latency.

This library tries to make its programming interface as simple as possible, which means that SysEx messages are put completely into a buffer in the internal memory, which means that larger messages cannot be handled.
The only way to handle larger messages is to read the bytes directly from the serial port, and parse the MIDI messages yourself. (The MIDI specification has a helpful flowchart about MIDI parsing in the first appendix.) When you have detected the start of your large SysEx, you can then do whatever you want with the following bytes, e.g., handling them as a stream, or write them to external RAM)^.

Thanks for your answer ... I'm sure I will be able to read it directly without the library, and possibly I will go that way later. But not to continuously change my 'design', I continue for now with the MIDI library and using your way (reading directly from Serial) later.
But very good to know it can be done that way fairly easily. It would even reduce the latency further if I can start handling bytes already without having to wait for the entire message, especially for critical latency messages (mostly non system exclusive messages).


text:
Differences between a real and clone Arduino uno?
Today I got my clone Arduino and connected it to my real Arduino and they both work. (UPDATE: The Arduino noted as real Arduino probably also is not a real Arduino; however both work fine).
However, I see some differences and wonder if these are good or bad:

My questions
1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.
2) At number 2 are 4 holes without any explanation. What is the function?
3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.
4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

Might need to check if your original arduino uno is not a counterfeit; https://www.arduino.cc/en/products/counterfeit

@MikaelPatel Probably the other one is not original either, since the text 'designed in Italy' is shown instead of 'made in italy'. But they both work :-)

What is the number on the main chip on the black one?

@Majenko first line: Delta-symbol (triangle) ATMEL, 2nd line: MEGA328P and 3th line: AU 1646

Ah right. I was wondering if it was one of the new B ones with the second UART. Shame.

By the way, the blue the blue one is counterfeit. The silk is wrong for a real one.

For 3 euro I expected something that might not even work :-)

@Majenko: what means 'silk' in this context?

Silk Screen. The white lettering and drawing on the board. The big giveaway is that they used a serif font for the URL. Serif fonts are common on Chinese boards. Arduino, and most "western" designers use a sans-serif font.

ok :-) since I probably will order mostly from Aliexpress, if there will be more Arduino's they might be clones too.

to me it just looks like your new one is an R3, nothing special.

I'm happy with the new R3 (it's my second Arduino anyway).

The best help is the schematics for the clone.

1) At number 1 there is on the clone arduino a 12 MHz oscillator? What does it do? And since there is also the regular 16 MHz oscillator I wonder why there are two.

Lower left on the schematics is the 12 MHz crystal. It is for the CH340G (USB-UART chip).

2) At number 2 are 4 holes without any explanation. What is the function?

Lower middle is the pins X1. They are extra signals from the USB-UART chip (CTS, DSR, R and DCD).

3) At 3 there are 12 holes (sorry that only 9 are visible, under the blue/black cable are 4 more holes with silver square around them.

Upper right on the schematics are the extra pins. This might be handy.

4) At 4 there is a SCL and SDA which are used for SPI I think, but these are not on the original Arduino. But the original Arduino has 6 pins at the same location and 4 holes (where 2 of them are marked as JP2).

The original has an extra ISP pins (ICSP1) for the ATmega16U2. See the schematics. The clone has the new layout I2C signals extending beyond pin 13.

Thank you very much (just for my curiosity), how did you find the schematics? I don't see any clear ID.
Guess it's not bad at all (and it was less than 3 euros).

Web-search "arduino uno ch340 schematics" :) It all about the "magical" index word. In this case the USB-UART ch340 chip.

I didn't know the USB/UART chip would be that important to find the schematics

The trick when constructing a web-search query is to consider the unique and distinguishing attribute, in this case the CH340G chip. This helps the search engine reduce the search space. Using for instance the 12 MHz crystal is not as distinguished as the Arduino itself could use that.

Thanks ... I am new to electronics so I was not aware that the CH340G was the 'unique'  factor. But it will help me in future to find datasheets/schematics as well to know such information.


text:
TinyGPS (Plus) Library
Is there a particular function in the library TinyGPS or TinyGPS Plus which outputs the raw NMEA sentences? I couldn't find anything about it on the website guide of the library.

There doesn't seem to be, but what you could do is print each character as it arrives. From their example code:
  while (nss.available())
  {
    if (gps.encode(nss.read()))    // <--- pass to TinyGPS
      return true;
  }

So, change that to be:
  while (nss.available())
  {
    char c = nss.read();  // <--- get the incoming character
    Serial.print (c);     // <--- print it
    if (gps.encode(c))    // <--- now pass it to TinyGPS
      return true;
  }


text:
Arduino + 4051 -> noise on certain 4051 pins

I am trying to use two 4051 ICs with an Arduino Micro right now. The idea was to have an 16-sensor demo station (8 sensors per 4051) wherein each 4051 pin selection is controlled by a potentiometer as input. I am new to using MUX's, so I mocked the following up as a quick demo based on this help document via Arduino (it's basically the same), which only uses one 4051 and does not use a potentiometer as selector input. So, I should be able to set the variable which to whatever number (0 - 7) to change the sensor selection that shows up at A2 on the Arduino.
Setting which to 0 is fine, but when I have more than two sensors plugged into 4051 and set the selector pin to any other number than 0 there is a strong likelihood that the output that shows up in the Serial Monitor is both unresponsive to the selected sensor change and appears to be simply noise (random numbers around 200 or so). I have been trying to isolate where this noise is coming from and am totally stumped. Has anyone had this issue and, if so, any suggestions on how to further diagnose what is happening? I am currently powering everything off of the Arduino 5V, which I am under the impression should be okay, though I have tried this with external power supplies (12V at 2A, for example) and gotten the same results (so I am fairly certain power is not the issue here).
Measuring voltage on pins 2, 3, and 4, I am seeing 1mV on pin 2, 1mV on pin 3, and 0.9mV on pin 4 following the initial spike during upload. When comparing against the Arduino 4051 doc I linked to above, I see that in that file pins 2, 3, and 4 show a Voltage of 2.5V following the initial spike during upload. Any idea what I am doing incorrectly?
/*
Sensor Station via MUX

 * code example for useing a 4051 * analog multiplexer / demultiplexer
 * by david c. and tomek n.* for k3 / malmï¿½ hï¿½gskola
 *
 * edited by Ross R.
 */

int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}

void loop () {

  which = (0);

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);
}

In the linked code, the for loop repeatedly cycles count from 0 to 7, so Ard. pins 2-3-4 will average 2.5 V.  In your code, they should sit close to 0 V.  What do you have 4051 pin 6, INH, set at?  What is another value of which that you tried, and what was connected to the corresponding 4051 input pin?   Try connecting all of the 4051 input pins (NO0-NO7, pins 13, 1, 15, 2, 14, 5, 12, 4) together and to the sensor or a pot and see if you get the same reading on all 8 channels.

You don't have a Serial.begin() call there so I'm a little surprised you see anything in the serial monitor.

I have a post about that chip at 74HC4051 multiplexer / demultiplexer.
I made up the circuit shown on my page above with modifications as described below:

I moved the A/B/C and O/I pins to match your code.
A is the low-order bit so pin 11 on the 74HC4051 should go to D2 on the Arduino.
74HC4051  Arduino   Meaning
    11       D2        A
    10       D3        B
     9       D4        C
     3       A2        O/I

I put a pot on I/O0 (pin 13 on the 74HC4051) and randomly set the other pins to +5 V or Gnd, as shown.

In setup() I added:
Serial.begin (115200);

I also modified it to automatically sequence through all 8 possible ports, and then stop after 1000 iterations to stop flooding the USB port on my computer. Code is:
int r0 = 0;      //value of select pin at the 4051 (s0)
int r1 = 0;      //value of select pin at the 4051 (s1)
int r2 = 0;      //value of select pin at the 4051 (s2)
int which = 0;   //which y pin we are selecting
int val;

void setup() {
  Serial.begin (115200);
  pinMode(A2, INPUT);       // mux1 input
  pinMode(2, OUTPUT);    // s0
  pinMode(3, OUTPUT);    // s1
  pinMode(4, OUTPUT);    // s2
}  // end of setup

unsigned long counter;

void loop () {

  // select the bit
  r0 = bitRead(which, 0);
  r1 = bitRead(which, 1);
  r2 = bitRead(which, 2);    // use this with arduino 0013 (and newer     versions)

  digitalWrite(2, r0);
  digitalWrite(3, r1);
  digitalWrite(4, r2);

  //Either read or write the multiplexed pin here
  // refactor, this should be digitalWrite with millis or something
  val = analogRead(A2);     // MUX ouputs here

  Serial.print("sensor number ");
  Serial.print(which);
  Serial.print('\t');
  Serial.print("val is ");
  Serial.println(val);

  delay(2);

  if (++which > 7)
    which = 0;

  if (++counter >= 1000)
    {
    Serial.flush ();
    exit (1);
    }
}  // end of loop

The output from your sketch was as expected:
sensor number 0 val is 781
sensor number 1 val is 0
sensor number 2 val is 1023
sensor number 3 val is 1023
sensor number 4 val is 0
sensor number 5 val is 0
sensor number 6 val is 0
sensor number 7 val is 1023

I suggest you check that your wiring agrees with mine.

Re “I moved the A/B/C and O/I pins to match your code”, your diagram connects 4051 A,B,C to Ard 6,5,4 instead of to Ard 2,3,4.  Also, the code shown in the question doesn't have a loop, so it might be good to include your code in your answer

@nick, Thanks for your input on this. The omission of Serial.begin was an oversight on my part but has been added. Your answer resolved my issue: I had the digital pins connected in the wrong order. Thanks!

@jwpat7 - I have modified the post to include my test code. your diagram connects 4051 A,B,C to Ard 6,5,4 instead of to Ard 2,3,4 - true, that was one of my stock schematics. I noted underneath which changes had been made. The code on my linked page matches the schematic. I wanted to use the OP's exact code (as far as possible) in case there were subtle problems with those pins.

@jwpat7: To make my answer more useful, I redrew the schematic to match the code on this page, to avoid confusion.

@NickGammon, +1


text:
How do pins on an arduino mega 2560 work?
I got a copy of Arduino from a local retailer here (it's a local copy and I'm pretty confused with how the pins actually work).
I know basic electronics so far, there should be two pins for every node one acting as the negative terminal and other as the positive terminal. If I were to connect an LED with my Arduino board which pins would I be utilizing?
Here let me tell you how pins are arranged on mine:
IOREF                                                                         GND

                                         13
RESET                                                                         12
3.3V     //this left group marked power                                        .
5V                                  //right group marked PWM                   2
GND            //right groupmarked communication                          TX0 -1
GND                                                                       RX0- 0

V1N                                                                       TX3-14
                                                                         RX2 -15
A0                                                                         ..
A1                                                                      SCL -21
..   //THIS left GROUP MARKED ANALOG IN
A7

A8
A9 //I believe it is part of the above group
..
A14
A15

     //the pins below marked DIGITAL
     52-50-`48-46...........................................................22`

there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a common "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked GND on the board.

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.
You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

PWM: Pulse-width-modulated output
COMMUNICATION: Serial input/output (4 serial ports)
ANALOG IN: Analog-to-digital converter (ADC) input
DIGITAL: Digital (not analog) input/output
SDA/SCL: I2C communications
Pins 50-53: SPI communications (not marked on the board)

However all pins, as you noted, can - if you wish - be used for digital input or output.

Great. Thank you. Btw can you tell me why there are two pins on the bottom horizontal row? I mean the grounds on left and right are singled pin but on the horizontal row they are double pinned?
Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins? If yes, what? If not, why are they categorized as PWM, COMMUNICATION,ANALOGI IN,and DIGITAL?

This is another example of a lengthy answer, which doesn't get a single upvote, nor an accepted answer vote. So it is recycled by "Community" as unanswered. IMHO it was answered.

One good turn deserves another.

Any IO pin can be set to either be an input, where it reports to your program if the voltage present on that pin (relative to ground) is above or below a certain threshold (HIGH or LOW voltage), or it can be an output, where it can either be set to be a HIGH output (pin is connected internally to +5V) or a LOW output (pin is connected internally to GND).
To drive an LED you would connect one side of a small resistor (say 470Ω) to any IO pin you choose.  The other side of the resistor would connect to the anode of the LED.  The cathode of the LED would then connect to ground.  When you set the IO pin to HIGH it will provide 5V to the LED through the resistor (which is needed to limit the current as the LED is a non-linear, current driven, component) and the circuit is completed by the return path through ground.

Note that you must not exceed 40mA going into or out of any IO pin, and you should not exceed 25mA going into or out of any IO pin.  The total current going into or out of all IO pins must not exceed 200mA.

Understood. Thanks, for the part where you said a resistor must be used with an LED can you tell me which formula do you use to calculate the required resistance?
I=V/R
R=V/I
R=RequiredVoltage/RequiredCurrent Is this it?

I'm upvoting this answer to stop this question staying as unanswered. Even though I posted my own answer. :)

@NickGammon I have noticed the Arduino community is much less inclined to upvote or accept answers than other communities. Just looking at the question list you see much lower numbers in general here than in for example the Photography community.

I've noticed that too. My fairly minor contributions to other SE sites (eg. English) get quite a few votes, even for a short post, but a lengthy one here, complete with schematics, photos, code, etc. can get completely ignored. It is a little off-putting.

"The total current going into or out of all IO pins must not exceed 200mA."  For a '2560, the total is actually 800mA.  200mA per VCC/Gnd pin, the Mega has 4 of each. This was confirmed with Atmel tech support some number of years ago and posted at Arduino.cc


text:
Xbee for Arduino Uno
I'm very new to Arduino, and I was wanting to control my Arduino wirelessly. Some googling shows that there is a shield for Arduino called Xbee that allows wireless communication. Unfortunately, I just purchased the #1 shield without checking specifications, (went back later, couldn't find them :/) and now i have a shield that appears to small for my Uno. (XBee Pro 60mW Wire Antenna - Series 1 (802.15.4))
Some more googling showed results that this was indeed the right shield, but I don't see how since the pin pattern is about half the size as the female ports on the Arduino. Is this the right shield? if so, how do I attach the two pieces of hardware?

What you have there is an XBee module. It is designed to plug into an XBee shield which then plugs into the Arduino.
So you need to buy more.
That's the bad news.  The good news is that you have already bought the most expensive part, and the shield to go with it is pretty cheap.
Numerous people make the shields, such as:

Sparkfun
Seeed
DFRobot

Also note that XBees talk to other XBees, so you need at least two of them to get any form of communication going.  If you want to talk to your computer there is a device called the XBee Explorer which plugs into the PC to allow you to communicate with an XBee module.

So, would i need a new Xbee module for the computers side of communication?

Yep. You need two of the same modules to talk to each other.

great... this is expensive. :P thanks so much for your help


text:
How to upgrade Arduino UnoR3 clock
A little background:
I need to generate a 40KHz frequency as accurately as possible.
(One of my other posts is here:
Stable frequency generation)
My code is solid- I'm using an Uno R3 and generating the most accurate frequency I can at this point. The only way to get a more accurate frequency is to upgrade the ceramic resonator to a crystal oscillator.
So, my over-arching question is: How do I actually upgrade the ceramic resonator to a crystal oscillator?
Things I'm considering are:
Is it worth it to actually upgrade my Uno R3 - and is it even possible? Is there a clone that drives the ATMega328p with a crystal oscillator that I could use instead? Is there simply just a better model for this application?

It's really easy to take an ATmega328 chip and wire it up on it's own.  There are even instructions on the Arduino site on how to do it.  Take a look at http://www.arduino.cc/en/Main/Standalone .
You could even pull the 328 out of the Uno, add the crystal and a few caps and then program it with the Uno board.  I've done this a few times myself and it worked just fine for my needs.

I was trying to avoid using a bare chip as I'm using a 12v supply to power the Uno and utilizing the onboard 5v for some other circuitry.

A 7805 voltage regulator would be easy to add to that circuit to give you a nice 5v to power the atmega and any other circuitry you have. They are relatively cheap and plentiful as well.

Looking at the Arduino R3 reference design, it should have a crystal! But in practice it seems that the manufacturers are cutting corners and using a resonator because it is cheaper. I don't like your chances of fitting an xtal instead of a resonator. Unless you are a soldering expert and have suitable facilities, the most likely outcome is a dead board.
If your board has the MCU chip in a socket, you could bend the xtal pins so they don't go into the socket and solder a xtal and a couple capacitors to them. Not exactly a production line solution, but it will be fine if you just want a one-off - and anyone reasonably at home with a soldering iron could do it.
Freetronics (an Australian company) make a R3 compatable with xtals for both processors. These are very well made (I own two), and have a prototyping area as well. Downside is the higher cost. See http://www.freetronics.com.au/products/eleven#.VT3F-PCo1BA

The eleven may have its LEDs on the edge (where they belong), but the reset button is still in the middle of the board, which is not R3 compatible, and won't be reachable with a shield on top. Besides, two identical crystals this close together is kinda stupid. They could have done with one crystal and use a buffer to bring the clock to the other microcontroller. And yes, AUD 40 is expensive.

@JorisGroosman The site I pointed to is AUD 29.00 - a bit less but still quite expensive (and they are out of stock)

@kiwiron I do like the idea of slightly bending the pins as a one off solution... Although the Eleven would work perfectly if I could find one. Without trying to get off topic from my original question, can I run my code on a Freeduino? (I would be able to solder a crystal into the kit).


text:
Which type of sensor should i use to get RPM of an engine?
Using Arduino (i got leonardo and uno),
I'm looking for a way to get the RPM of my car's engine.
I know this can be done using an OBD2 connection however i'm looking for a different way.
Sensing?
I need a reference for a sensor / a creative way to get this data.
Having said that, these approaches came up:

guessing the RPM by reading the amps in the car's 12V connection
recording the sound of the engine using a microphone and setting thresholds for certain RPM values

If you wrap a few loops of wire around one ignition wire you can probably messure the ignition pulses. But that could kill your arduino, because even the induced voltage in the wrapped wire may be over 1000 Volts. So be carefull!!! Perhaps a diode (Fast Schottky) might help. But that's a question for the electronics site http://electronics.stackexchange.com/. These guys know more about that than I do.

I think it will depend on whether you have access to the tachometer feed (assuming one is available).  Otherwise, if there is something "rotating" at the engine speed, you can attach various types of sensor for measuring revolutions (eg. IR reflection or hall effect magnet sensing).

Paint a white of black spot on the drivebelt, and use an reflective optical sensor (e.g. tcrt5000) to see how many times the spot passes the sensor.

Could you state the reasons why OBD2 is not an option?

I would think something like this would benefit you greatly. If your vehicle was produced after 1996 it will have an OBD port near the steering wheel that allows you to read diagnostic information from the car. This diagnostic information always includes error codes (think: Check engine light), and often includes operating information like speed and engine rpm.

I'm doing this with a TCRT5000 and a LED+phototransistor, you can find them all over Amazon and eBay. I painted one quarter of a camshaft pulley white, and the other three-quarters flat black, and mounted the optical sensor over the edge of the pulley. This is on a Subaru, where the cam pulley and timing belt are all underneath a shroud, which keeps out ambient light. It works quite well.
Plus a .1uf capacitor next to the Arduino, because the transitions between high and low were pretty noisy without it.

What about measuring the speedometer? I suspect that would be easiest - you may get away with hooking up the speedo directly to the Arduino analog (but measure with multimeter first!).

The question seeks engine RPM, not speed.  Transmissions have various ratios, and they slip, so the two are not directly related.

Most speedos have RPMs. I meant "the rpm line on the dashboard" (that part of the dashboard being referred to as the speedo, even the parts that aren't).


text:
Unable to reset arduino with RESET pin
I am using a custom built arduino UNO for some personal projects. I am using a custom optiboot bootloader given by Nick in this post. This was done to prevent the three LED flashes on digital pin 13.
I have noticed a weird thing with the setup. During normal operation, I am able to reset it by pulling the reset pin low. Sometimes, my microcontroller freezes due to noise and I am unable to reset it by pulling the reset pin low. However powering it off and back on still works.
I am wondering what could be a possible cause for this. Is it the custom bootloader or whether power on reset is different as compared to normal reset? Is there a way to ensure atmega328 always resetting through reset pin? Can noise affect the chip and make it behave in such a way?
After some google searches, I found an issue where people disable the reset pin functionality by setting a fuse but this doesn't seem to be that case because I am able to reset the chip during normal operations.
Updates and edits:
@Nick - Bootloader seems to be working fine. I have ruled out any issues due to the bootloader that you provided because I am having similar issues with original ones as well.
Custom arduino has all the necessary circuit elements - including reset pin pullup 10K resistor and 1N4148 protection diode. I am able to program and run the code without any trouble.
Sometimes, due to electromagnetic noise, the atmega locks up. GPIO doesn't work. Here is a separate question explaining this.
During tests, I leave the board running and wait for that hang-up to occur. During this time period, I deliberately try to induce noise in ac lines (by switching on/off appliances, turning the fan regulator knob etc). When it hangs up, I try to reset it by pulling the reset pin low using a wire. Sometimes it resets and sometimes it doesn't. When it doesn't, the only way out is to power it down and power it up back again.

Could you please clarify what you mean by freezing due to noise? Is it possible that this noise upsets more than your code (i.e. causes a brown-out condition that isn't checked for, corrupting the DDRB register or more)?

@sekdiy Brown-out levels have been raised to 2.7V and mcu is getting brownout reset on separate test and everything starts working as expected. I am not sure about DDRB register corruption. Can that thing disable RESET pin from functioning? And will a power cycle set the things straight?

Can you clarify if the bootloading isn't working, or if this affects the sketch running? That is, after you upload the sketch (say in the morning) and later in the day you have trouble resetting the board?

On your custom Uno (so it isn't really a Uno, eh?) do you have a pull-up resistor on /RESET? Also do you have a diode on /RESET?

@NickGammon - I updated the question to answer your questions.

@Whiskeyjack AFAIK the pin is not software driven.. Usually on other uC (e.g. PIC) you can set the reset pin function to off using the fuses. Are the fuses the same as the UNO ones? Moreover if you have these random freezes I suggest you to use the integrated watchdog, so you won't have to manually reset it

@frarugi87 - I tried internal WDT and it failed to reset during those freezes. As a last resort I was using another ESP module present on the same esp to keep checking whether arduino is alive or not and reset it whenever it freezes. In some cases it works but in others it doesn't because grounding the reset pin isn't helping anymore. I thought nothing will be as robust as resetting it externally using reset pin but now, only power cycle seems to be 100% reliable. Implementing power cycle is a difficult option.

@Whiskeyjack sorry, but.. Where does the ESP come from? You never mentioned it...

Weird problem. Why don't you use the reset-button, by the way? I've had wires in the headers not properly making contact in the past. But why don't try to fix the source of the problem; i.e. the power source. Try using a different AC-power adapter.

@frarugi87 - Sorry, I didn't mention it because I felt it shouldn't affect the scenario. The issue is simple - I am pulling reset pin LOW but I am not able to reset the atmega328p.

@gerben - I tried it with another power supply. Faced the same issue.

A possible thing is that a high voltage on /RESET is putting it into high-voltage programming mode, however the diode I mentioned, and that you say you are using, should prevent that. Perhaps if you posted the schematic for your custom design.


text:
Cannot compile C++11 code via Makefile
I am building my Arduino project with a makefile:
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyACM0
USER_LIB_PATH = /home/prakhar/dev/alfred/arduino/libraries
CPPFLAGS=-x c++ -std=c++11 -Wall -DUNIX_ENVIRONMENT -DHAVE_NAMESPACES -DHAVE_STD
include /usr/share/arduino/Arduino.mk

I keep getting this error:
cc1plus: error: unrecognized command line option "-std=c++11"

I googled and this says that I need to update g++/gcc. I already have the newset versions:
prakhar@sim74stic ~ $ avr-g++ --version
avr-g++ (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ avr-gcc --version
avr-gcc (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ g++ --version
g++ (GCC) 4.9.1 20140903 (prerelease)
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I installed arduino from the AUR (packages aur/arduino 1:1.0.6-1 and aur/arduino-mk 1.3.4-2).
Can anybody point out what I'm doing wrong?

Check out the first few comments here: https://aur.archlinux.org/packages/arduino/  It may help.

Thanks for pointing me in the right direction. I C++11 to work.

As I turns out, the avr-gcc (GCC) 4.9.1 goodies weren't being used at all! The arduino package was using a decrepit version of gcc,
prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ --version
avr-g++ (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-gcc --version
avr-gcc (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

All I had to do was specify:
AVR_TOOLS_DIR = /usr

to exexute with -std=c++11 flag (I also had to add an -fpermissive flag to compile C with g++).


text:
Moving an object in an area
I am planning to build a little game and I would need to move a small magnet inside a rectangular area. Ideally I would be able to control movement arbitrarily e.g. using a joystick.
I am trying to find a way of doing this, something like an actuator, I guess, but allowing movement in 2D.
Any suggestions on which parts to use?
Edit : in brief, what I'm trying to do is this. I have a piece of plywood, underneath which I want to put a magnet. The magnet will be moveable using a joystick (everything controlled through an Arduino) and will be used to move a magnetised figurine on the other side of the plywood. I guess in term of precision of movement I am not looking for extreme precision, having something accurate to 2-3mm would be absolutely fine. Haven't really thought of speed... But not looking for extreme high speeds.

Two linear axes perpendicular to each other, made of pulleys (like most 3D printers) or of nuts on threaded rods. Or two rotational axes on top of each other, like a SCARA robot. Your question is really broad. You didn't explain enough, what you are trying to achieve. We don't know nothing about your requirements. And maybe this is better fit for the robotics SE site, since your question is not about Arduino.

Hi @chrisl, thank you for your comment. What type of details would help?

First an overview, what you are trying to achieve here. I'm sure moving a magnet is not all to the story. Then you need to think about how fast and precise the magnet should move. When using linear axes, pulleys are much faster, threaded rods are more precise. And I assume there is something important lying in the fact, that you try to move a magnet. Do you want to move it with another magnet from under a table? These information are important for designing a fitting solution.

Totally unrelated to the question, This question is #20,000 question in Arduino SE.

@chrisl thank you. I added a few more details. Anyways your suggestions are already a great start, I guess you could convert that to an answer?

@ElectronSurf, it is not. many questions are deleted and this will be deleted too after a month or so

@nico, I'm looking at this history of this question.  Keep in mind all stack exchange sites (not just Arduino) are best used 1 question at a time.  And often it is best to try something first then come here and ask question if that attempt did not work out.  If you need to discuss an Arduino project and get some direction it may be better to try forum.arduino.cc.  Look at this specific thread and search or others that are similar.  Then come back here with specific questions after trying something.

@st2000 I know, I've been using StackExchange for a very long time. You are right, I should have specified what I did try, but since I could not really find a proper way of looking for this I was just looking for some inspiration. Probably arduino forum would have been a better fit, anyway I got enough ideas from the answer and hopefully someone else facing a similar problem will benefit from this as well.

Well put.  I would search for project involving moving chess pieces with electromagnets like this one: https://magpi.raspberrypi.org/articles/ghost-chess-electromagnets-move-pieces

First you need to think about your axes configuration, then about the actual implementation. I for example can directly think of 2 options:

You could arrange your axes perpendicular to each other, like a Cartesian coordinate system. Here you might need more parts to build it, than with other arrangements, though it is a sturdy system and the positions and paths are easily to calculate. For implementation there are 2 common ways, both using stepper motors in most cases:

You could let the magnet travel on the 2 perpendicular axes pulled by a belt and stepper motor for each axis. As you have to mount one axes onto the other, you might need to use 2 stepper motors (one for each side) for the first axis (depending on your dimensions, how smooth the axes glide and how much force is introduced by dragging the figurine). This approach is mostly used by 3D Printers, since they need rather fast movement, which is also rather precise, but don't need to accommodate high forces.
Instead of belts and pulleys you could use threaded rods for each axis. The magnet is mounted on nuts on these rods. Rotating the rots will move the magnet over the axis, since the magnet is fixed in it's orientation. The precision is highly dependent on the used rods, but all in all it is often more precise, than belts. But it is also way slower.

You could use only rotational axes, like a SCARA robot. It has a rod on a rotational axis and another axis at the end of it. This approach might use less parts, than the Cartesian approach, but you need good servos to have precise and jitter-free positioning (though you could also go for a geared stepper motor here). Also the arm of the robot can look out under the field quite a bit, when positioning it to the far one side.

All of the above approaches can be way more precise, than you need it. They are all viable options.
I personally would go the first way, Cartesian axes with belts and pulleys. The principle is straight forward and you can easily hide it under your piece of plywood (including a margin for all the mechanical stuff of course).

Thanks for the answer! Extremely helpful and gave me some good directions to look at

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


text:
Unable to load sketch: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41
I've stumbled upon what I've later found it's quite common error, but there seems not to be simple troubleshooting way and solution (people often try various things, sometimes they succeed, sometimes not).
I am using DAGU mini driver, I was able to load sketch as described here - chose Arduino NG ATMega8 as board, connect to my PC via USB (with the driver listed on the product page).
Later on I've plugged RedBot wheel encoders sensor and write some simplistic program to check whether it works at all. I've summarized the steps in a github issue, so that it's easy to reference it.
When I tried to upload the sketch I've receiced stk500_initialize(): (a) protocol error, expect=0x14, resp=0x42, stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41. The full log is included in comment on that github issue.
The D13 diode is making series of 3-blink bursts - 8 bursts after start. More diagnostic I did in the github issue as well.
My question (apart from obvious 'how to fix it!?!' ;) ) is whether there is some kind of documentation for this protocol? On the various topics I've found people seem to have somewhat different problems (the numbers and messages were different). I just want to know why the first few messages are exchanged OK (avrdude receives some basic info from the chip), but later ones (namely Send: A [41] . [81]   [20]) are producing protocol errors.

Ordered programmer, will see if it's just corrupted bootloader

AVR programmer helped.
Meaning the bootloader somewhat got corrupted and I had to burn new one.


text:
Arduino and Raspberry Pi - 5V/3.3V I2C
This topic have been covered in various places, but I still think it hasn't been thoroughly explained anywhere. Doing google search on connecting Arduino to Raspberry Pi via i2c gives for example, this page.
While apparently this should work, there is a factual error there: on arduino side, pins used for i2c do have internal pull ups, and they are activated by Wire library.
Digging further, I've found following information:

However, it turns out that these are weak (high-resistance) pull-ups;
  the Pi has strong pull-ups which dominate those on the Arduino, making
  direct connection safe.

What does safe mean? And how weaker are those pullups compared to raspberry pi ones?
Let's check:

rpi i2c pullup: 1K8
arduino i2c pullup: 20K-50K from datasheet (if I'm looking correctly, I'm using ATmega8), though the above page states 10K.

What can I make of those values? My (intuition rather than) basic knowledge hints me something along the lines:
If the i2c is floating, it means the 5V is connected with 3.3V and there are only those pullups along the way, so:

calculate voltage drop between 5 and 3.3: 1.7V.
calculate voltage drop across rpi pullup proportionally to voltage drop across arduino pullup:
1800 / 30000 = 0.06, meaning 0.102V across rpi pullup and 1.598 across arduino pullup, so the actual pulled up voltage is gonna be 3.3V + 0.102V = 5V - 1.598V = 3.402V?

Though I'm pretty sure I'm doing some terrible math here and someone is gonna have good laugh:)
So, my question is not whether it's safe (as it's been proved), but rather why is it safe considering the internet resources are inaccurate on this matter.

And your question is? I have done this and it works. 2. What makes you think the Arduino pullups are enabled? Even if they were, I²C would not work reliably. 3. I haven't checked your calculation, but even if you put 3.402V it wouldn't matter. It only becomes an issue if the voltage exceeds a diode voltage drop.

Well, my question is to find out why is it safe, cause it's been tested and proven, yet always backed by some erroneous/informal claims.
The pullups are enabled, check 'twi_init' helper function in Wire library source.

You math seems correct. Try calculation the amount of current. It will be in the micro-amps. Combined with the low voltage, you get a few micro-watt in power. Not enough to do any kind of damage. I think that is how they came to the conclusion it's safe.

If you are sure to disable pull up on arduino side you are safe, as i2c works in open-drain mode, but the logic level "high" of arduino is about 3.2v, so it would be unstable.
Otherwise i2c pin of rasp are NOT 5v tolerant, so you must be sure the voltage on the bus does not exceed operative limit; as you calculated ~3.5v should be good on raspi, but please check on datasheet.
Also, you should check the total current on the bus, but as atmega resistor as so high,it should not pose a problem with raspi (but may give problem with passive i2c, that you can solve with a external pull up)

But I have no idea whether I calculated it correctly...


text:
TLE9879 BLDC shield won't communicate
I just got the TLE9879 BLDC shield, which I connected to an Arduino Leonardo. Compiling the example sketch (bldc_shield_blinky_test) went fine, however, upon flashing it to the board the LED on the shield doesn't change the color (it stays white) and the following line is repeatedly printed to the Serial console:

WARNING: Board[1]; Command[901]; Answer[0]

I have initially tried the shield in its out of the box state. I have since then flashed it with the HALL version of the shield software, using the project included in the SW distribution that comes with the shield. In both cases, the shield behaved as described above when connected to the Arduino.
Does anybody know what this warning message is about?

@jsotola It behaved exactly the same before and after flashing. I assume it came pre-flashed.

what happens if you run the sketch without the BLDC shield connected to the arduino?

I never use TLE9879, but I could guess of why it doesn't work as expected.
For ATMega328p-based Arduino boards (i.e. Uno, Nano and Pro Mini), it has pin 11, 12 and 13 as SPI’s MOSI, MISO and SCLK signals, but at the same time these signals are also available on those board’s In-Circuit Serial Programming (ICSP) header pin 4, 1 and 3, except for Pro Mini which does not have a dedicated ICSP header.
This however is not the case for Arduino Leonardo and Arduino Micro which are based on ATMega32U4, for those boards, the SPI is only available on ICSP header. This is one of the reasons that some of the Arduino shields designed for Arduino Uno does not work with Arduino Leonardo when SPI communication is involved.
Based on the information of TLE9879, the SPI port is connected to pin 11-13 so it is designed to work with Arduino Uno but will not work for Arduino Leonardo.


text:
How to use bitset/read on 16bit numbers (Arduino)
I'm working on an Arduino powered Tetris game. To keep track of the pieces that have fallen and become fixed I have an array of bytes
byte theGrid[] = {
B00000000,
B00000000,
B00000000,
B00000000,
B00000000,
...

This works great when the well is only 8 LEDs wide, but I need it to be 16 wide. Is there a way to perform bitwise operations on a 16 bit number, like a short? I tried just declaring theGrid as a short, but I'm getting this error no matter what I do.
tetris:62: error: 'B0000000000000000' was not declared in this scope

The reason I was using byte is so I could use bitread and bitset. So if an L piece comes down and lands, I can bitset the appropriate bits like this
bitSet(theGrid[pixelY], 15-pixelX);

and end up with
B1000000000000000, B1110000000000000

There are no bitwise operations in that code.

@IgnacioVazquez-Abrams I edited the OP

The main problem that you're having is that binary literals don't exist in C; the Arduino libraries get around this by having every single binary value from 1'b0 to 8'b1111_1111 defined as a macro in cores/arduino/binary.h. The obvious workaround is to use octal, decimal, or hexadecimal literals instead.
unsigned short theGrid[] = {
00,
0,
0x0,
 ...
};

Bitwise operations work as normal.
theGrid[pixelY] |= _BV(15 - pixelX);

Thanks, I got a similar answer on stackoverflow. I think this will work :)


text:
Anyone have the Maplin N97DG bluetooth shield working?
I went & impulse-bought a Maplin Bluetooth shield yesterday.
It comes with a little tiny book containing examples, and uses the softwareserial library in these; I can load them, and get the Arduino <-> PC communication going OK, however there appears not to be a response from the bluetooth part of the device. The LED lights much as the booklet says it should. I did see it return some odd characters one time, just the once..
Given that the system appears to be alive, I don't want to give up & take it back; however the output from Google is not promising, and my trial to date isn't either - so I'm looking for positive news that this product does actually work for someone somewhere?
I'm using the built-in serial in the IDE to talk to it, not X-CTU as they suggest (as they don't do a Linux version).

I've just got mine working, in about 3 hours.
The first example I've never got working. The SAT+RESET worked first time... and I was then able to pair.
An easier module is the HC-05. That by default goes straight to discovery mode, and makes things alot easier.
I have more success with the serial monitor in Arduino studio, rather than X-CTU.
The point of the sheild is to prototype, or the shield you have to use in your production project. If you are doing the former, then there is little point in using the shield as you would have to change the code to fit the hardware.
It seems a thorough product, probably too involved.

Which Arduino board worked?

I have them both working on the Uno. Would you like me to put together my steps?

Actually, yes please, that would be useful - if I can have it working I may go re-purchase one!


text:
Am I able to set up a code where I can have two ways of turning something on?
I am pretty new to Arduino.
I've created a code with the help of many YouTube tutorials to control a servo with a button. I decided it has gotten a little un-exciting so I've been trying to add a sound sensor module to it so that if you clap or whatever, it will control the servo in the same way the servo did. Is it possible to control the servo with the button and the sound sensor so that I have to ways of turning on the servo at the same instance.
The code I currently have just runs the servo constantly and does not stop, you'll probably see what I mean when I attach the code below.
I'm just looking for help on this issue as I don't have a lot of experience with this, but my guess is it is not possible.
    #include <Servo.h>;

    const int buttonPin = 8;
    int soundSensor = 2;
    Servo servo;

    int buttonState = 0;

    void setup()
    {
      servo.attach(3);
      servo.write(80);

      pinMode(buttonPin, INPUT);

      pinMode (soundSensor, INPUT);
    }

    void loop() {
      int statusSensor = digitalRead (soundSensor);

      if (statusSensor == 1)
      {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);
      }
      else
      {
        servo.write(80);
      }

      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH)
      {
        servo.write(80);
      }
      if (buttonState == LOW)
      {
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);
      }
    }

Yes, you can. You just have to change your thinking from "The button is being pressed" to "The button has been pressed".

you have to realize that controlling a servo, detecting a button press and detecting sound are all completely separate functions ..... you can have a boolean variable moveThatServo .... if the variable has a value true then the servo is moved and if it is false then the servo stops ..... you can have multiple buttons, some set moveThatServo to true and some set it to false .... you can have a sound detector that sets moveThatServo to true ...... you can write a timer function that does the same..... just use your imagination

Just cobled this together,
untested but should give you some hints in the right direction.
In the main loop it checks the condition of the button and also the sound detector.
If either are active it sets a bool to true.
at the end of the loop, if either are true it calls the servo function that then powers the servo.
hopefully you will be able to pull this apart to add more triggers
#include <Servo.h>;

const int buttonPin = 8;
int soundSensor = 2;
Servo servo;

int buttonState = 0;
int statusSensor = 0;

bool runServo = false;  // bool setting to start the servo

void setup()
{
  servo.attach(3);
  servo.write(80);

  pinMode(buttonPin, INPUT);
  pinMode (soundSensor, INPUT);
}

void loop() {
  statusSensor = digitalRead (soundSensor);
  buttonState = digitalRead(buttonPin);

    runServo = false;  // start of loop reset the runServo flag

  if (statusSensor == 1)
  {
    runServo = true;
  }

  if (buttonState == HIGH)
  {
    runServo = true
  }

  if (runServo == true)
  {
    servoFunction();//call the servoFunction code
  }

};

void servoFunction(){
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(500);

}

Spriggsy