text:
Lockup while evaluating Wire.requestFrom function (Arduino)
I am currently working on a Arduino project that combines an InertiaOne IMU sensor board (from Atmel), with an Arduino UNO and two motors driven by a Makeblock driver board. All sensors communicate using I2C, with different addresses. My issue is that the program runs just fine for a while (everything between 1 second and 2 minutes), but suddenly lock up inside the Wire.requestFrom-function that handles I2C communication. More specifically, I believe that the code hangs at one of these points in the Wire library (the code is a direct copy):
...
// wait until twi is ready, become master receiver
while(TWI_READY != twi_state){
    continue;
}
...
// wait for read operation to complete
while(TWI_MRX == twi_state){
    continue;
}

As far as I know, there are only two units that utilise I2C in the system, both of which are embedded onto the InertiaOne circuit board. What I find very strange is that reading these two sensors works just fine when no motors are running, but that the problem occurs when the motors are activated. My first reaction was to use separate power supplies for the motors and sensor board since the issue could have been caused by a dip in the voltage and a reset of the sensor board, but without any change of result.
I am running out of things to try, and do simply not have the required understanding of I2C and embedded systems to see what exactly the issue is. Could it simply be that some of my parts are faulty, or am I perhaps overlooking something?

As for my problem: the code that is displayed above is taken directly from the libraries provided by Arduino, and is therefore most likely well programmed; however, I have actually tried both adding timers to the while loop and moving the sensor board 15 cm away from the motors (the motors are small). I unfortunately do not have any sort of debugging equipment, but using simple print statements, I have managed to trace all lockups down to the single ...

... two code snippets displayed above. My guess therefore goes to this being some deadlock in the I2C communication, a field of which I am no expert. Although I agree with all of what you suggest, I find either thought very hard to verify. :)

If you are using long cables, it might be an EMI issue. Either find an oscilloscope and probe what is happening on the I2C bus on the μC side or try using shorter wires just to see what happens. Also check that the grounds are all connected at some point. A star ground topology might help. Lastly, check to see if the PSU can supply enough current when the motors are turned on. Again, use an oscilloscope and prove the Vcc of the μC.

Hi, Evangelos. The cables are about 10 cm long, and I do unfortunately not have an oscilloscope available (although I certainly wish I had!). I have connected all GNDs to the same point, and also attempted to use unconnected (except through ground) power supplies for the sensor board and Arduino.

When saying you have connected all GNDs, have you tried connecting all circuit grounds together and then connected that point to mains earth? If that didn't work, I have no more insights. You'll need an oscilloscope or logic probe or some other way to debug it. You could try sending debug text to a computer through the serial interface of the UNO.

I have not tried connecting all GNDs to an external main earth, if that is what you mean. I will try that, and also make another more serious attempt to try and avoid EMI - I might have ruled that out too quickly. Also, maybe I can get a second arduino to work as a scope for the first somehow. Thanks!

"libraries provided by Arduino, and is therefore most likely well programmed" - There's a false assumption right away, especially for the TWI library.

Thanks for your comment, Dan! I'm starting to believe that the Arduino itself locks up / resets / whatever, and not the IMU unit, which I previously though was the problem. I will try adding timeout methods and recovery code for the TWI library, as was previously suggested above. Without the equipment to investigate the I2C communication or power levels accurately, I believe recovering from the issue will be much easier than actually solving it at this point!

The Wire library has an issue in the lines you posted, that if an interrupt is lost, it will stay in that loop forever. There are two things you could do to fix this:

Stop the interrupt from being lost (ie. fix electrical problems)
Use a library that has a time-out.

For the electrical issues, I would make sure you have pull-up resistors from SDA and SCL to +5V - typically 4.7k (for each one), but that would depend a bit on whether the device already has them. Also make sure you have decoupling capacitors on the Vcc lines as appropriate.
For the software side, there is an alternative library (master only) at
Arduino I2C Master Library.
I haven't personally needed to use that library, as with pull-up resistors and short cable runs, I haven't had problems with the Wire library. However if things are marginal you may well find that it helps.

It is a shame that a library which is so horribly bad programmed found it's way into Arduino core. Obviously there must be a timeout!

True, some parts sacrifice reliability for simplicity. The good part is, you can always write your own, or just take the existing one and modify it. It's not like the libraries are distributed in binary form only.


text:
Why is my real time clock getting the wrong time from my PC?
I want my real-time clock to set its time as the time on my PC. However, when I run the following sketch, the real-time clock reports the time as being 32-33 seconds earlier than my PC says the time is.
#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

void setup () {
  Serial.begin(57600);
  Wire.begin();
  RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
// uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
  DateTime now = RTC.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
}

I have also tried manually setting the time on the RTC, but I end up with the same problem: the RTC is always 32-33 seconds behind what I set it to. The lag happens as soon as I run the sketch. It seems very odd to me that no matter how I try to set the time, I end up with exactly the same error. I can tell the Arduino to report the time as being 33 seconds after what the RTC says it is, but this solution seems kind of sketchy, and I am worried that something is fundamentally wrong with my RTC or the way I am using it.
I am using an Arduino Uno with an Assembled Data Logging Shield from Adafruit. The data logging shield uses a DS1307 RTC. Has anyone had this problem before, or have any ideas about what could be causing it? Any help would be much appreciated.

Ive taken Hugo Bertini and Oli explanation to use in my projects and it works ! Thank you (: but it goes faster by 26 seconds....

The __DATE__ and __TIME__ are set when the code is compiling so they will naturally be behind since the code still needs to finish compiling and then be flashed to the chip.
See the Arduino Playground for an example of how to sync it to your computer over serial.

TimeSerial.pde shows Arduino as a clock without external hardware.
It is synchronized by time messages sent over the serial port.   A
  companion Processing sketch will automatically provide these messages
  if it is running and connected to the Arduino serial port.

You can fix the offset by calling once the following code in the setup() function:
RTC_DS3231 rtc;

DateTime now = rtc.now();
rtc.adjust(DateTime(now.unixtime() + 10)); // add 10s to current time for fixing the offset

I am experiencing a similar problem with an Arduino UNO and a Nano. Both from the same PC.
 Indeed it looks like the time it takes from compile time to upload + MCU start is reflected.
Assuming the RTC has a good battery and the compilation + upload times are consistent, then adding a drift compensation to the code seems to do the trick.
Here's how I did it (in my case 7 seconds did the "trick" - sorry for the hardocode, but that's for mere description purposes):
RTC.adjust(DateTime(__DATE__, __TIME__));
DateTime t = DateTime(RTC.now().unixtime()+7);
RTC.adjust(t);

Regards,
Hugo Bertini

With the <DS1307RTC.h> library the DS1307 can be adjusted during time setup, by using a global variable and then adding this to Sec reading in the getTime() function, for example as follows:
#include <DS1307RTC.h>
tmElements_t tm;
byte adjustt = 8;  // adustment for seconds lag allowing for compiler download time

/*********************

bool getTime(const char *str) {
  int Hour, Min, Sec;
  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec + adjustt;
  return true;
}

The Arduino takes the computer time and sends it to the DS1307. The time it takes to copy is the one you are seeing wrong. I would solve the problem by advancing the computer time the necessary seconds that you say is delayed and when programming you should have the exact time.

source: Stack Exchange

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

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

sort: votes


text:
Arduino UNO USB not recognized
I've just received my Uno today and already I think I may have broken it :(
I was able to connect to usb and upload a sketch (the blink). However, I then tried to connect a circuit to do the Hello World LCD example. After trying this a few times, I noticed the LCD chip get very hot...and I had mis-wired it. In any case, after a few more tries, the USB connection to my Arduino UNO stopped working.
I tried swapping the cable, connecting it to another mac and to a windows with no luck. I'm worried I may have shorted the USB bus chip when trying Hello World.
I also tried connecting a 12V DC power supply.
I still get the green power light and the amber L light...
Did I break my Uno?
How do I troubleshoot this one?
thanks

What do you mean that it "has stopped working?" Any errors? Right COM/board selected? Any luck with no LCD?

Basically the serial USB didn't show in the list of ports and also it doesn't show in the mac system profiler...no luck with the lcd

Try reflashing the firmware on the atmega8u2. You might be able to do this using dfu, if the bootloader on it wasn't corrupted (too).

Very similar disscussion: http://arduino.stackexchange.com/q/129/37

When the LCD pulled enough current to overheat, the Arduino's power supply (which I gather was the Uno's USB interface, at the time) was probably stressed to the point of failure. One fortunate result is that the Arduino took the hit instead of the computer's USB port that was supplying it. It's not clear which part was involved but here's a discussion on another forum concerning a similar failure and replacing the ATMegaxU2 which does USB-interface duty on the Uno (x = 8, if it's a rev 2 Uno, x = 16, if rev 3). It may be possible to replace the failed chip - regulator or USB interface (though with LEDs working, it's probably not the regulator). Otherwise, you can probably still program it with an ISP (In System Programmer). But the easiest way to do that is probably involves another Uno.

Replacing a QFN is no easy feat. Drawing to much current however shouldn't break the atmegaXu2. The u2 is only connected to the atmega328 via TX and RX, and those connections have a resistor. My suggestion would be to try reflashing the firmware on the atmegaXu2, and maybe replacing the atmega328 (which is could be broken due to excessive current through one of the IO pins).

You can try and buy the Arduino serial board, and connect it directly to the pins on the Arduino , see if this works, basicly override the Arduino's own interface, or if you have another Arduino you can try and "serial" connect them using the first Arduino as ISP.
Else it is like JRobert says, you could move the chip from another arduino burn it on that one and then put it back, using the second Arduino as a run only.
Last but not least, you may find a cheap broken Arduino board on some online auction site, where the chip is broken, then move the defect chip to your defect board, and the working chip to the working board, and throw the defect Arduino in the electronics recycling.

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


text:
I bought USB > FT232RL, can I use it to program a bootloader onto an Arduino?
I bought this thing off of eBay:

eBay Link

Will it allow me to program an ATmega[xxx] (Arduino clone) with a bootloader?
 --> If so, how would I go about it? What should I do, and what should I certainly not do?
 --> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

I'm a bit new to Arduino, and since I learned that a fair amount of the clones being sold on eBay don't have a bootloader, I wondered how to fix this. (and the "barebones" seem to be quite a bit cheaper)

Answer - summarized from different answers below (as I can only mark one answer below as accepted):

Can you use an FT232R to burn a bootloader onto an AVR (such as an ATmega328)?

=> Yes you can, though it's a bit annoying to do, as it's slow and a bit more complicated than just plug and play. See the first part of Chris Stratton's answer below.

I already have a working Arduino style board, can I use that?

=> Yes, you can use for example a UNO-style board to program another. This process is explained here: http://arduino.cc/en/Tutorial/ArduinoISP, which was referenced in the second part of Chris Strattons' answer below.

The two options above are too much of a hassle for me, or I don't have an Arduino yet/available, is there another option?

=> Yes, you can buy a USB to ISP (In-System Programmer) board/programmer. They're pretty cheap and are called USBISP or USBASP for example. Here's an example: http://www.ebay.com/itm/180980285082, referenced at the end of MatsK's answer. (or an even cheaper one: http://www.ebay.com/itm/390806886235).

None of the Arduino clones I bought (from several web stores) came without a boot loader. They were all programmed with bootloader / blink example. How did you determine there is no bootloader on it?

Because I asked the seller, for example the Mini Pro on the page doesn't have one: http://www.ebay.com/itm/400683486113 (while their 'Nano' does).

In fact, you can, but you are unlikely to enjoy it as it will be fairly slow.
While this module is intended for serial communications - which the ATmega won't support until it has a bootloader on it - the chip around which it is built can also be operated in "bitbang" mode:
http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf
Using reconfigured pins of this wired to the ISP pins of your target, and an implementation of the ISP algorithm running on the PC, it will indeed be possible to load a bootloader on to a new ATmega chip.  However, USB is not designed for this type of usage - it is meant to move large blocks of data, rather than to efficiently do sequences of tiny operations.  The result is that the loading process will be drastically slower than with other methods.  You may also spend a fair amount of time tracking down software to do it, or writing your own.
If you have an already working Arduino-style board available, you can use that to program your new chip:
http://arduino.cc/en/Tutorial/ArduinoISP

avrdude has a number of programmer entries with ft232r in the name, implementing various bitbang configurations for FTDI chips, so the software side is pretty much solved. That said, I agree with @ChrisStratton that it's not much fun.

Drastically slower, meaning a few minutes instead of seconds, or even more? (ballpark number's fine).
That would only be the first time then, for burning the bootloader? Because after the bootloader's been put in it can be programmed through a serial connection, meaning seconds, right?

I expect it would take less time to run than it would to find the software to do it that way, but yes, the bootloader is fairly small and only needs to be loaded once.

Ok, that's what I figured. I think I'll be using your second suggestion since I already have a UNO clone.

You must use a ISP or (HV)PP programmer in order to write the Arduino (or similar) bootloader to the chip first. Only once you have done so will you be able to program it via a serial connection.

Will it allow me to program an ATmega[xxx] (Arduino clone) with a
  bootloader?

NO. The serial device can only be used when the Atmel ATmega chip has a bootloader burned onto it.

--> If so, how would I go about it? What should I do, and what should I certainly not do?

To burn a bootloader onto a Atmel AVR chip you need a "AVR ISP (In-System Programmer)".
There is a small 2x3 pin contact on your Arduino board.
In the Arduino IDE under the menu "Tools", "Programmer" you will find the different "AVR ISP (In-System Programmer)" that you can use.
Please note that some programmer have an 2x5 pin ISP contact and if that is the case you will also need to buy a 2x3 to 2x5 adapter.
Ref.: http://arduino.cc/en/Hacking/Bootloader

--> If not, what do I need (or where can I learn) to be able to use an Arduino clone with the Arduino IDE?

Most Arduino clones bought on ebay have info witch clone of Arduino they are.

I'm a bit new to Arduino, and since I learned that a fair amount of
  the clones being sold on eBay don't have a bootloader, I wondered how
  to fix this. (and the "barebones" seem to be quite a bit cheaper)

Im a bit confused, I have bought ~10 Arduino clones from ebay and all had a bootloader. And they are clones of UNO, Nano, Leonardo and Mini Pro and that is what I uses for settings in my Arduino IDE.
I'm interested in witch ebay clones that doesn't have a bootloader, could you post a comment with that info?
I use a USBASP (example: http://goo.gl/kCiMd) as my external programmer.

The serial device can only be used when the Atmel ATmega chip has a bootloader burned onto it. — This is true, as far as that goes, but the FT232 also has bitbang mode.

"Most Arduino clones bought on ebay have info witch clone of Arduino they are." > I'm not confused about which clone/model they are, just curious about how to burn the bootloader ;)
I asked a seller of a 'Mini Pro' on the following page whether it has a bootloader, and he says it doesn't: http://www.ebay.com/itm/400683486113 (while their 'Nano' does).

DaJF it was not my intention to be condescending.

No problem, I didn't interpret it that way, just wanted to clarify :)
The fact that you haven't come across a clone without a bootloader gives me hope I won't either, so thanks for the info.

My FT232RL has a 2x3 pin ISP header eBay, but I did not check it yet.


text:
Leonardo (32u4): Timer0 problems with CTC mode
I want to use timer 0 to generate a rectangular signal on OC0A (D11) without the use of Arduino specific functions (that use timers for themselves). When I toggle D11 manually using a loop, I hear a sound in the connected piezo, but with my sample code, I don't hear something:
#define ALARM_PIN 11

void setup() {
  digitalWrite(ALARM_PIN, LOW);
  pinMode(ALARM_PIN, OUTPUT);
  noInterrupts();

  OCR0A = 60;
  // Toggle OC0A on compare match
  TCCR0A = (0 << COM0A1)
         | (1 << COM0A0)
  // CTC mode
         | (1 << WGM01)
         | (0 << WGM00);
  // prescaler = 256
  TCCR0B = (0 << WGM02)
         | (1 << CS02);
}

void loop() {
}

Any idea, what could be wrong?
Update
I've played with it a little bit more:
#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 250);
}

This causes my LED to light very dim, so the timer is running up to 255. But as soon as I set TCCR0A, nothing is lighting up:
#define LED_PIN 9

void setup() {
  pinMode(LED_PIN, OUTPUT);
  OCR0A = 60;
  TCCR0A = (1 << WGM01);
  TCCR0B = (1 << CS02);
}

void loop() {
  digitalWrite(LED_PIN, TCNT0 > 0);
}

What happens when you connect an led to pin 11? What happens if you flip the polarity of the led around? (So pin11--resistor--led--ground and pin11--resistor--led--vcc). If pwm is working then the led should be lid either way.

You should re-enable interrupts after you finish setting up. Use either
interrupts();

or
sei();

If you want to don't want to use the arduino specific commands. Even if the code does not need interrupts, background code does use them.
Timer 0 is used in arduino for some basic "house keeping" function like keeping time. I'm not sure if that could be part of your problem. you could try using a different timer.

Thanks for the answer, but I don't need the interrupt, the port pin should be toggled automatically on compare match.

You are correct. I thought at the time that the bits would also control the compare match output, in any case you might not want to leave interrupts off.

Enabling interrupts at the end of setup() using sei(); does not make any difference.

Your value of 60 for OCRA will give you tone of around 16666hz which isn't audible to us humans. Try setting it to 255. That should give you a 4000hz tone, which is audible. (Or get your neighbors dog, and see if he dislikes hearing it)
You can use this online calculator to help you get the correct value for OCRA.
Note that you need 2 cycles to get a full wavelength (1 low and one high), so two toggles.

16MHz + 256 prescaler and the OCRA set to 60 should give me ~500Hz. I've tried different values, even your 255 but without success.

A decent-sized portion of the population can hear 17kHz sounds. 19kHz would be a bit of a stretch though.

My mistake. I don't know where I got that 8-prescaler from.


text:
Leonardo (32u4): ways to brick it programmatically
When the Leonardo was introduced, I think, I've read some articles about being cautious to do some things, that could cause it to not load any new sketches any more, so one has to rewrite the bootloader. Because I plan to use power-saving options, e.g. to disable unused hardware components like USB port, I fear to do something wrong.
One Leonardo-delicacy I've found so far:

if interrupts are disabled, uploading new sketches fails unless one presses the Reset button as soon as the Arduino IDE is showing "Uploading..."

What stuff (except of the usual hardware-related thinks like connecting output-configured pins to fixed potentials) could damage the controller or require to reflash the Leonardo with a fresh bootloader?

Generally, Arduinos are impossible to brick via software unless messing with the fuses on the chip (or designing a robot to destroy the board :D).

The bootloader is always run before your own program. So when you press the reset button the bootloader will start and you can upload you new program, even if the your old program was faulty. Disabling certain components is just temporarily, and they should restore when the device is reset. By changing the fuses you can make certain option permanent, so try to avoid having  to changing those.

Gerben, could you please add your comment as answer?

If you upload a program that changes the speed of the USB core it would be almost bricked. What would happen is this:

Power on, boot loader starts, USB device enumerated on PC.
A few second later program start, USB core speed changed, USB device disappears from PC

The issue here is that not only do you have to hit reset to program, after the reset you have to quickly select the right com port and then upload before the program starts.
The Redbearlab Blend Micro requires a USB core speed to be set in the user program. In their setup instructions there is a step to edit the Arduino main.cpp and add a section to do so. If this step is missed, the above problem happens.

I managed to brickwall an ATMega128RFA1. The bootloader, and the software I uploaded in it, were working fine. But it was impossible to erase/write the ROM.
After checking for what have happened, I discovered in the datasheet that some fuses in the AVR core are intended to protect accidental writing on the ROM. Some kind of security fuses.
I never found the bug which wrote in these bytes (as it was a really big program and we were 3 peoples involved in the coding) but yeah, we just blew a fuse and lost an MCU because of a bug.
As for the leonardo, several things could happen, but none of these can brickwall your board unless you blow one of this protection fuse.

It is possible, with some really clever code, to exploit the bootloader to overwrite itself.
Excerpt:

The solution is actually conceptually fairly simple. A bootloader, by
  its very nature is designed to download new firmware to the device.
  Therefore it will contain at least one spm instruction. Because the
  spm configuration register must be written no more than 4 cycles
  before the spm instruction it means there are very few sequences that
  practically occur: just sts, spm or out, spm sequences. So, all you
  need to is find the sequence in the bootloader section; set up the
  right registers and call it.
However, it turned out there was a major problem with that too. The
  V-USB self-programming bootloader's spm instructions aren't a neat
  little routine, but are inlined into the main code; so calling it
  would just cause the AVR to crash as it tried to execute the rest of
  the V-USB bootloader.
Nasty, but again there's a solution. By using a timer clocked at the
  CPU frequency (which is easy on an AVR), you can create a routine in
  assembler which sets up the registers for the Bootloader's out, spm
  sequence; calls it and just at the moment when it's executed the first
  cycle of the spm itself, the timer interrupt goes off and the AVR
  should jump to your interrupt routine (in Application space). The
  interrupt routine pops the bootloader address and then returns to the
  previous code - which is the routine that sets up the out, spm
  sequence. This should work, because when you apply spm instructions to
  the bootloader section the CPU is halted until it's complete.

So basically, you can do some fancy programming, and get the bootloader to hose itself, rendering the MCU useless without a dedicated programmer.

The one I know of is making the Leonard act like a USB mouse that flaps everywhere and types random keys so you can't reprogram it without doing some kind of trick to get around it. But they mention this on the api docs.


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

Have you tried peak detection yet?

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

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

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

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

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

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

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

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


text:
Maximum Current?
This is an extremely noobie question, but I have a 5V at 2A power source. This power source is going to be powering 6 Sharp IR distance sensors(20-150cm) and a few other low current consumption sensors(ie Xbee).
My question is if it is safe to simply use that power source without some sort of resistor between the power source and sensors?
also the IR sensors have a analog output. Is that same to plug into the arduino's analog pins?

also the IR sensors have a analog output. Is that same to plug into the arduino's analog pins?

If the sensors won't generate more than 5V, it should be safe. (Generally, they're all less than 5V. However, verify this...)

My question is if it is safe to simply use that power source without some sort of resistor between the power source and sensors?

You probably don't need a resistor*. Current is supplied on demand; if you need 1A but have a 2A supply, only 1A will flow. Voltage, however, is constant.
That being said, some parts will pull more current than they can safely use (like a LED, so then you would use a resistor.
This should all be found on the datasheet (especially with a more trusted brand like Sharp). Just look for example circuits and input voltage/forward voltage. A quick note, make sure to connect the grounds if you're not driving the Arduino directly from the power supply.
*There probably is an internal resistor for the LED. Again, datasheets, datasheets, datasheets!

wow once again you answered my question flawlessly. Thank you so much

A few other points, in addition to Penguin's excellent answer:
Make sure your 5V supply is a REGULATED supply. Unregulated power supplies will exceed their target voltage when unloaded, and "droop" to lower than their target voltage when under heavy load.
Quite a few digital components can be destroyed if their input voltage varies too much from 5V, especially over-voltage. TTL is especially sensitive to over-voltage (which destroys the circuit) and to malfunctioning on under-voltage.
Even a regulated power supply will have some ripple if you switch heavy loads on it. You might want to use separate, isolated supplies for your high power and low power logic systems.
A higher current regulated supply will be "stiffer" and therefore more stable if run at lower loads.

I am using 4 seperate ESC (electronic speed controllers) these give off 5 volts at 2 amps as a BEC (battery eliminating circuit) I assume that they must be regulated to take their 11.1 volt input and turn it into 5 volts.

I also have the IR sensors using their own power supply and my gps and xbee with another. By the way thanks


text:
Arduino Controlling through C#
i would like to measure some signals from arduino and send it to a pc using USART and display the results in a c# winform application. Does anyone have such a project example ?
Besides, i want to send the data in live time mode, each values should be directly transmitted and then the second measurement ( sample rate 100 kHz )
Thanks a lot

Are you sure you can support that sample rate with your communications?

The maximum sampling rate for analog signals is 10 kHz at default 10 bit resolution. Digital should be ok. The USB bus is nominally 12 MBit/s. Assuming 1-byte data size, you would probably have to send the data in 64 byte bursts(max packet size) if you want a chance of having eneough bandwidth since there is also overhead. Whether possible would depend on the Leonardo USB implementation and possibly also hardware/software on the PC.

User2973, you should post your comment as an answer, and then the OP should accept it. (Excellent, through treatment of the question. Voted.)

ok, if we assume with 5 KHz samle rate, do you can any suggestion for c# PC program to control the board ?

This question was never specific enough for the rules of this site, and has clearly been abandoned for over a year.  Voting to close.

Am I missing the point here or wouldn't the C# just have to open a Serial connection to the board and read and write to that to control the program running on the Arduino?
Yes the board is connected by USB, but that's only so it can open a serial connection.
To be honest I don't think you will be able to sample at that speed, you might be better looking at ICs that directly interface with GPIO and RS232/USB.


text:
Arduino Yun Serial Terminal Overflow Issues?
EDIT: after reading up on some stuff and with the help of the comments people left, I'm certain that it's an overflow issue, but I'm not sure how to solve that...
So I just got an Arduino Yun today and have been figuring out how to use it.  I seem to have run into a problem though and haven't been able to solve it...
I stripped down the YunSerialTerminal sketch that allows accessing the yun linux terminal over a usb com port:
void setup() {
  Serial.begin(9600);      // open serial connection via USB-Serial
  Serial1.begin(250000);   // open serial connection to Linux
}

void loop() {
  if (Serial.available()) {             // got anything from USB-Serial?
    int c = Serial.read();              // read from USB-serial
    Serial1.write(c);                   // write to Linux
  }
  if (Serial1.available()) {            // got anything from Linux?
    int c = Serial1.read();             // read from Linux
    Serial.write(c);                    // write to USB-serial
  }
}

It works for the most part, but has some odd differences from connecting via ssh over wifi.
It seems to be dropping random characters from the screen (due to buffer overflow):

As you can see, it's messed up some of the text such as md5um which should be md5sum and the formatting is all off.
It gets even worse when launching elinks terminal web browser (which works beautifully when connecting via ssh over wifi):

I've also tried different programs (other than putty), including the arduino ide serial monitor, and they all produce the exact same result (and yes I'm setting them to the correct port speed as well).
Does anyone have any idea what I'm doing wrong?  I've tried many different port speed combinations and they all produce the same result.  It seems that the atheros-atmel link is set to 250000 baud (Which is why I have to use that speed on Serial1 in my sketch), but can that be changed?  I've read some things about how 250000 is way too fast when the atmel is involved, but is there a way to change that speed without losing the Bridge library functionality?
Also, could someone else with a yun try this sketch and verify that it works? Load it, and connect with putty via serial (using whatever com port arduino bound to) and double tap tab key to see if the command listing is missing letters.

Are you sure you only have one application reading serial data?

Nearly positive, all I have open is putty. Also, it only drops characters when something large is printed out, when I'm typing or holding down enter to get blank prompts, it appears fine.

Looks like your serial buffer is overflowing. Does the original code work as intended? Did you remove software handshaking (XON/XOFF) by any chance?

The original code has the same issue (I stripped it down in an attempt to fix it. I noticed the software handshake settings in putty and left it set to xon/xoff, is there something in the code I need for it to work?

I'd agree with Jippie on overflow, specially the atheros-to-atmel channel is fast enough that linux can easily overwhelm any possible buffer in the atmel before the data can drain at the drastically slower USB-serial baud rate.  You could try increasing the external baud rate.  XON/XOFF might work, but it would need to be applied to the atheros-to-atmel link.

@ChrisStratton I've read up on a bunch of stuff, and I agree it's definitely overflow.  However, I've tried running both serial connections at 250000 and it still has the exact same issue.  I'm thinking that maybe the USB-serial isn't capable at running at 250000?  In which case I'd need to lower the atheros-atmel link to a slower rate.  Do you have any idea how to do this or XON/XOFF for that link?


text:
Receiving two-byte int values over serial
I am using Python smbus write_word_data method to send int values from a Raspberry Pi to an Arduino using I²C.
This seems to be the correct method.
When I send values from 0-255, I see the following in my Arduino serial monitor

0,0,0
  0,1,0
  0,2,0
  …
  0,255,0

Sending 256 I see:

0,0,1

For 257 I see:

0,1,1

Etc, etc...
My question is, how would I modify the following Arduino code to properly 'reconstitute' the int values, and then send them back to the RPi?
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
bool newData = false;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
  Serial.println("Ready!");
}

void loop() {
  Serial.println(receivedValue);
  newData=false;
}

// callback for received data
void receiveData(int byteCount) {
  while(Wire.available()) {
    newData = true;
    Wire.read();
    if(Wire.available() == 2) {
      receivedValue = Wire.read() | Wire.read() << 8;
    }
  }
}

// callback for sending data
void sendData() {
  Wire.write(number);
}

Aren't you really transferring these over i2c, not (asynchronous) serial as implied in the title, and using the serial more as a debug monitor to tell what is going on?

void receiveData(int byteCount){

  // Looks like your number is sent in a 3 byte packet
  if (bytecount == 3)
  {

    // Discard first number as it is seemingly alway zero
    Wire.read();

    // Read low byte into rxnum
    int rxnum = Wire.read();

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    // Send back
    sendInt(rxnum);

  }

}

void sendInt(int num){

  // Uncomment below if you want so send back in same format
  // Wire.write(0);

  // Send low byte
  Wire.write((uint8_t)num);

  // Send high byte
  num >>= 8;
  Wire.write((uint8_t)num);
}

Just to clarify. Wire.read() and Wire.write only work of single bytes. To send a 2 byte int, you need to split the int into 2 bytes, send them individually, and then join them again at the receiving end.

thanks!. I've edited my original code and it works, but how do I separate out my x,y coordinates in my main loop?   Serial.println(receivedValue);

This likely won't work as op expects. Each write(byte) transmits in separate transactions. If the master calls this with requestFrom(), it'll only receive the first byte, and never receive the second. To send both bytes, you need to pass a byte array to write().

Ir seems to me that there is something wrong with the Python Raspberry Pi code. What you show is 3 bytes of data, not 2. That's wrong.
If you're writing a 2 byte word, I would expect to see 2 bytes, not 3. You might want to post a question on the Raspberry Pi forum to get help resolving THAT problem first.
If you're stuck with the sending code you have, then here's what you would do.
Looking at your data, the first byte is always zero. You want to discard it.
The second byte is your low order byte, and your third byte of data is the high order byte. You need to do some juggling to get the data into the correct byte order, like this:
void readWordWithPadding()
{
  if (Wire.available()<3)
  {
    newData = false;
    return;
  }
    newData = true;

  Wire.read(); //Throw away the filler byte
  int lowByte = Wire.read();
  int hiByte = Wire.read();

  //Shift the high byte by 8 bits and add in the low byte
  receivedValue = (hiByte << 8) + lowByte ;
  return;
}

Thanks. The remaining problem is separating out my x,y values. On the sending side I call writeNumber(x) then writeNumber(y). So In my arduino code receivedValue alternates between x&y. But having a problem separating the 2.

That is a design problem. You need to coordinate what is sent from the Pi with what you look for on the Arduino side. If you're always sending an X/Y pair, then you should write your Arduino code to look for an X/Y pair. Always read both numbers. You might need to adjust your code logic to make sure 4 bytes (or 6 bytes if you haven't been able to get rid of those spurious zero bytes) are available before starting to read.

Unless (and until) your application needs high enough data rates that you need to make the most efficient use possible of your data channel (or you're talking to an inflexible hardware device that dictates the data protocol), you'll save yourself a lot of headaches by sending human-readable strings, something like:
x= 12345, y=   -32
x=   432, y=-33221

You can reconstitute them at the other end with with atol(), log them  to a file, be able to understand them later, and see instantly whether the sender sent what you expected it to. Don't optimize until you have to; you may not have to.


text:
Connecting Arduino Yun to wifi with 802.1X authentication
Is it possible to connect the Yun to wifi using 802.1X authentication?  802.1X is WPA2-Enterprise that uses a username and password (per user) instead of one password (for every user).  I don't see a way to do it from the Yun web interface, but is there a way to do it from the linino terminal?
As far as I know, the Atheros AR9331 chip should be capable of this, but I don't see a way to do it with the software included on linino, there must be a way to install something for this?

The question would ultimately be if this is requires any hardware changes, and if not if it is implemented in code which is open source and modifiable, or some propriety binary-blob chipset firmware or driver.


text:
Changing direction of DC motor
i am working on a project which requires changing the direction of the DC motor using arduino. that is I want the DC motor to rotate clockwise when i press key 'A' and anti clockwise when i press key 'D' on my computer.
i have v+ and v- input wires from battery. i have connected one end of the DC motor to gnd of the battery. On the other end of DC motor i want to connect V+ and V- input from the battery to spin the DC motor in clockwise and anticlockwise respectively. I have used BC547 npn transistor.
i do not know how to change inputs (v+ to v- and vice-versa) using arduino when key is pressed.
is there any method other than H-bridge method to do so?
i use arduino uno.

I've used a double-pole-double-throw relay once to move a dc motor back and forth. Not ideal, but very easy to wire up, and foolproof. Just out of curiosity, what kind of battery are you using that has three terminals (GND, V+ and V-)?

When working with DC - no there's no other ways. You can physically reverse the connections with a relay, or you can use an H-bridge. Regardless of the way it might be constructed, a device which allows you to control the current direction electronically will be called an H-bridge. You get an H-bridge in the Arduino starter kit so there's no reason to fear it. They are easy to use.

@Gerben i have 2 battery packs. i have packaged it into one. i do not fear the use of Hbridge. but i dint want to make the circuit more bulky. so thot if there was an other method where u can achieve this without using Hbridge just by using arduino and transistors

Since you have both a V+ and V- you could just use 2 transitors. If you look at an H-bridge, you only need half the circuit. The only problem is that you need V- to disconnect the NPN transistor, and the arduino can only go as low as GND. So you'd need a second transitor to drive it. The same might also be needed for the PNP side, if the arduino voltage is regulated to a lower value than V+. I found this schematic applicable, but only use the left side, and replace the opto's with normal transisors.

@Gerben thast cool. post that as an answer. thank you much

Since you have both a V+ and V- you could just use 2 transitors. If you look at an H-bridge, you only need half the circuit.
The only problem is that you need V- to disconnect the NPN transistor, and the arduino can only go as low as GND. So you'd need a second transistor to drive it.
The same might also be needed for the PNP side, if the arduino voltage is regulated to a lower value than V+.
I found this schematic applicable, but only use the left side. The right side of the motor should be connected to ground (or the middle voltage of your battery). , and replace the opto's with normal transistors.

Come to think of it, I'm not entirely confident about replacing the bottom opto, since battery-negative is below GND in your case. I think it should work, but I'm still quite new to this stuff.
Also make sure you add something like 1k resistors to the base of the transistors (that replace the opto's)

L298 IC is very popular way of doing it. IN1 IN2 to control direction, open circuit and breaking (short circuit of motor terminals). EN1 for PWM speed control.
Ready made module PCB widely available.
useful info
https://www.sparkfun.com/products/9670
http://forum.arduino.cc/index.php/topic,84439.0.html
Hope it helps.

Without using any other IC is there a way?

You could get 4 transistors and build your own H-bridge instead of one packaged in an IC.

Building a discrete H-bridge is non-trivial, so most will go with the IC solution.  The L298 works but has high internal losses and is not great for battery powered projects.  Something more modern like the TB6612FNG is more fragile but also far more efficient.

L298 boards has been around for long time, made by 50 factories and 200 resellers, thus, very good cost and easy available.  Lot of tutorials and examples. New MOS driver can have better several to ten percents turn-on lower power loss which is generally not significant for DIY uses as compared when battery life is very important for real commercial products. They are higher cost and less easily available.

Why is an H-bridge non-trivial to build? I could do it with 4 logic level MOSFETs connected to logic lines on an Arduino. Add a few logic gates and it would only need a forward/reverse control and an on/off control from the Arduino.

so hbridge is the only way i suppose. i did not want to make the circuit more bulky. thot if that could be achieved only through arduino. since i had v+ and v- inputs. any way u can switch these inputs other than physically doing it?

If small size is the requirement, you may want to take a look at this example (others has similar too), at bottom of page, there are small boards at 5 USD. http://www.pololu.com/category/11/brushed-dc-motor-drivers   The reason that external driver chip/transistor is needed is because drive current from Arduino UNO/ATMEGA2560 are source / sink 20mA, where small motor is about 100mA upward. Consider Arduino Pro Mini for small size.

Arduino can't handle motor level power directly. It also can't handle negative voltages directly. The Arduino can CONTROL a circuit to drive a motor forwards and backwards, but it can't drive the motor directly. Handling high power devices like motors takes external circuitry, period.

@DuncanC - you must select components, make sure your get the gate drive voltages, make sure you have flyback & ESD protection, make sure your switching will not result in shoot-through, etc.  Modern IC bridges accomplish a lot of that for you, and so are far more user-friendly when the goal is to make a motor spin rather than learn subtle lessons about power semiconductor usage.

@ChrisStratton, thanks for the explanation. "Lessons about power semiconductor usage" sounds like it might involve smoke and the smell of burning electrical components. Does the H-Bridge design illustration in Gerben's answer seem reasonable? Looks good to me, with diodes to prevent flyback, opto isolators to isolate the control and power sides, etc.


text:
Proxying streaming i2c data(int values) to serial
The following code works correctly in reading single int values. It also works correctly for 3-4 seconds if I 'stream' the values in constantly (Mouse move coordinates) before I get an IO error and the i2C bus connection is dropped. I assume this is some sort of buffer overrun...or? Can anyone get me on the right track here? What changes do I need to make so that I can constantly stream in serial data?
    #include <Wire.h>

#define SLAVE_ADDRESS 0x04
int zeroByte;
int state = 0;
int receivedValue = 0;

int numBytes = 0;

bool newData = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
    if(newData){

      Serial.println(receivedValue);
      newData=false;
    }
}

// callback for received data
void receiveData(int byteCount){

    while(Wire.available()) {
        newData = true;
        zeroByte = Wire.read();

         if(Wire.available() == 2)
  {
    receivedValue = Wire.read() | Wire.read() << 8;

  }

     }
}

// callback for sending data
void sendData(){

    Wire.write(receivedValue);
}

Please specify which arduino board you are using and where you see the I2C io error.

Your I2C bus is operating at 100 kHz. Your serial connection is set to 9600 baud. In case you are sending coordinates at a pace faster than the serial interface can keep up, the buffer will fill up. I assume you are using hardware serial (uno, mega, etc). Once the buffer is filled up Serial.write (which is called by Serial.println) will block until the buffer has free space. But the serial transmission depends on interrupts, and you are calling Serial.write inside an interrupt routine. By defult interrupt routines block other interrupts from happening. So your program gets stuck there and locks up both the serial transmission and the I2C interface.
It would be a good idea to put the serial write outside the interrupt routine, in the loop. Make a global variable bool newData = false; and set it true in the receiveData function. In your loop check the flag and transmit the data. Then set the flag to false.
You will still experience data loss if the serial interface can't keep up, but your application wont lock up. To solve the data loss simply use a higher baud rate, eg. 115200.

brilliant answer! will test and provide feedback. Thanks

I've made you're suggested changes (see above) but I'm only seeing the 2nd receivedValue(y value) in my println statement. Could you possibly suggest what changes I need to make and I will approve your answer. Thanks again.

You need to remove the delay from loop(). Also consider using Serial.begin(115200) if you don't want data loss.

Works!.....But how do I separate out my x,y coordinates in my main loop? Serial.println(receivedValue);


text:
Is i2C more or less robust than GPIO?
Currently using i2C to connect a RPi with an arduino. It seems i2C is quite finicky and, drops the bus immediately if there are any IO errors. Since what i am building is meant to be semi permanent, I am worried that i2C may not be the best choice.
Has anyone done any real world testing of i2C vs GPIO for RPi to arduino communication?

GPIO is too generic to compare to without being more specific; for example, you can (with some difficulty) implement I2C using GPIOs.  I2C reliability/recovery problems are likely more about drivers than peripheral blocks themselves.

Here are a few things to remember:

You should have a ground connection between the RPi and Arduino
I2C was meant for really short distances on a printed circuit board
Arduino runs at 5 Volt logic levels and RPi at 3.3 Volt logic levels - you need a level translator between them to make that work.

If the RPi and the Arduino are not far apart, I would say less than 1 foot (30 cm) and you have the grounds connected between the boards, then it is a software issue. I2C is meant for short distances any anything longer than a foot puts too much capaitance on the wires and starts causing unreliable communication. I would not even use it for more than a few inches unless it was on a circuit board where you control the capacitance.
I am assuming your using the Wire library on the Arduino side. On the RPi side I would use the the Adafruit I2C library for the RPi as I have had success using the library to communicate with I2C sensors listed on their site. Here is the link:
Adafruit RPi I2C Tutorial

Not sure there is such a thing as the 'Adafruit' i2c library. The instructions on the adafruit site are quite good, but really no different than those on half a dozen other blogs. Also I believe you are incorrect about needing a level translator if connecting just one device.

Sorry, I2C is not the library, I was thinking the smbus Python library they tell you to apt-get. That is what I installed for my RPi. As for the level translator - you should not put 5 Volt signals to the RPi pins as it will burn them out. It might take a little while, though in my experience I burn out a few GPIO with 5 Volt signals as soon as I turned power on. Take a look at this from the Raspberry Pi website: http://www.raspberrypi.org/documentation/hardware/raspberrypi/gpio/README.md

@tiger19tony72 is right. If its 5V, use 5V, if 3.3V use 3.3V. Specifications exsit for a reason :)


text:
Unable to send data from Processing to Arduino through ports
I'm just beginning to use Processing along side with Arduino and need help linking the two. Just to get started, I just wanted to send a single character (eventually strings) to the Arduino and have the Arduino light up a matrix if the Arduino receives the data.
Here's my code for the Arduino (I'm using an Arduino Uno):
#include <Adafruit_GFX.h>   // Core graphics library
#include <RGBmatrixPanel.h> // Hardware-specific library

// Set up the matrix
#define CLK 8
#define LAT A3
#define OE  9
#define A   A0
#define B   A1
#define C   A2
RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);

int incomingByte = 0;   // for incoming serial data

void setup() {

  Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  matrix.begin();
}

void loop() {
    if(Serial.available() > 0) {
    incomingByte = Serial.read();

    // Print a white "Done!" to the matrix
    matrix.setCursor(1, 0);
    matrix.setTextSize(0);
    matrix.setTextColor(matrix.Color333(7, 7, 7));
    matrix.print("Done!");

  }
}

And here's the code for Processing:
// Example by Tom Igoe

import processing.serial.*;

// The serial port:
Serial myPort;

// List all the available serial ports:
println(Serial.list());

// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[1], 9600);

// Send a capital "A" out the serial port
myPort.write(65);

I run the processing sketch and then upload the code to the Arduino, but get nothing. The Arduino is using COM3 and I believe the Processing sketch is too, but that may be where I'm messing up.
If I open up the serial monitor and send some data to the Arduino that way, then the LED lights up fine, but only when I do it through that.
Any help would be appreciated. Thanks!

Please specify what Arduino board you are using. Boards like the Uno reset when you open the serial connection and won't respond till the bootloader has exited. I believe it takes 1-2 seconds.

Just edited the post to specify, sorry about that. I'm using an Arduino Uno.

Your code seems to be assuming that the Arduino is on the first port of the list you fetch, which doesn't sound like it is the case.  Anyway, you should first make sure you can trigger your code with the serial monitor in the IDE.

I can easily trigger the code with the serial monitor. I've tried it with Processing going to Serial.list()[0] and Serial.list()[1] but have gotten no results either way.

What's the output of println(Serial.list());?

When you open a serial connection to Arduino Uno the atmega328 microcontroller is usually reset(this depends if the OS is configured to toggle the DTR serial control signal on/off when a port is opened). Just after a reset the bootloader (optiboot) runs to see if you are trying to upload a new sketch. If the bootloader doesn't receive any meaningful communication it will start your sketch after ~1 sec. All communication sent to the serial port while the bootloader is running is lost.
When you use the serial monitor you are too slow to notice the 1 second where the board won't respond to your commands. But the processing sketch is another story.
The easiest fix will be to insert a delay after you open the serial port and before you send any data.
// Wait 1.2 sec
int start = millis();
while (millis() - start < 1200);

If you would rather use a hardware fix you can connect a 10uF capacitor between RESET and GND pins that will prevent the board from being reset by the usb to serial converter.

The resest-on-open behavior is often a configurable property of the host operating system's serial device, but even if configured not to happen it easily could if the board is moved to a different install.

I updated the answer to be more speific


text:
Sniffing Bluetooth Packets
I'm attempting to create something similar in nature to the Ubertooth one. I'd like to sniff Bluetooth packets using the Arduino.
I've found a few nRF24L01+ wireless modules, which appear to operate on a frequency similar to Bluetooth LE. Unfortunately, I don't believe this will work for Bluetooth or BLE.
What would be the best way to sniff radio frequencies in the Bluetooth range from Arduino, am I on the right track?

You'd need access to the raw data in the 2.4 ghz spectrum. The arduino just isn't fast enough for that. You could use dedicated hardware like the Ubertooth, or you could connect a Software Defined Radio to your PC.  People are using a $20,- DVB-T TV tuner dongle based on the RTL2832U chipset for that.

Depending on what sorts of data you want to see (ie the more public parts before private ones are negotiated, if they even are in the cases of interest), you may be able to simply use a bluetooth or BLE chip.

@ChrisStratton I'm interested in the entire protocol, including the pairing proccess.


text:
How do I set Grove GPS to use A-GPS?
I am using a grove GPS http://www.seeedstudio.com/wiki/Grove_-_GPS
I attached the GPS to Serial1 of Arduino Mega 2560.
The baudrate of the GPS is set to 9600.
Library wise, I am using TinyGps to parse the GPS data.
The GPS receiver can only get a valid data if it can see a clear sky.
I read uBlox documentation and it states that I can use A-GPS.
So, my question is, how do I actually set the Grove GPS that is attached to my Mega, to use A-GPS?

A-GPS uses a network connection to download GPS almanac and ephemeris data to enable satellites to be located faster. Otherwise the GPS device has to wait for the data to be sent by a satellite, which may take up to 12.5 minutes. Alternatively, the GPS device can send noise GPS data to an assistance server which will process it and send back a fix.
A-GPS requires a network connection to an A-GPS server. You can't just 'turn it on'. There are some modules out there that combine GPS with a 3G modem which do A-GPS automatically.

In other words, are you saying that I cannot use A-GPS on the grove GPS? I do have the official GSM/GPRS shield attached to the mega too on top of the Grove GPS However.

You would have to find a server, see http://www.u-blox.com/en/assisted-gps.html

But then, how do I configure the Grove GPS on the arduino to use A-GPS?

I'm guessing it will be in the datasheet or app note for the UBlox chipset. A lot of work required.

If you connect your Grove GPS to a Raspberry Pi, it keeps track of the ephemeris data, so after rebooting you can find a signal quicker. eg. using gpsd package. If your Pi is last used in a different country, the stored data wont make sense, so it will have to wait for fresh data sent by the satellite anyway


text:
Bit mask first 2 bits of 16 bits for accelerometer
The datasheet for the accelerometer states that:

Here is the data output from the accelerometer:

I have tried to mask the first two bits using a bitwise AND command with B0011111111111111.
I tried to use this code, but unfortunately the first 2 bits are still "11" so the value has not changed:
int bresult=0b0011111111111111&result;
Serial.print(bresult,BIN);

How would I bits mask the first two bits and will arduino automatically know how to convert to twos compliment?
The variable result is of data type "long"
According to an answer, I tried:
int bresult= result<<2;
Serial.print(bresult,BIN);

I got this result which is great but is it possible to remove the last two zeros because this is making my value larger?
The image below shows result then bresult.

That's odd, as 0b0011111111111111&result; works as expected on my Arduino. I just tested it as I didn't know about the 0b... notation (I only knew B...)

Since it won't convert to two's complement if the sign bit is the 14 bit instead of the 16th, it would be easier to just shift the value left by 2. So
int bresult= result<<2;

Since <<2 is the same as *4 the result will be 4 times as high. So you need to divide the result by 4. Since you already have to multiply by 0.025 (or divide by 40), you end up having to multiply by 0.00625 (or divide by 160).

I tried to do this: int bresult= result<<2;
Serial.print(bresult,BIN);
However i still get 15 bits

Here is a screenshot : http://i.imgur.com/Ck35p4V.png

However, I am left with two zeros at the end of the value, making my value bigger. Is it possible to remove these two zeros? Here is a screenshot of result and bresult: http://prntscr.com/45j01c

Please re-read my answer, as already told you that would happen. Two extra 0s at the end means the result is 4 times too big.

For the arduino, long is 32 bits, int is 16 and char is 8.
Save the result in an int not a long. Then Gerben's method int bresult = (result << 2)/4 should work. This is because << 2 moves everything left two bits, but / 4 move every thing right two bits with new bytes the same as the sign bit. So you get a 16 bit signed variable with the correct number. If you have it as a long you would have to do
int bresult = (result << 18)/(2^18).
BTW Serial.print(bresult,BIN); is always going to give you up to 16 bits. There is no 14 bit type.

However, I am left with two zeros at the end of the value, making my value bigger. Is it possible to remove these two zeros? Here is a screenshot of result and bresult: http://prntscr.com/45j01c

As geo said, printing a result as binary will always show 16 bits. You will ALWAYS see 16 binary digits, no matter what. What are you trying to do with the output? If you need 14 bits of 1 and zero characters written to the serial output, you might need to write a custom function for that. It would be trivial to do.

@Hamoudy in the screen shot you haven't done the /4 yet.


text:
Arduino Yun, node.js and serial
I'm trying to bypass Bridge library and read serial directly from nodejs. I'm on the last sys upgrade (1.3) I have correctly installed nodes and serial module via opkg install. I have also commented out the line in the /etc/inittab:
#ttyATH0::askfirst:/bin/ash --login

This is my arduino code:
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("dudee");
  delay(100);
}

This is my node.js code:
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyATH0", {
    baudrate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
}, false);

console.log("hello");

serialPort.on("open", function () {
    console.log('open');
    serialPort.on('data', function(data) {
        console.log('data received: ' + data);
    });
});

serialPort.on('error', function(err) {
    console.log('error: '+err);
});

serialPort.open();

If I ssh to yun and run the script I don't see any "dudee":
~/test# node serial.js
hello
open

While if I open the serial monitor I see it.
If I run the node script on my computer (changing the right serial port name) everything works nice and I see the dude..
What can it be?

Autosolved thanks to this old forum post.
It is Serial1 not Serial.
In the Arduino code in the Yun Serial is a different object from Serial1. Even if it is not super well document (or at least not in the first dumb google search) here are some links that talks about Serial1:
https://www.arduino.cc/en/Tutorial/YunSerialTerminal
http://andrea-toscano.com/arduino-yun-tcpip-to-serial1-redirect/
http://crossbar.io/iotcookbook/Arduino-Yun-Disable-Bridge/

Thanks man, this was really helpfull, as I had the same issue.

@nkint would you like to elaborate how did the post help you? Your answer would be good for other seekers.

@ChetanBhargava: it is only a different object in the arduino side.. Serial is different from Serial1 int he Yun..


text:
Error uploading on Arduino Mega 2560
I'm completely new to Arduino, I bought a Rampos 1.4 and an Arduino Mega 2560 to build a Prusa Mendel 3D printer.
But when I connect the Arduino via USB to my computer, open the software and click to upload the blink example, it does anything and says Uploading to i/o board.
This happens when I use Arduino 0022 and then when I use Arduino 1.0.5 r2 that is the problem:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

I don't know what is happening, and I don't know what to do.

you need to read the extremely comprehensive getting started documentation on the Arduino website. this is off-topic here as it is way to broad to teach the basics and fundamentals of working with an Arduino. this is about specific solvable questions, not help teach me I don't want to read type questions.

I searched on Google during 2 hours until make that post, I'm not of that people you say. Now I'm searching that getting started that you said.

And @JarrodRoberson, I'm not english and I had several mistakes to write and I to read. Is that what I have to read? http://arduino.cc/en/Guide/Windows

I've done all the getting started, and it happened another time. I don't know what to do, now the port changed from COM12 to COM3, but it's still not working.

You need to select the proper board and port.

@TOMATO I've done it.

This question fits the subject scope of SuperUser better than that of StackOverflow.

Sorry I do not have the reputation to comment. I think your problem can be because you selected the wrong settings for your board. Check in Tools option, and make sure Board, Processor and Port is correct.


text:
How can I get two Arduinos to "talk" to each other?
I'm pretty new to this whole thing so please excuse my lack of familiarity with terminology.
I'm looking to build two "buzzers" of sorts. One will live on the ground floor and the other will live on the fourth floor. There is wireless internet as well as wired internet available to connect the two.
This is the basic idea. I might put more frills in later. Both buzzers have one button and one LED. I want it so that once a buzzer's button is pressed, the LED lights on both buzzers will light up. Then, only when buzzer two's button is pressed, will the LED lights on both buzzers turn off.
I'm pretty tied up on the two Arduinos communicating with each other. Is it possible to do something like that?

My favourite way to link devices together is to use these XRF modules, which you can get on ebay for £12 or less with an antenna. They talk to each other over long distances (upto 1000m with wire antenna) using a configurable encrypted messaging system (AES128 if I remember correctly), and they work for me really well. Easy to attach better antennae to them as well :)

Wired
Communication speed is not a factor - you only have to transmit an on/off signal. The simplest method would be to run a 4-wire cable, like a telephone cable, between the two.
The wires would be

GND
5V (maybe)
Ground floor output -> fourth floor input
Fourth floor output -> ground floor input

The steps are

Both wire 3 and 4 start LOW When ground floor button is pressed, ground floor led goes on, wire 3 is set HIGH.
Fourth floor is monitoring wire 3, when it goes HIGH, fourth floor led goes on, and    wire 4 is set HIGH
Ground floor is monitoring wire 4, when it goes HIGH, ground floor led goes off, and wire 3 is set LOW
Fourth floor is monitoring wire 3, when it goes LOW, fourth floor led goes off,    and wire 4 is set LOW
Ground floor is monitoring wire 4, when it    goes LOW, it begins waiting for a button press again.

Wire 2 can be used for 5V (or 3.3V depending on the Arduino) so that one of the devices can be powered off the other.
Wireless
The other option is to attach an RF transceiver to each Arduino, something like this would be good as it has 100m line-of-site range which you might need to get through 4 floors of concrete.
Learning
Start off with the simple wired method shown above. When it is working, connect wire 3 and 4 into the RX and TX pins and try to communicate using the serial port. Finally, move on to the wireless transceivers.

Benefits of a networked device:

Fairly fast because it has to be able to transfer large amounts of data
Can be compatible and used with computers, servers, and mobile devices. You might also only have to have one Arduino (if the second one would only be acting as a bridge between the protocol and the computer)
Why wouldn't you want to have a networked Arduino :)

So that rules out the protocols I2C, UART, and SPI. I find Bluetooth too hard to work with (it seems to have only a short range) using an Arduino. That leaves us with Wifi, wired network connection, and USB. USB would be best if you could run a short wire, but most USB peripherals aren't really designed to be used 100 feet away from the computer.
With ethernet and Wifi left, I'm going to advise you to go with a wired connection if possible. Benefits of keeping it wired:

Even faster (with lower latiencies)
Lower cost to interface with
More reliable than Wifi
No pesky Wifi passwords

tl;dr: Without a ton of info, wired internet (a.k.a. ethernet) seems to be the best choice.  Other wireless options don't provide the distance you need and you (probably) can't run a wire with another protocol.

Remember that for attaching 2 like devices like Arduino you'll need a crossover cable.


text:
Is it bad coding practice to design a buffer using pointers?
I coded a ring buffer for my Arduino to buffer data from either the SPI or TWI ports. In the .h file I used a pointer for the buffer:
typedef uint8_t *ring_buffer_t;
typedef uint8_t ring_count_t;
typedef uint8_t ring_index_t;
typedef uint8_t ring_size_t;

typedef struct ring_t
{
    ring_buffer_t buffer;
    ring_count_t  count;
    ring_index_t  head;
    ring_index_t  tail;
    ring_size_t   size;
}rint_t;

int ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size);

// other function prototypes to add and remove from the ring buffer

There is more code to handle adding and removing from the buffer, but I am simplifying here. Then in my .c file I have:
#include<string.h>

void ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size)
{
    r->buffer = buffer;
    r->size   = size;
    r->head   = 0;
    r->tail   = 0;
    r->count  = 0;

    // clear out the buffer memset cheaper by 12 bytes rather than for loop
    memset((void *)r->buffer, 0, r->size);
}

Then somewhere in code where the ring buffer is going to be used:
In SPI.h ...
#define MAX_BUFFER_SIZE 32
ring_t  rx_ring;
uint8_t spi_rx_buffer[MAX_BUFFER_SIZE];

#define MAX_BUFFER_SIZE 32
ring_t  tx_ring;
uint8_t spi_tx_buffer[MAX_BUFFER_SIZE];

In SPI.c ...
void spi_init( ... )
{
    ring_init(&rx_ring, spi_rx_buffer, MAX_BUFFER_SIZE);
    ring_init(&tx_ring, spi_tx_buffer, MAX_BUFFER_SIZE);

    // initialize other spi parameters
}

Are there any issues with my code that are obvious that I am not seeing? I ask because I ran the code and it works, but I feel I am doing something wrong. I can code in C and remember something about malloc() for dynamic memory allocation, just not sure if what I am doing qualifies. Or should this work creating a buffer of some defined size?
Thanks for any help or ideas.
EDIT: 07/27/2014 Added code to try and make what I am trying to do clear. Let me know, thanks.

Don't bother with malloc unless you need to. If you explicitly define your buffer before hand then you can use avr-size to check your SRAM usage.
Also the C compiler automatically adds code to initialise global variables to 0, so you don't need ring_init if your define the array explicitly. See https://stackoverflow.com/questions/2218254/variable-initialization-in-c for initialisation comments. Even if buffer was filled with non-zeros it wouldn't matter because it should be written to before being read from.
If you change the ring buffer from chars to ints, etc. you will have to change memset, as it assumes chars.
Will MAX_BUFFER_SIZE change? If not, you could put the buffer in ring_t.

Not enough info. You have a struct ring_t that has a pointer to an array of uint8_t's. In your ring_init method, your code assumes that the pointer points to valid memory. If you have not explicitly pointed the pointer to a block of memory, either stack memory or heap memory, then yes, there is a problem.
You COULD malloc the ring buffer, or you could create it as a global variable. If you've only got one ring buffer it's probably just as well to make the buffer a global and set the pointer in your setup method.

In my function ring_init the second argument "ring_buffer_t buffer" I expect an array to be referenced. So the first argument would be a ring_t struct, the second argument an uint8_t array, and the last argument would be the size of that array. Does that help?

Your description still isn't clear. Post the code that defines your ring_t struct, the array, and the code that calls the method.

I adjusted the code above to try and make it clear what I am trying to do. If you need it I can post all the code I have but we are talking  5 files and over 450 lines of code, though I could take out the comments and whitespace. Still would be looking at around 250 lines of code.

Simple answer: No, it isn't bad practice at all. I write with pointers all the time. Pointer referencing usually compiles to more efficient code than does array referencing.
But:
It looks like you've confused a pointer with the thing it is supposed to point to. The member you call 'buffer' is declared as pointer to unsigned byte. It doesn't appear to get initialized anywhere; it should be initialized with the address of an array of unsigned bytes (at least) as large as your ring buffer needs to be. I don't see this in anywhere in your code.
As others have described, the buffer could be allocated at run time with malloc() (but it's best not to save malloc() & free() for things you have to create and destroy on the fly; or direct the compiler to allocate it before your program gets control, with something like:
#define RINGBUFSIZE 32

uint8_t ring_buffer_memory[RINGBUFSIZE];

and initialize your pointer to it with:
r->buffer = ring_buffer_memory;

This will initialize your pointer to the first of (in this case) 32 bytes of zeroed memory reserved for the ring buffer. In your code, it's quite likely the pointer contains 0, thus pointing to memory location zero and is definitely not what you mean to do.
A word on variable names - adopt a convention for naming your variables that help a future reader (probably you!) understand/remember what that variable is for. In this case I'd probably use ringBuf for the array, and pRingBuf for its pointer. As a new reader of this code, I'd find it pretty inconvenient to have to have to remember that buffer is really a pointer (and what the heck was the buffer called!?).


text:
Arduino uno + XBee Shield Not transmitting when under battery power?
I have a few Arduino's along with XBee Shields communicating with one another.
The problem I'm having is that, when all the Arduinos+XBee Shields are powered via USB(PC) they seem to work fine and all transmissions get through to one another. But, when I use them with 9Volt batteries(fairly new batteries) the whole thing crashes and I never receive responses back from the battery powered ones.
I'm wondering if this is really a power issue? wouldn't a 9volt be enough to power a single arduino(uno)+xbee shield?

Using a multimeter you can confirm your theory by looking for a voltage drop on the power connections to the XBee and into the UNO.
9V batteries don't store much charge, nominally 563mAh according to wikipedia. It is possible that the fairly new batteries are not that new after all.
Depending on the XBee, power consumption varies. 40mA for a normal XBee (ZigBee), 200mA for pro, and 309mA when transmitting for the new XBee WiFi. If the battery is low, the high current draw plus internal battery resistance may drop the 9V output to below the 7V needed for the UNO's voltage regulator to function correctly.

The usb port on your computer can supply about 500mA of current. If geometrikal is correct about the 563mAh and you are using an XBee pro or a higher current draw radio, you could easily be hitting the current limit of the battery. Another aspect of this is the internal resistance of the battery. I'll let you read about it, but it is another current limiting factor. All of this boils down to once you are drawing more current than the battery can provide the voltage drops. Once it gets down to below what the Arduino board can regulate the microcontroller will reset.

Is space an issue? Have you considered using 6 AA batteries? From what I've read basically the current provided by a battery is determined by it's size so C is bigger than AA which is bigger than AAA.
The 9volt battery is from what I understand made up of 6 AAAA cells and therefore has a much lower maximum current. about 563mAh rather than about 1500mAh depending upon the type you choose.

Current is measured in A (amps) or mA (milli-amps). mAh stands for milli-amp hours. This refers to how much current can be drawn for a single hour. For example with a 500mAh rated battery you could draw 500mA for 1 hour or 250mA for 2 hours. mAh says nothing about maximum current draw, except for how fast the battery will be drained (if you know the current draw).

I know i was over simplifying things but does not the fact of a higher mAh not indicate that the potential current is higher? I guess i need to do more reading

It is solely an indicator of capacity. For example if the ESR (http://en.wikipedia.org/wiki/Equivalent_series_resistance) is low enough you could draw 1000mA from a 500mAh battery for 30 minutes.


text:
Can I control analog IO pins using Yun Linux
2 days back I bought Arduino Yun. I'm able to flash Led on 13 pin. And I'm able to flash Led on Bread board connected to A0. I'm able to run linux commands.
Now I want control A0 pin using Linux/Python program. Is this possible? I read many documents. But I didn't find thing related to this.
How I  can flash the LED using Linux programs?

Do you mean using the Linux side of the Yun or using a Linux computer?

@bersch - please undo your edit which changed the subject of the question.

There are several libraries which will do this for you. Basically, you should upload a special sketch onto the Arduino, which listens to the serial port, and performs the I/O that the Linux chip requests. Libraries which can do this are

Firmata
Autobahn
LininoIO

I haven't used a Yun before, but here is my understanding.
The Yun is really 2 separate computers with a bidirectional serial port between them.
The output pins are on the Arduino side. If you want to control Arduino pins from the LINUX side, you need to come up with a simple command syntax for communicating between the 2 computers and write code on both sides that supports that command syntax.
Say the command is:
digitalPinx=n;

Where x is the pin number, and n is a value, 0 or 1. (for digital pins). For a PWM output pin you could use a command analogPin and values of n from 0 to 255:
analogPinx=n;

On the LINUX side you'd just send that command through the serial port to the Arduino.
On the Arduino side, you'd write a loop that would wait for data to come into the serial port from the LINUX chip. If it gets data, it would read it into a buffer until it saw a semicolon.
Then it would break the data into separate lines using the semicolon as a delimiter, search for "digitalPin" or "analogPin", parse the data between the command and the semicolon for the values, and issue the digitalWrite or analogWrite command using those values.

how to send a command to from linux to arduino?

I don't know the specifics. I bet there are example sketches on the Arduino site that show you how to send data between the two processors though. You would need to write code for both sides that defines a command syntax. The Yun's LINUX processor would send a series of bytes to the serial port and that represented a command to the Arduino processor. The Arduino processor would listen on it's serial port, and when it saw the command, it would use it to change the state of pin A0.

I am looking for the same thing. The only thing I have come up with is that you can use the Bridge Library and use curl on the Linux side to read or write the pins

Could you develop your answer further, e.g. with sample code that shows at least where to start?

Bridge makes sense, but how would curl command help?

Suggest starting with the  the Mailbox examples in the Bridge library. Specifically the example
http://www.arduino.cc/en/Tutorial/MailboxReadMessage
Which shows how to transfer messages to the Arduino processor. It does discuss how to fire the curl process from the command line.

The simpliest thing I've found, is using the command "lininoio start"
then you can use nodejs with https://github.com/ideino/ideino-linino-lib and you no need to worry with the sketch part anymore, just javascript :-)
http://smag0.blogspot.fr/2017/07/smagyun.html


text:
Can't read from / write to SPI EEPROM
I'm currently trying to write to and read from an 25LC256-E EEPROM with my Arduino Uno via SPI. I've made a program which is supposed to do this, but I only get weird answers.
I'm sending in a Serial-string.
This string should start with 'w', 'r' or 'e', depending on what action I want to perform. The second character should be an int between 0 and 3 to determine witch PIN I should use as slave (currently I'm using only 1 slave, so the int should always be 0).
The rest of the string gets written to the EEPROM, one byte/character at the time.
What am I missing?
CODE:
    #include <SPI.h>

    #define WREN  6
    #define WRDI  4
    #define RDSR  5
    #define WRSR  1
    #define READ  3
    #define WRITE 2

    // Multiple slaves for future project
    const int CHANNELS[4] = {10, 8, 7, 4};
    String readResult;

    void setup() {

      Serial.begin(9600);
      channelSetup(); // Set all slave pins in CHANNELS to OUTPUT and HIGH

      SPI.begin();
      SPI.setDataMode(SPI_MODE3);
      SPI.setClockDivider(SPI_CLOCK_DIV2);
      SPI.setBitOrder(MSBFIRST);

    }

    void loop() {

      Serial.println("START");

      while(!Serial.available());
      delay(20);

      // Get all available bytes/characters
      String serialInput = getSerialStream(Serial.available());

      // Second character in serialInput is an int between 0 and 3
      int channel = makeValidChannel(serialInput[1]);

      // "channel" must be between 0 and 3
      // to be able to point to CHANNELS
      if (channel >= 0 && channel <= 3) {

        // First character decides what to do
        switch (serialInput[0]) {

          case 'w':
            writeToChannel(channel, serialInput.substring(2));
            break;

          case 'r':
            readResult = "EMPTY";
            readResult = readFromChannel(channel);
            Serial.print("Result: ");
            Serial.println(readResult);
            break;

          case 'e':
            overWriteEEPROM(channel);
            break;

          default:
            Serial.println("INVALID FIRST OPERATION");

        }

      }

      else
        Serial.print("INVALID CHANNEL: ");
        Serial.println(channel);

    }

    void channelSetup() {

      for (int i = 0; i < sizeof(CHANNELS); i++) {

        pinMode(CHANNELS[i], OUTPUT);
        digitalWrite(CHANNELS[i], HIGH);

      }

    }

    String getSerialStream(int numOfChars) {

      char serialStream[numOfChars + 1];
      int i;

      for (i = 0; i < numOfChars; i++) {

        serialStream[i] = char(Serial.read());
        delay(5);

      }

      serialStream[i] = '\0';
      return String(serialStream);

    }

    int makeValidChannel(char chIn) {

      int channel = chIn - '0';
      //channel -= 48;

      if (channel >= 0 && channel <= 3)
        return channel;
      else
        return -1;

    }

    void writeToChannel(int channel, String message) {

      int slaveselect = CHANNELS[channel];
      int i;

      // Write enabled
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WREN);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      // Disable Write Protection
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRSR);
      SPI.transfer(0);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      for (i = 0; i < message.length(); i++) {

        digitalWrite(slaveselect, LOW);
        SPI.transfer(WRITE);
        SPI.transfer(0);
        SPI.transfer(i);
        SPI.transfer(message[i]);
        digitalWrite(slaveselect, HIGH);
        delay(5);

      }

      // When writing of "message" is done,
      // add a 0-byte as terminating character
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRITE);
      SPI.transfer(0);
      SPI.transfer(i);
      SPI.transfer(0x00);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      // Enable Write Protection
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRSR);
      SPI.transfer(3);
      digitalWrite(slaveselect, HIGH);
      delay(5);

      // Write Disabled
      digitalWrite(slaveselect, LOW);
      SPI.transfer(WRDI);
      digitalWrite(slaveselect, HIGH);
      delay(5);

    }

    String readFromChannel(int channel) {

      Serial.println("Reading started");

      int slaveselect = CHANNELS[channel];
      char outputArr[64];
      int i = 0;

      while (true) {

        digitalWrite(slaveselect, LOW);
        SPI.transfer(READ);
        SPI.transfer(0);
        SPI.transfer(i);
        outputArr[i] = SPI.transfer(0x00);
        digitalWrite(slaveselect, HIGH);
        delay(5);

        if (outputArr[i] == 0x00 || i >= 64) {

          outputArr[i] = '\0';
          return String(outputArr);

                }

        else
          i++;

      }

    }

    void overWriteEEPROM(int channel) {

      char zeroArr[64];
      for (int i = 0; i < 256; i++) {

        zeroArr[i] = 0;

      }

      writeToChannel(channel, String(zeroArr))

    }

Don't know if this is the issue, but the else part of your if statement in the loop is missing opening and closing curly brackets....

@AnnonomusPenguin : No, but thanks for noticing. It's just a minor bug that causes Serial.println(channel); to run regardless of if/else.

"but I only get weird answers". That's kind of vague, could you give us some sample outputs?

@Gerben : I tested some more, and I think I found out what the "weird answers" were: I filled the first 8 adressfields of my EEPROM (using working demo code) with int values ranging from 59 and upwards, and when I tried reading the values later they printed out in ASCII. I.E., "59" became ";".

@DoTheGenes great work. So it's solved then!

@Gerben : Sort of. I've solved the mystery of what the weird answers was, but the readFromChannel() will not stop when the string i wrote to the EEPROM is read out, it just continues to read through all addresses.
Basically, the only reason it stops is because I put the i >= 64-condition in the if-statement. The null-terminator will not work as intended.

That's weird. Try adding Serial.print(outputArr[i], BIN) to see the individual bits being read. Check if there is indeed a 0x00 present.

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


text:
How to use two Sonar's
I'm using a single sonar, but I want to use two sonar to know another distance.
Here is how I use my single sonar:
    #include <NewPing.h>

    #define TRIGGER_PIN  9
    #define ECHO_PIN  10
    #define MAX_DISTANCE  100 // in CM
    ...
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
    ...
    delay(100);
    unsigned int uS = sonar.ping();
    int cm = uS / US_ROUNDTRIP_CM;

But I Want to use a second one to calculate another distance, how to?
#define TRIGGER_PIN_2  11
#define ECHO_PIN_2  12
...
new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE);
...
???

Thanks in advance
EDIT:
Maybe this one, I'll try this when I will get my second sonar
#define SONAR_NUM     2
#define MAX_DISTANCE 200
...
NewPing sonar[SONAR_NUM] = {
  NewPing(9, 10, MAX_DISTANCE),
  NewPing(11, 12, MAX_DISTANCE)
};
...
delay(100);
unsigned int uS1 = sonar[0].ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar[1].ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

Who's sonar device are you using? Can you provide a link to the website?

@Duncan: I used this kind of untrasonic sonar http://www.hitronics.net/image/cache/data/Arduino/Ultrasonic%20Module/F90JYNWH7UR7RCS.LARGE[1]-500x500.jpg, and And I found Library here: https://code.google.com/p/arduino-new-ping/, http://playground.arduino.cc/Code/NewPing .

Thanks for the reply. Can you send a link to a source of the module rather than just a picture of it?

@Duncan : source is here: https://code.google.com/p/arduino-new-ping/downloads/list

Maybe this one, I'll try this when I will get my second sonar

Ding ding ding! Yeah, this would be one way to do that. That creates an array so you can reference the sonar with sonar[i], where i is either 0 or 1 for the first or second number.
For only two sensors, it might be easier just to do something like this:
NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

Then you can run the other code like this:
delay(100);
unsigned int uS1 = sonar1.ping();
int cm1 = uS1 / US_ROUNDTRIP_CM;

unsigned int uS2 = sonar2.ping();
int cm2 = uS2 / US_ROUNDTRIP_CM;

A little less code to read, whichever one you want.
The reason you can do this is you can replace the sonar with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it Arduino_Sonar if you wanted to.
The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do int numbers[500]; to declare them. An array might be more useful if you're expanding your circuit, but either is correct.

@Annonomous : Thanks, What a great price! I prefer your version, only two sonar's :-) Thanks for the support!


text:
Unstable reading from pushbutton on digital pin
I use the Pin 7 to get the status of a push button. I put 10Kohm R on the - .
The status is unstable because arduino says thet I push it but it is not true...
int button = 7;
...
// var for reading pushbutton value
int buttonState = 0;
...
buttonState = digitalRead(button);
  if(buttonState == HIGH)
  {
    myFunction();
  }

EDIT :
ARDUINO PIN 7 <---> R 10Kohm <--> [switch] <---> VCC

It sounds like you may have connected it incorrectly. Can you show a diagram of your circuit?

@Peter: thanks, I didn't use the GND like here: http://arduino.cc/en/uploads/Tutorial/button.png This looks like to be the mistake isn't it?

At the moment, your resistor isn't doing anything useful. When your switch is open, the pin is still 'floating', which means it's ending up with random stray readings from nearby electromagnetic fields.
You basically need two connections coming from your Arduino pin. One goes through a resistor straight to ground. The other goes through your switch straight to +5V.
In that case, the resistor is acting as a pull-down, because it holds your pin at Ground whenever the switch is open. You could swap over the ground and +5V, and it the resistor would function as a pull-up instead.
This question deals with the same kind of issue:

Button state changing randomly

thanks, it looks like a good asking, I'll try this in a few hours but I'm sure it will work :-)

Note that the arduino already has pull-up resistors for all the pins inside the chip. You just need to enable them. See DuncanC's answer to see how.

Note that you can also activate the internal pull-up resistor on the pin by first making it an input, then setting it to HIGH.
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);

EDIT:
Based on info from Craig (in the comments below) it's simpler to use the new pinMode INPUT_PULLUP:
pinMode(pin, INPUT_PULLUP);

Then wire the switch directly to ground.
This is the simplest way to wire a pushbutton to an arduino (no resistor needed) but do you need an extra line of code.
Also, the pin will read as HIGH when not pressed, and LOW when pressed (which might seem counter-intuitive)

I'll try this method! Thanks for the tip :-)

Glad to help. Remember to up-vote if it helps, and accept the best answer. (@PeterR.Bloomfield's answer above is probably the one you should accept since it directly addresses the problem with your circuit. My answer is more of a follow-on alternate approach.)

You can now configure the internal pull-up with pinMode(pin,INPUT_PULLUP) without the need for digitalWrite.

Cool. What are the IDE/Arduino version requirements to support that?