text:
arduino - millis()
Copied from the Arduino reference - millis()

Tip: Note that the parameter for millis is an unsigned long, errors may be generated if a programmer tries to do math with other
  datatypes such as ints.

What kind of math? What kind of other type of processing is excluded while working with millis?
Could someone clarify this statement and/or give some example?

Whenever you write an equation in C/C++, the data types being operated on have a very real effect on the equation's output.
Each type like int, float, and unsigned long have different behaviors, and take a certain amount of space in memory to store.
int (on arduino) is store in 16 bits, with half of its values being given to negative numbers, half-1 given to positive values, and one value given to 0. That gives it a range of -2^15 (-32,768) to +2^15-1 (32,767).
unsigned long (on arduino) is 32 bits, but none are designated as negative. its range is then 0 to 2^32-1 (4294967295).

What kind of math? What kind of other type of processing is excluded
  while working with millis?

The crux of the issue is that it the time millis returns ever got past 32767 and you tried to store it in an int, the arduino couldn't do it, because an int can't hold that big of a number. The type of math this is off limits is math happening to smaller data types, not any specific operations. Maybe these examples will help:
  int i = 32767;
  Serial.println(i);
  //No problems here; it fits just fine

32767

  i = 32767 + 1;
  Serial.println(i);
  //Oh no, the value didn't fit

-32768

  unsigned long fake_millis = 42000;
  i = fake_millis;
  Serial.println(i);
  //This is an example of millis going past an int

-23536

  i = -10;
  unsigned int j = i;
  Serial.println(j);
  //no way to put a negative number in an unsigned value

65526

  uint32_t k = fake_millis;
  Serial.println(k);
  //unsigned long is a uint32_t on arduino; this works great!

42000

The way this is implemented is really quite genius; If you are interested in where these numbers come from and why they spill over in the way they do you should look into same explanations of two's complement number representations.

Just a simple question: Declaring "unsigned long fake_millis;" equals to "uint_32 fake_millis;" ?

Yes, those are equal on the arduino. The difference is unsigned long can change with different platforms (eg x86), uint32_t will always be 32 unsigned bits everywhere.

It should be noted that your second example (32767 + 1) yields undefined behavior, which is almost always a bad thing. Your other examples are documented behavior you can rely upon.

millis() returns a unsigned long, which is a 32-bit unsigned integer on the Arduino. When you then try to do something like unsigned int time = millis() - 1000, you try to store that in a 16-bit unsigned integer unsigned int. A 16-bit integer can never hold a 32-bit value.
According to the C specification, paragraph 6.3.1.3, the upper 16 bits are discarded.
If possible, keep the millis() output in a unsigned long and only use data types with less bits when you're absolutely sure you will not lose bits.
There's more information on explicit casts in C here: https://stackoverflow.com/a/13652624/1544337

Thanks for the edit. I removed the reference to uint32_t as it's something different. uint32_t guarantees that you have a 32-bit unsigned integer, unsigned long doesn't (although on Arduino it is). I also already mentioned that it's a 32-bit type.

Then wouldn't you say its more correct to say it returns an uint32_t which happens to be an unsigned long on arduino?

@BrettAM according to the docs this function returns an unsigned long.

Removed old comments, since the whole discussion makes little sense with the current version of the answer. Just keeping this for the record: if the conversion is to a signed integer (int time = millis() - 1000), the result is similar: the upper 16 bits are discarded. This time the C standard says the result is implementation-defined, and the behavior is specified in the gcc documentation on the implementation-defined behavior of integers (fourth bullet point).

When you want to do stuff with millis() just remember to initialize your variable with type "uint32_t"
So do something like "uint32_t last_millis" where you will store the output of the "millis()" function.
Otherwise like the others said, it would overflow when going past 31,000 which will happen pretty quickly.


text:
How to forward sms using arduino uno + gsm shield
hey there I'm new to arduino. I'm working on a project that needs to send an sms to get a response and forward the response to another mobile.
What is the easiest way to do so

Why do you want to involve an arduino in this?

source: Stack Exchange

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

sort: votes


text:
Trying to track down macro or #define values, possibly in arduino preprocessor
In reading various code I stumble across symbols that seem to be the result
of #define or other macro like symbols that I cannot find just by tracking
through the code ( including its chain, if any, of includes ).
Can someone offer some reasonably simple, but complete, guidance on how the
arduino ide works with especially emphasis on automatically included files
( and their location ) and any other automagically appearing stuff.

The Arduino IDE handles very few of these itself. Try looking at what AVR-GCC does.

On Linux, I usually just grep -l FOO /usr/share/arduino/hardware/arduino/cores/arduino/*.h or grep -lr FOO /usr/lib/avr/include/.

Most of the #defines happen an Arduino.h and the board  variant files, although a few are passed as compiler arguments if you still can't find anything.

I usually do a search on the github page (https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/cores/arduino)

Arduino inclusion is dark magic mixed with randomness... I haven't been able to find a consistent include "scheme" for Arduino, although I haven't poked around in the source.

It might help to point out the use of -D switches of gcc here.
If you turn on verbose output of the Arduino IDE (I am using a pretty old version):

you will see, when you compile a sketch, that the compiler is not only called with a switch -m (e.g.  -mmcu=atmega328p) which describes the target (i.e. the ATMEL AVR instruction set or MCU type) for which the code is compiled, but also with a number of -D switches.
The -D switches predefine a name as a macro and also that depend on the target.
You might see for example
-DF_CPU=16000000L -DARDUINO=100

where F_CPU is used to pass information about the target's clock speed (16 MHz in this case) to code that depends on this, e.g. the delay function or the Serial library.
3 ways to define macros
In general, the confusion might come from the fact that including files in the Arduino build chain depends a lot on compiler flags, and there are several ways to define these:

#define
using -D switches
from the target specification (compiler built-in, -m)

The last point means that the above mentioned -matmega328p defines the macro __AVR_ATmega328P__ which is e.g. used in io.h to include the appropriate file with pin mappings, RAM sizes etc. (Google for avr-mcus.def to find a full list of these predefined macros for AVR targets.)
Finally, note that the Arduino IDE also sets include paths depending on the target. The appropriate set of pin definitions is selected by passing an include path like this to avr-g++:
-I/usr/share/arduino/hardware/arduino/variants/standard

where standard is replaced by leonardo, micro, mega etc.
Short answer / summary / how to debug
First, to generate a list of the current #define directives, use the -dM option like this (compiling an empty program that is specified to be C with -x c):
echo | avr-gcc -x c -E -dM -mmcu=atmega328p - | sort

Change -mmcu=atmega328p to your needs (you can also leave it out).
Second, you can use the option -g3 to include the macro definitions in the output. Keep the intermediate files by using -save-temps. You can append these to the compiler call by the IDE:
avr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega168 -DF_CPU=8000000L -DARDUINO=100 -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard /tmp/build5017602110288.tmp/SerialManual.cpp -o/tmp/build5017602110288.tmp/SerialManual.cpp.o -save-temps -g3

which will create a long output file *.ii (here SerialManual.ii) that lists among others the defines and typedefs and, most importantly, from which files they come.
Sample output:
# 1 "/tmp/build501760211028815624.tmp/SerialManual.cpp"
# 1 "/tmp/1//"
# 1 "<built-in>"
#define __STDC__ 1
#define __cplusplus 1
#define __AVR_ATmega168__ 1
#define __CHAR16_TYPE__ short unsigned int
...
# 1 "<command-line>"
#define F_CPU 8000000L
#define ARDUINO 100
...
# 1 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 1 3
# 34 "/usr/lib/gcc/avr/4.5.3/../../../avr/include/avr/iom168.h" 3
#define _AVR_IOM168_H_ 1
#define SPM_PAGESIZE 128
#define RAMSTART (0x100)
#define RAMEND 0x4FF
#define XRAMEND RAMEND
#define E2END 0x1FF
#define E2PAGESIZE 4
#define FLASHEND 0x3FFF
...

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


text:
Why won't Wifi Shield detect any networks? Even really close
I just purchased an Adafruit Wifi Shield CC3300 and strapped it onto my Arduino Uno board.
I'm running this basic sketch that I found to test the functionality of the Wifi Shield: http://arduino.cc/en/Guide/ArduinoWiFiShield#toc1
Of course in my home I have Wifi, so I expected this sketch to show my Wifi name. However it doesn't. Instead I get this output on my serial monitor:
Init...
** Scan Networks **
Initializing Wifi...
MAC: 0:0:0:0:0:0
Scanning available networks...
** Scan Networks **
number of available networks:0
Scanning available networks...
** Scan Networks **
number of available networks:0

It just keeps going forever detecting zero networks.
I even took the Arduino and stood 3 feet away from my Wifi router. Still nothing.
I even tried making my cell phone a Wifi hotspot and holding it right next to the Arduino. Still nothing. And why does it say the MAC Address 0:0:0:0:0:0?
Can anyone suggest a fix?
FYI, here is a photo of what my setup looks like:

Do you know if the Adafruit wifi board is compatible with the Arduino wifi shield libraries? Adafruit provides their own libraries on their tutorial page here: https://learn.adafruit.com/adafruit-cc3000-wifi?view=all#download-the-library I would try using their code with their hardware first.

Also what's up with the headers floating, are they even soldered to your WiFi shield?

Was this ever solved?  I'm having the same issue with an Arduino Uno and the Wifi/SD Shield.


text:
Using ethernet, how do I navigate to a page on my local server
I want to access the following page on my local using my Arduino with ethernet shield"  192.168.1.2/zombie/arduino.php.  My arduino is conencted to a PC through a router. The system keeps timing out
I am using the following code:
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
char server[] = "192.168.1.2/zombie/arduino.php";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

"localhost" means the loopback interface (ie, 127.0.0.1), and so by definition cannot be accessed from any other system.  You have a local server (presumably on the same subnet as your Arduino), not a "localhost" one.

I discovered the answer after some testing.
The server var:
char server[] = "192.168.1.2/zombie/arduino.php";

should only contain the ip address.  So it should look like this:
byte server[] = { 192,168,1,2 };

The additional URL elements should be added using:
client.println("GET /zombie/arduino.php");

after a connection has been established
The final code should look like this:
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
byte server[] = { 192,168,1,2 };

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println("GET /zombie/arduino.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}


text:
Powering an Arduino Mega with external USB Power Bank?
I am making a robot with arduino mega r3. I want to power the arduino with a usb power bank. How should I do that?

Did you try plugging it in?

Plug USB power bank output into Arduino USB port. Done. [BUT see madanon's comment re the need to dra a minimum current level in some cases to keep powerbank output alive].

I know that I am not supposed to post this, but @IgnacioVazquez-Abrams, thank you sir. I love your sense of humor :D

I have a "USB power bank" with two USB ports, which I use to power some projects.
I have discovered that my bank (i.e. your mileage may vary!) shuts off unless my project draws at least 50mA. If your project does draw at least that at ALL times, you should just be able to plug a USB cable directly from the powerbank to the project.
For some other projects, I have bought a USB cable (USB A to USB A) which I cut in half, stripped the wires, then used a multimeter set to "Volts" to work out which wire was +5V and which was GND; I connect these straight to the 5V/GND on my project. To make sure at least 50mA was drawn at all times, I put a 100 Ohm resistor from +5V to GND (at LEAST 1/4 watt!!). This obviously wastes a lot of power (turning it into 1/4 watt of heat), but it keeps the power bank "awake". By using a USB A to USB A, I now have two cables.
My power bank also has a "torch" (led) integrated; if the torch is on, it also stays awake.

+1 Quantification if minimum current requirement is useful.

Thanks! This solved my problem. I tried powering an arduino with a power bank and it kept shutting down every X seconds, unless I turned on the LED on the power bank. In that case it continued working until the led went out. Now I know why :)

@RussellMcMahon, the 50mA figure is probably not useful, as it will vary from model to model. Gives an idea though :)

Powerbank is a term for those external batteries that output USB. Usually used to recharge a phone when you don't have access to wall outlet and USB charger.
Inside powerbank:
Battery (3.7v) --- Some Circuit --- USB female
How to:
You have a bank
You have USB cable
ugh! ...
Plug USB to Arduino and you are (pretty much) done.
For those who use ProMini and/or want to skip the USB port
Cut the USB cable and take the red (+) and black (-).
Put it directly to Vin and Gnd and you are good to go.
*
Unfortunately for us (fortunately for most) most Powerbank has auto-shutoff where it will shut off the power if there's no load (usually ~50mA, vary with every brand). Since Arduino may not draw that much, the battery thinks it is not connected to anything.. thus it will auto-shutoff after a while
I found this trick helps (a lot!! thank you!):
https://www.dorkbotpdx.org/blog/paul/battery_pack_load

Not clear what a usb power bank is. I assume you actually have a battery, perhaps with a regulator. The data sheet
http://www.arduino.cc/en/Main/arduinoBoardMega at says: Microcontroller ATmega1280 Operating Voltage 5V Input Voltage (recommended) 7-12V Input Voltage (limits) 6-20V Digital I/O Pins 54 (of which 15 provide PWM output) Analog Input Pins 16 DC Current per I/O Pin 40 mA DC Current for 3.3V Pin 50 mA
also
The Arduino Mega can be powered via the USB connection or with an external power supply. The power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter (wall-wart) or battery. The adapter can be connected by plugging a 2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER connector.
The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.
If you use the usb connector, use the correct pins an make sure you have it regulated to 5 volts.
I think this answers the question, if not please comment.


text:
How do I send a string to master using i2c
I want to write an Arduino program that simply recieves a string (via the I2C wire library) from a master Arduino, then waits for a request, and sends that string back.
Here is my code:
#include <Wire.h>

void setup()
{
  Wire.begin(4);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);
}

String data = "";

void loop()
{

}

void receiveEvent(int howMany)
{
  data = "";
  while( Wire.available()){
    data += (char)Wire.read();
  }
}

void requestEvent()
{
    Wire.write(data);
}

I read in the API that the write() function accepts a string, but I keep getting a "No matching function for call" error.  I tried to simply replace
Wire.write(data);

with
Wire.write("test");

and that worked without error.  Why is this the case?

Try this instead of wire.write(data); wire.print(data);

data is a String. "test" is a char*. Wire.write() has no prototype that takes a String.
Wire.write(data.c_str());

working perfectly :)


text:
How does the Arduino send more than 6 bytes via I2C
I have been working with the wire library (I2C) to send data from one Arduino to another.  I read that the Arduino can only send 6 bytes per cycle, but I have been able to transfer much larger strings.  This code works without error:
  Wire.beginTransmission(4); // transmit to device #4

  for(int i = 0; i < 20; i ++){
    char rand = random(65, 100);
    Wire.write(rand);
  }

  Wire.endTransmission();    // stop transmitting

How is this possible?  It seams that 32 characters can be sent without trouble.
I read this here: http://arduino.cc/en/Tutorial/MasterReader

Arduino 1, the Master, is programmed to request, and then read, 6 bytes of data sent from the uniquely addressed Slave Arduino.

Now that I look at this again (after reading the responses) I think that the limit was set in the code sample.

Please post the code that doesn't work.

Can you link to where it says the arduino can only handle 6 bytes per cycle? And, by 'per cycle' I assume you meant between the 'beginTransmission and endTransmission'. I couldn't find reference to the 6 byte limitation in the wire reference ( http://arduino.cc/en/Reference/Wire )

Can you give the sample code for it

There is no reason to believe there is a 6 byte limit.
The Arduino Reference makes no mention of a 6 byte limit.
The Wire.cpp defines 'txBuffer[BUFFER_LENGTH];' where BUFFER_LENGTH = 32 (defined in Wire.h). The maximum is 32 bytes, just as you noticed.

in the wire code examples, the master uses beginTransmission() and endTransmission(), but the slave does not.  The slave only uses write().  why is this?  How does the Slave know when to end the transmission?

@Hoytman I'm actually not sure why the library handles i2c that way. I would expect that it has its roots in making a generic i2c/twi interface, but I don't understand i2c/twi well enough to give a correct answer.

In the Wire library, beginTransmission() "primes" (starts) collecting data for a transmission. Then Wire.write() simply adds data to an internal buffer (which is 32 bytes long). Finally the endTransmission() actually does the sending of the buffer. As for the slave, in a "requestFrom" function as soon as you do a Wire.write() it is sent (or at least, it commences to be sent). You cannot (successfully) do more than one. If you attempt to, the second one overwrites the buffer used to return the data to the master.

The Arduino Wire implementation is synchronous (blocking) but still requires an intermediate buffer. As the answer about states the buffer is limited to max 32 bytes. This alternative I2C (Two-Wire) library does not have this limit and supports both software and hardware bus manager implementation. https://github.com/mikaelpatel/Arduino-TWI Device drivers written using this library can be used with the AVR/SAM hardware support or with any GPIO pin.


text:
Detect external ground on an input pin
I am making a bike alarm for my bike. I haven't started yet.
Basically, I'm thinking of a pin to be connected to the metal post (to which the bike is locked.) I want to detect if that connection (to the ground via the metal post) is broken.
Is that possible?

If there is another connection from there to the Arduino's ground, and if you have an internal or external pullup resistor on the pin, then yes it should be straightforward.

I only want one 1 single wire from arduino to detect ground, not two/a loop

That's not going to work very well.  You could try something with captive sensing but it is likely to be unusably sensitive to false alarms (wind, rain, other bikes in proximity, even current leakage via tires wet with road anti-icing brine, etc).  The whole project is a bit impractical anyway - how will you protect against disconnecting the power source?

Well I was considering the fact that the thief could connect the wires directly excluding the post so preventing an alarm at all. Do you have any suggestions?

@ZeeshanAhmad do you use a chain, wire, or a bike lock to lock up your bike? If so, you could use the metal of the chain/wire/lock to form a circuit. If the circuit breaks (the thief cuts the chain or opens the lock), then we know to set off the alarm. Just a thought

But the lock is itself just one piece, so I can't defer between a locked and a broken/unlocked state. It is one piece of metal conductor.

How about fastening a wire to the post, and then the other end, on the bike, goes into a "jack" (the sort of thing you plug headphones into). With the wire inserted, it makes a connection, and the Arduino knows the wire is there. As the thief steals the bicycle the plug (or loose wire) is pulled from the jack, breaking the connection. i.e.

I will have to try this, and see how it goes


text:
How to increase the detection distance on Arduino KY-032 obstacle Avoidance sensor?
We've got an Arduino KY-032 obstacle avoidance sensor, and have spent a decent time searching and researching to find a detailed data sheet/manual to figure out how it works; but there aren't any detailed information on the module.

One of the few instructions here says that the potentiometers on the chip are used to adjust the distance, but I've tried all different settings and the maximum I can get is 10 centimeters. I've tried different surfaces with different reflectivity levels, but it doesn't really differ much.
Any idea how to increase the distance on this? Anything to do with the enable jumper?
Update: Here's the related code to the obstacle detection:
void loop() {
  // check the network connection once every 10 seconds:
  val = digitalRead (buttonpin) ;// digital interface will be assigned a value of 3 to read val
  if(full==1 && val==LOW) {
    Serial.print("Bin Full");
    delay(5000);
  } else {
    if (val == LOW) {
      // When the obstacle avoidance sensor detects a signal, LED flashes
      digitalWrite (Led, HIGH);
      delay(2000);
      if(digitalRead(buttonpin)==LOW) {
        delay(2000);
        if(digitalRead(buttonpin)==LOW) {
          full = 1;
        }
      }
      count++;
      //printCurrentNet();
      sendData();
    } else {
      digitalWrite (Led, LOW);
      if(full==1) {
          count = 0;
      }
      full = 0;
    }
  }
}

It could be code related. Can you add small snippet of your code (excluding anything unrelated to this issue)? Thanks!

@AnnonomusPenguin There you go. (:

It may just be defective.  Have you tested duplicate sensors? It may also just be low quality product.  Have you tried contacting the manufacturer?

How about this- test the sensor WITHOUT the Arduino Uno.

How did you connected it to arduino?

@Pedro What do you mean how we connected it to Arduino? We were using an Intel Galileo board and programming it with Arduino. There are tutorials if you look up.

The IR sensor module incorporates an internal 38KHz bandpass filter. The pot near the GND pin fine tunes the frequency of that signal, which is used to illuminate the IR LED.
The other pot adjusts the duty cycle of the signal. This controls the brightness of the IR LED.  Both adjustments effect the sensitivity and range of the device.
To achieve maximum sensitivity, it is absolutely necessary to use the 'EN' or 'Enable' pin.  When used correctly, however, additional optical shielding of the IR LED is required.  This can be done with a small cardboard tube commonly used as packing material or any of a variety of other materials.
If the Enable function is not used, the jumper must be installed on the board. The Enable pin cannot be used if the jumper is in place.
For more information, see: http://irsensor.wizecode.com/

The wizecode page has some nice info. However the R5 pot (near the EN jumper) does not change the duty cycle but directly the current to the IR LED - still affects the brightness though. Too much current seems to trigger false positives - depends on your additional optical shielding. I put some black heat shrink tubing over the sensor - with a hole punched in for the sensor to see though.
Also the R6 pot does not really "fine tune" the frequency, more like "coarse tune" - even a small nudge can detune by a kHz, greatly reducing the sensitivity.
If you use the EN jumper, a suddenly appearing object gives a short pulse, but then the disturbance signal suppression kicks in turns sensitivity down and 'unsees' the object. Also slowly appearing objects are not recognized for that reason. Only very near objects (a few cm) give a strong enough signal to overcome that sensitivity attenuation.
What I found somewhat irritating: Setting EN to LOW lets the IR LED steady on instead of off, which I would have expected. That might irritate the sensor more than necessary. Also draws more power (maybe even a lot, depending on R5 current setting).
Funny enough, you can get a somewhat analog behaviour from this sensor if you measure how long it takes from activating the EN pin to the sensor output getting low. The nearer the object is, the faster it reacts. Near objects take ~190us, farther objects more than 400us. Not nearly a linear behaviour though. Also depends on distance, size, angle, IR reflectivity and IR LED power.
However it can detect a person in more than 1m distance.

These Obstacle sensors don't always work as expected.I bought 3 of them, but only 2 worked properly.The other only worked to a distance of about 6-7cm.
By the way, the code seems to be fine, but there is no way to tell for sure without complete code.

Check This: http://irsensor.wizecode.com/

When the GREEN JUMPER is installed on the board (see picture), the IR LED will flicker continuously at 38kHz.  If the Enable (EN) function will not be used, the jumper must be installed .  When the jumper is removed, pin 4 of the 555 timer is held LOW (RESET) by R3, a 22K pull-down resistor. Then, if a HIGH condition is applied to the EN pin, the reset condition will be relieved and the 555 timer will begin to oscillate. The Enable function cannot be used if the GREEN JUMPER is in place.  You must remove the jumper on the board in order to use the EN (Enable) pin.

Well, the range of the sensor should be: "2-40cm"
I would suggest using the code below and changing the potentiometers to see if it makes any difference.
int Led = 13 ;// define LED Interface
int buttonpin = 3; // define the obstacle avoidance sensor interface

void setup ()
{
  pinMode (Led, OUTPUT) ;// define LED as output interface
  pinMode (buttonpin, INPUT) ;// define the obstacle avoidance sensor output interface
}
void loop ()
{
  if (digitalRead (buttonpin) == HIGH) // When the obstacle avoidance sensor detects a signal, LED goes on.
  {
    digitalWrite (Led, HIGH);
  }
  else
  {
    digitalWrite (Led, LOW);
  }
}

I wouldn't think that's required, it's very likely that the Sensor is malfunctioning.

@Mathsman100 But it is a way to prove so?

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


text:
Atmel Studio and Arduino IDE compiles the same code different
Before going in details I need to say I am trying to program Arduino Nano board with atmega328p.
Here is my code in Atmel Studio;
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;

ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}

int main(void)
{
    //DDRB |= (1 << PORTB3);
    //DDRD |= (1 << PORTD3);

    DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
        while(1)
    {

    }
    return 0;
}

And here is the code in Arduino IDE;
#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>

int received;
int pinState = 0;
ISR(USART_RX_vect)
{
    //cli();
    while(!(UCSR0A&(1<<RXC0))){};
     //clear the USART interrupt
    received = UDR0;
    UDR0 = received;
    //sei();
}
void setup() {
 DDRD = 0xFF;
    DDRB= 0xFF;

    #define F_CPU 16000000

    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);

    TCCR0A |= _BV(WGM00) | _BV(WGM01) | _BV(COM0A1);
    TCCR0B |= _BV(CS02);

    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);   // Turn on the transmission, reception, and Receive interrupt
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //DDRB |= (1 << DDB1)|(1 << DDB2);

    sei();
}

void loop() {
           // wait for a second
}

As you can see these codes are exactly the same (except the setup-loop format)
Now I am using exact same parameters for AVRdude;
-CF:\arduino-1.0.6\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -P\.\COM9 -b57600 -D -Uflash:w: and following the hex file that is created after compile. But when I examine the verbose output of avrdude.exe they are different.
Arduino program works but the program uploaded using Atmel Studio does not. For more information everything about avrdude and parameters are working and it uploads and doesnt give any errors.
I chose atmega328p in Atmel Studio which is correct because I am using arduino nano board.

In arduino the init function is called

Just to help identify the problem: try to put the Atmel Studio version in the Arduino IDE. In principle you do not need to use the setup-loop format in Arduino: you can provide your own main(), and it will override the one from libcore.

I found the solution (or what the problem is). Avrdude not only requires MCU model but also programmer parameter. If you are using any of Arduino based boards you need to add -c programmer id do avrdude input parameters.


text:
Arduino Yun USB host - reading usb MIDI data and passing forward to another device
I am starting simple, but for some reason I cannot find any examples online and I stuck with my task.
I have a usb midi keyboard, Arduino Yun, and a synthesiser that can accept midi via usb. The problem is that the synth doesn't send a voltage through its usb and the keyboard has only one usb that is used to send midi data and it's powered via it at the same time.
My idea is to use my Yun's USB host (which sends voltage too) to power my midi keyboard and grab all incoming midi data from the keyboard, then simply pass it unchanged through to my synth.
Where do I start? Do I need some python code for it or everything can be done with sketch code? I've done few arduino projects but I am new to usb host functionality  . This is my first step, later I would like to also convert usb-midi to 5-din-midi (old school connection), but that's different story.
Can you guys help me and point into the right direction? Anyone done something similar on Yun? I've seen some examples done on different boards, but it's all overcomplicated, I need simple read/pass usb solution. Thanks!

If the problem is simply power, you are far better off making a power injection cable than trying to proxy things through software.  Only resort to that if there are other things you need to do as well.

If you are going to try and sniff USB, don't even start. It's not ever going to happen at your skill level. USB is a very very complicated software stack to even get "hello world" working. If you are dealing with pure midi signals, this is a different story. MIDI is very simple and there are tons of guides

You need the USB Audio kernel driver and the aconnect utility:
$ opkg update
$ opkg install kmod-usb-audio
$ opkg install alsa-utils-aconnect

Then just connect the ports:
$ aconnect -lio
client 0: 'System' [type=kernel]
    0 'Timer           '
    1 'Announce        '
client 14: 'Midi Through' [type=kernel]
    0 'Midi Through Port-0'
client 40: 'SC-8820' [type=kernel]
    0 'SC-8820 Part A  '
    1 'SC-8820 Part B  '
    2 'SC-8820 MIDI    '
client 44: 'My Little Keyboard' [type=kernel]
    0 'My Little Keyboard MIDI 1'
$ aconnect "My Little Keyboard" SC-8820
$

(This is plain Linux and does not need to run anything on the ATmega.)

Thanks for you answer, but I need to do it with Arduino, not Linux computer, I will be later extending that project to convert to 5-din midi socket. Also, I won't have the laptop next to the keyboard and synth when using that set-up so it has to go through Arduino I am afraid.

The Yun runs a Linux on the AR9331's CPU. And that is where the USB host ports are.

I got confused by your comment it doesn't need Arduino ; ) Ok I will need to test this solution then!


text:
Arduino code for XBee
I am trying to send analog data, from a LM35, using an XBee (series 1 - XB24).
My setup:

Transmitting Module: XBee with USB explorer+Arduino+LM35 (temperature sensor)
Receiving Module: XBee with XBee shield+Arduino

I read analog data using the Arduino and send it through the XBee in the USB explorer, then the receiving XBee module receives it and shows it in the serial monitor of the Arduino.
I have tried many ways but I can't reach it and I have figured out that my problem lies in the Arduino code.
So, please can anyone help with some demo code for this project?

Can you post what code you have so far, and what part you think is broken?

You probably want to take a look at Robert Faludi's book Building Wireless Sensor Networks, published by O'Reilly. He describes, step by step, a very similar project, but without the Arduino.
Or Alasdair Allan's Distributed Network Data, also published by O'Reilly, which has a similar project using an Arduino.
Also, take a look at Robert Faludi's blog TMP36 Instructions: Simple Sensor Network.


text:
Vibrating motors with different intervals
For my project, I have 3 ultrasonic sensors and 3 vibrating motors; the motors need to buzz for a small amount of time, then wait for a specific time that corresponds whith the range of the ultrasonic sensor, then muzz again.
The problem I'm having is that I used delays at first but that would cause the third motor only to buzz after the first two already waited.
I basically need something like "digitalWrite(motorPin_1, HIGH) for X amount of time;"
and at the same moment it has to start "digitalWrite(motorPin_2, HIGH) for X amount of time;".
Sadly I can't get the motors to vibrate any softer or harder, so I use these intervals.

Did you check the Blink Without Delay Arduino tutorial?

oh, thanks i had no idea it was so simple. with the blink it works just as i wanted! :)

Like Edgar commented, you need to check out Blink Without Delay (http://arduino.cc/en/Tutorial/BlinkWithoutDelay). Learn what they are doing and you will get this just fine.
Also, I recommend you learn to use libraries. This library can do exactly what you are asking for: http://playground.arduino.cc/Main/LibraryList#Timing --> click on the "Timer" library by Simon Monk & J Christensen. Follow the examples there. This library works great!
Here is a complete set of code to answer your question. It should work perfectly for you.
/*
buzz3Motors.ino
By Gabriel Staples
http://electricrcaircraftguy.blogspot.com/
7 March 2015

To help this person here: http://arduino.stackexchange.com/questions/9089/vibriting-motors-with-different-intervals
*/

#include "Timer.h"

Timer t;

boolean buzzMotor1Now = false, buzzMotor2Now = false, buzzMotor3Now = false;
unsigned int buzzTime = 1000; //ms
byte buzzPin1 = 11;
byte buzzPin2 = 12;
byte buzzPin3 = 13;

void setup()
{
  //set pins to outputs
  pinMode(buzzPin1, OUTPUT);
  pinMode(buzzPin2, OUTPUT);
  pinMode(buzzPin3, OUTPUT);
}

void loop()
{
  //UPDATE YOUR BUZZMOTOR BOOLEANS HERE, and set to true if necessary

  /**
   * This method will generate a pulse of pulseValue, starting immediately and of
   * length period. The pin will be left in the !pulseValue state
   */
  //Function format: int8_t pulseImmediate(uint8_t pin, unsigned long period, uint8_t pulseValue);
  //see here: https://github.com/JChristensen/Timer/blob/master/Timer.h

  if (buzzMotor1Now==true)
  {
    buzzMotor1Now = false; //reset
    t.pulseImmediate(buzzPin1,buzzTime,HIGH);
  }
  if (buzzMotor2Now==true)
  {
    buzzMotor2Now = false; //reset
    t.pulseImmediate(buzzPin2,buzzTime,HIGH);
  }
  if (buzzMotor3Now==true)
  {
    buzzMotor3Now = false; //reset
    t.pulseImmediate(buzzPin3,buzzTime,HIGH);
  }

  t.update(); //update all timer events
}

Note that only 10 timer events can be ongoing at any given time. If you want to have more you must increase the MAX_NUMBER_OF_EVENTS value in the Timer.h (https://github.com/JChristensen/Timer/blob/master/Timer.h) file.
PS. Also look into the "oscillate", "after", "every", and "pulse" functions, that the library also supports.
If this answer meets your needs please mark the green check beside it to indicate accepted answer. Thanks.

you are completely right, the timer library works great, thanks for your replie. :p


text:
How do you call a class method with named parameters?
I have a C++ class constructor like:
Motors(int p1=0, int p2=0);

However, when I attempt to instantiate it with named parameters like:
Motors motors(p1=123, p2=456);

the Arduino C/C++ compiler gives me the errors:
src/motors.ino:3: error: ‘p1’ was not declared in this scope
src/motors.ino:3: error: ‘p2’ was not declared in this scope

The compiler doesn't seem to support named parameters and thinks I'm referring to variables. I thought named parameters was a pretty widely supported feature, even in C++. What am I doing wrong?

C++ doesn't support named parameters, and I doubt it ever will.
It has strict calling conventions which mean you couldn't re-order the parameters at call-time without adding an unnecessary layer of data duplication/indirection (which would hurt performance). It would also need a significant change to compiler architecture, as variable/parameter names are usually stripped out long before the linker is invoked.
If you want to achieve a similar effect though, you could use comment blocks instead, e.g.:
Motors motors(/*p1*/ 123, /*p2*/ 456);


text:
Problem to upload code
I tried to upload example code form arduino software and got error below. Two arduino attach with my computer running windows8.1. And These arduino using port 3 and port 4. The arduino using Port 3 is cordinator and arduino using port 4 is router.
I doesn't understand why error show COM1 is not available. I am not using COM1.
Arduino: 1.6.0 (Windows 8), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.

Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.

C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM1 -b115200 -D -Uflash:w:C:\Users\Jiya\AppData\Local\Temp\build1135139715306090793.tmp/Blink.cpp.hex:i

avrdude: Version 6.0.1, compiled on Apr  3 2014 at 23:12:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : COM1
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available
Board at COM1 is not available

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

(I'm assuming you're using the official Arduino IDE here.)
Before uploading a sketch, you need to select which port you want to upload to. Within the Arduino IDE, click on the Tools menu and open the Port submenu. Click on the port your Arduino is connected to, such as COM3 or COM4.
You also need to ensure the appropriate board type is selected in Tools -> Board.
You should then be able to and upload the sketch.

Did you try with code bender. In my experience, uploading through the code bender works all the time even if it fails with Arduino IDE

On windows systems, COM1 is usually the system port, so you shouldn't use that for programming.
Try updating device drivers by going to device manager and right click on the COM3 and COM4 icons for the arduino boards.
If this keeps persisting then try reinstalling the ide and restarting your computer

If all the other solutions don't work and you are on a Linux distro try sudo arduino and that should work, or follow these instructions: Getting Started With Arduino on Linux (Ubuntu)

It looks like the user is on a Windows machine – and on *nix even the super user can't open a nonexistent file :-)

Experience has taught me twice... to make sure you use the right cables.  I used a spare cable that ended up being a power brick charging cable, i.e. no data lines.  Make sure you use a decent USB cable - preferably one that asks you question on a cellphone when connected to a PC, so you know all the internal wires are there and working.

your kernel need to provide support to USB ACM.
CONFIG_USB_ACM=y

you can look for it at:
$ zcat /proc/config.gz | grep CONFIG_USB_ACM
CONFIG_USB_ACM=y


text:
Sketch stops printing after writing a few times
I am trying to build a random horoscope printer. I have a series of strings in an array which I am storing in program memory. I then pick a random number and print that index concatenated with a title. But it often (but not always) only runs 4 or 5 times.
#include <avr/pgmspace.h>

const char string_0[] PROGMEM = "You have a great need for other people to like and admire you. ";
const char string_1[] PROGMEM = "You have a tendency to be critical of yourself. ";
const char string_2[] PROGMEM = "You have a great deal of unused capacity which you have not turned to your advantage. ";
const char string_3[] PROGMEM = "While you have some personality weaknesses, you are generally able to compensate for them. ";
const char string_4[] PROGMEM = "Your sexual adjustment has presented problems for you. ";
const char string_5[] PROGMEM = "Disciplined and self-controlled outside, you tend to be worrisome and insecure inside. ";
const char string_6[] PROGMEM = "At times you have serious doubts as to whether you have made the right decision or done the right thing. ";
const char string_7[] PROGMEM = "You prefer a certain amount of change and variety and become dissatisfied when hemmed in by restrictions and limitations. ";
const char string_8[] PROGMEM =  "You pride yourself as an independent thinker and do not accept others' statements without satisfactory proof. ";
const char string_9[] PROGMEM = "You have found it unwise to be too frank in revealing yourself to others. ";
const char string_10[] PROGMEM = "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved. ";
const char string_11[] PROGMEM = "Some of your aspirations tend to be pretty unrealistic. ";
const char string_12[] PROGMEM = "Security is one of your major goals in life. ";

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_10, string_11, string_12};

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(2));
}

void loop() {
    Serial.println("WE GOING TO LOOP NOW");
    char buffer[50];
    int rand = random(0,12);
    Serial.println(rand);
    strcpy_P(buffer, (char*)pgm_read_word(&(string_table[rand]))); // Necessary casts and dereferencing, just copy.
    char text[15] = "Your horoscope";
    String output;
    output = strcat(text, buffer);
    Serial.println(output);
    delay(1000);
}

I also sometimes don't seem to get very clean results, but I'm not sure why. I.e. printing WWWW... and missing the first part of the string in the serial monitor.
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GOING TO LOOP NOW
1
Your horoscopeYou have a tendency to be critical of yourself.
WE GOING TO LOOP NOW
3
or them. While you have some personality weaknesses, you are generally able to compensate for them.
WE GOING TO LOOP NOW
4
Your horoscopeYour sexual adjustment has presented problems for you.
WE GOING TO LOOP NOW
2
ge. You have a great deal of unused capacity which you have not turned to your advantage.

What you see is undefined behavior. You define your buffer to have a length of 50 bytes:

char buffer[50];

This is too short for most of the strings you want copy into it and you will thus overwrite other variables.
The simplest solution is to increase the buffer size so that the longest string fits (e.g. 150). You will see that it then works as you expect. Take a look at http://linux.dd.com.au/wiki/Arduino_Static_Strings for hints how to avoid wasting RAM for the buffer.


text:
Use an ethernet shield and RFID rc522 together on a mega?
I am using an Arduino Mega and I would like to connect a rc52 RFID reader and a network shield.  My problem is that both are set to use the same set of pins: 50 - 53.  Can I redefine the pins used so that I can use both at the same time?

Yes, I do think so. according to my Question with RFID and display it turned out that those pins are for serial communiacation. So I think it should work.
I can verify
 that it will work if you do use the ICSP headers MOSI/MISO/SCLK pins. Connecting those three with the RC552 as well as GND and 3V3. Also connect two other pins to SS and RST. This pins can be adjusted in the sketch on the Arduino.


text:
Mirf not sending reply
I am trying to create a server - node connection with NRF24L01+ chip and Mirf library with interrupts. It seem to work, but server does not seem to get reply from node. If I put it in the loop it receives. Can you check what is wrong with my code?
Server:
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>

typedef struct{
  long int packet;
  byte address[5];
}
Test;
Test Toolkit;

void setup(){
  Serial.begin(9600);
  Serial.println("Configuring NRF24L01+ module ...");
  Mirf.cePin = 9;
  Mirf.csnPin = 10;
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"clie1");
  Mirf.setTADDR((byte *)"serv1");
  Mirf.payload = sizeof(Test);
  Mirf.config();
  Serial.println("Configuring internal script variables ...");
  Serial.println("Setting system interrupts ...");
  Toolkit.packet = 9;
  attachInterrupt(0,wakeupFunction,FALLING);
}

void loop(){
  strcpy((char *)Toolkit.address,"CLI");
  Mirf.send((byte *)&Toolkit);
  while(Mirf.isSending()) { }
  //Mirf.setRADDR((byte *)"clie1");
  /*if(Mirf.dataReady()) {
    Mirf.getData((byte *)&Toolkit);

    Serial.println("Got data!");
    Serial.print("Packet number: ");
    Serial.println(Toolkit.packet);
  } else Serial.println("NO DATA");*/
  delay(1000);
}
void wakeupFunction() {
  //while(Mirf.isSending()) { }
  if(Mirf.dataReady()) {
    Mirf.getData((byte *)&Toolkit);
    Toolkit.packet = random(300);
  }
}

and this is client
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>

typedef struct{
  long int packet;
  byte address[5];
}
Test;
Test Toolkit;

void setup(){
  Serial.begin(9600);
  Mirf.cePin = 9;
  Mirf.csnPin = 10;
  Mirf.spi = &MirfHardwareSpi;
  Mirf.init();
  Mirf.setRADDR((byte *)"serv1");
  Mirf.setTADDR((byte *)"clie1");
  Mirf.payload = sizeof(Test);
  Mirf.config();
  Serial.println("Listening...");
}

void loop(){
  if(!Mirf.isSending() && Mirf.dataReady()){
    Serial.println("Got packet");
    Mirf.getData((byte *)&Toolkit);
    Serial.println("Packet number:");
    Serial.println(Toolkit.packet);
    Serial.println((char *)Toolkit.address);
    //Sending
    delay(50);
    Mirf.setTADDR((byte *)"clie1");
    Mirf.send((byte *)&Toolkit);
    while(Mirf.isSending()) Serial.println("Sending");
    Serial.println("Reply sent.");
  }
}

I suppose that function Mirf.dataReady() does not work properly in Server interrupt. I have the same problem.


text:
Differential steering drive equation
I'm trying to control an Arduino-powered motorized toy with a differential drive. However, I want to code it the motor movements with a direction vector.
e.g.
(1,0) = forward
(-1,0) = backward
(0,1) = turn left, pivoting on center axis
(0,-1) = turn right, pivoting on center axis
(1,1) = forward-left, pivoting on left wheel
(1,-1) = forward-left, pivoting on right wheel

I thought the equation to convert these to the literal motor signals was:
float mag = sqrt(dirX*dirX + dirY*dirY);
float left = dirX - dirY;
float right = dirX + dirY;

This seems to work for the first 4 cases, but fails for the last two, where it results in an un-normalized vector.
One potential fix would be to simple wrap left and right in min() to stop it from going over 1.0, but that feels like a hack, and would possibly lose resolution. Is there a more elegant fix?

If you want to take it to to the extreme, I always use an algorithm called Diamond Coordinates. It is described in this PDF.  It performs perfectly, and I keep a C# and Java implementation handy. I'll probably be doing a Python one soon :)

Part of the problem is that "direction vector" is a bit vague in this context. Here are two popular ways of doing this:
(x = right speed, y = left speed)
This is like "tank drive", where two joystick's up/down axis are used to drive; you don't really need to do any math to get motor outputs.
(m = output magnitude, d = left/right balance)
I've heard this called "arcade drive", where one joystick's up/down is m and left/right is d.
Your equations are correct; the bounds check is unavoidable. Linear vector spaces just are not going to arbitrarily bound themselves at 1 for you. you could make it so "full speed ahead" doesn't actually max out the motor speeds; then when you turn it could still speed up one side a bit, but that is obviously still suboptimal.
You could try normalizing left and right, then multiplying by "m" again. The magnitude would be constant so you wouldn't have to do any bounds checking, but you would lose the pivoting on the center behavior you want, and full forward would be slower. You could also try making "d" an angle, and then choosing left and right with sine and cosine, probably shifted 45 degrees. That has the same problems.
I like to try driving it a bunch of different ways and see what handles best.


text:
How to change i2c address for mpu9250?
I'd like to connect 12 mpu9250 sensors to one arduino board.
I can't find documentation on how to change the addresses of mpu9250 boards. (i read through the reference ). Some tutorials talk about changing addresses for other device so i assume it is possible for mpu9250. I found this map of registers but can't figure out how to change the address.
I realize that mpu9250 might be too specific, so general guidance on how to solve these problems would be highly appreciated.
mpu9250 is similar to more popular mpu9150 and mpu6050. It is also known as GY-9250

http://www.wiimoteproject.com/general-discussion/2-nunchuck-with-arduino-help/msg8262/?PHPSESSID=e189911faffb53447fd2497bc3b87581#msg8262

Page 23 of the manual you linked:

The MPU-9250 always acts as a slave when communicating to the system processor.
  The LSB of the of the I2C slave address is set by pin 9 (AD0).

It seems you can only choose between two addresses as listed in the table on page 12.

fair enough, I just thought it would be logical to allow user to change the address

Might be a little late, but you can string more than two of these on one I2C bus, with a little ingenuity.
You connect the AD0 pin of each MPU to a different I/O pin of the processor, then take low the address of the one MPU you want to talk to.
Then that MPU has one address, all the others have the other address, and being slaves will not respond.
Provided you don't have more than one MPU selected at once, works a dream.

A very cunning suggestion, I like it!


text:
How to get the signal strength of the network connected with the ESP8266
I am using ESP8266 module with Arduino Uno.I don't know how to get the signal strength of the network with which ESP8266 is connected.Please help..

The page http://tomeko.net/other/ESP8266/ names the following command:

AT+CWLAP     // list available access points

According to the example given there, this returns a list of items looking like this:

+CWLAP:(3,"UPC784xxx",-75,"70:54:d2:xx:xx:xx",1)

where "APs are sorted by channel and values are: (security, "name", signal strength, MAC, channel) where for security: 0 = open, 1 = WEP, 3 = WPA, 4 = WPA2".
Thus you can use AT+CWJAP? to obtain the name of the network you're connected to and get the signal strength from the respective item in the list provided by AT+CWLAP.
See http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module for a reference of commands.

The security is wrong. Correct are (according to the documentation 0.2 from March 20, 2015): 0 = open, 1 = WEP, 2 = WPA_PSK, 3 = WPA2_PSK, 4 = WPA_WPA2_PSK.


text:
Pixel font resources in byte format
To write text on a dot-matrix or LC display with an Arduino you need to have a pixel font in byte format (i.e. typically 1 bit = 1 pixel).
On the Internet I have found surprisingly few resources for this.
Most of the results when searching for pixel fonts return true-type fonts (or similar) which are rather complicated to convert to obtain a satisfying result.
Also, most of the fonts are rather high resolution.
Any good resources I have missed?

Try looking at lcd libraries. Those have some fonts embedded in it. Or search for 5x7 fonts.

Mainly I am wondering if there is a site collecting a few pixel fonts to choose from, which would be quite useful. (I found a few fonts here and there, mostly in libraries. Unfortunately, all had only ASCII.)

What other characters do you need? Memory is limited, so it's a good idea to limit the amount of characters.

Umlaute :) 4321

Just an umlaut, or letters with umlaut? If the latter you need some additional pixels (height). You can't make an ä with only 5x7 pixels.

Well, actually I'd even prefer 8 pixel height.

The UTFT library has a SmallFont which is 8x12. Not sure whether this is too big for you, but it could be worth looking into. It is ASCII only, so you might want to add some characters yourself. But as someone mentioned, memory is limited, so add sparingly.

Moreover the creator of the library put online a tool to create new fonts starting from an image (here) and some other fonts made by other people (here)

You could create the character data yourself. I've built a little script for a similar prospect a while ago that does translate a matrix of checkboxes to a bit-array: http://jsfiddle.net/qrsye920/

Try the Dot Factory and The LCD Assistant. I'm happy with both. Let's you create any Windows font.


text:
How to add hysteresis to threshold values?
This code compares the analog input value against two thresholds, having three voltage regions. Then it will turn on an LED according to what region the read voltage is in.
The problem is that when the voltage read is very close to the threshold, the noise will disturb the output, resulting in an uncontrolled switching between LEDs.
I would need to add some sort of HYSTERESIS around my thresholds to avoid the uncontrolled switching, but I have no idea how to write this into the code language. Would anyone be able to help me writing the threshold bit?
This is the full code:
// these constant won't change:
const int BatteryVoltagePin = 14;   // the pin that battery voltage is attached to
const int GreenLedPin = 3;           // the pin that the green LED (On charge) is attached to
const int OrangeLedPin = 4;          // the pin that the orange LED (no risk) is attached to
const int RedLedPin = 5;             // the pin that the red LED (low battery) is attached to

// Variables will change:
int currentVoltage ;         // current voltage value
int previousVoltage ;     // previous voltage value

void setup() {
  // initialize the battery voltage pin as a input:
  pinMode(BatteryVoltagePin, INPUT);
  // initialize the green LED as an output:
  pinMode(GreenLedPin, OUTPUT);
  // initialize the orange LED as an output:
  pinMode(OrangeLedPin, OUTPUT);
  // initialize the red LED as an output:
  pinMode(RedLedPin, OUTPUT);
}

void loop() {
  // read the voltage across the battery voltage pin:
  currentVoltage = digitalRead(BatteryVoltagePin);

  // compare the current voltage value to its previous value
 if (currentVoltage != previousVoltage)

 delay(10);

    // value above maximum threshold
    {
     if ((( ( analogRead(BatteryVoltagePin) ) > ( 699 ) ))
        {
        digitalWrite(GreenLedPin, HIGH);
        }
        else
        {
          digitalWrite(GreenLedPin, LOW );
        }
    }

    //value between two thresholds (middle region)
    {
     if (( ( ( analogRead(BatteryVoltagePin) ) <= ( 699 ) ) && ( ( analogRead(BatteryVoltagePin) ) >= ( 628 ) ) ))
        {
        digitalWrite(OrangeLedPin, HIGH );
        }
        else
        {
          digitalWrite(OrangeLedPin, LOW );
        }
    }

    // value below minimum threshold
    {
     if (( ( analogRead(BatteryVoltagePin) ) < ( 628 ) ))
        {
        digitalWrite(RedLedPin, HIGH);
        }
        else
        {
          digitalWrite(RedLedPin, LOW );
        }
     }

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
 }

This kinda sounds like a case where you may need debouncing... Have you already done this?

no I haven't. Could you explain this in more details please?

Adding hysteresis behavior to your code is not difficult. You just need to store the state you're in and make the thresholds for transitioning into another state dependent on that.
You can use an enum to store the state:
enum BatteryStates {
  Red, Orange, Green
};

Then, instead of defining and checking against one threshold value, define two thresholds for each transition, separated by so much that you don't observe the undesired flip-flopping behavior.
For example, when transitioning from Green to Orange you could do something like this:
if ((state == Green) && (battery < 690))
  state = Orange;

And the other direction would use a slightly higher threshold
if ((state == Orange) && (battery > 700))
  state = Green;

so that small fluctuations of the voltage do not cause flip-flopping.
(Note that my code assumes
int battery = analogRead(BatteryVoltagePin);

The variable state should be declared and initialized like so:
enum BatteryStates state = Green;

Instead of an enum you could use a simple int and map each state to a number (e.g. red = 1, orange = 2, green = 3), but using enum makes the code easier to read and write. (In fact enum does use integer numbers.)
I might also use a switch statement instead of an if chain to implement the transitions, but that's a matter of taste.)

Thanks for your answer!!
But I do not know how to use the statmement enum. It looks like arduino IDE does not recognise it.
Could you please explain this in more details?

enum is not highlighted by the syntax highlighting. But it is accepted by the compiler. I have added some details.

Many thanks for your help! However, I am new to programming and I cannot make full sense of all this. I do understand the logic behind it... but when I try to put it together it does not work. If you could post a little working example that does compile, perhaps initialising all the variables etc, it would help a lot!

I am happy to help with concrete questions but I need to ask you to do your part: Try to solve the problem yourself first and if you fail describe where you need help.

This includes hysteresis and uses some loops and arrays to simplify and compact the code, since the logic for each range is essentially the same.  More ranges are easy to include by extending the Cutoffs and LedPins arrays (one more led than cutoff).
const int VoltagePin = 14;
const int Cutoffs[] = { 628 , 699 };
const int NumCutoffs = sizeof(Cutoffs)/sizeof(int);
const int Hysteresis = 5;

const int LedPins[NumCutoffs+1] = {5,4,3};

int Level = 0;
int Voltage = 0;

void setup()
{
  for (int i=0; i<=NumCutoffs; ++i) {
    pinMode(LedPins[i],OUTPUT);
  }
}

void loop()
{
  Voltage = analogRead(VoltagePin);

  while (Level < NumCutoffs && Voltage >= Cutoffs[Level]) {
    ++Level;
  }

  while (Level > 0 && Voltage < Cutoffs[Level-1] - Hysteresis) {
    --Level;
  }

  for (int i=0; i<=NumCutoffs; ++i) {
    digitalWrite(LedPins[i], i == Level);
  }

  delay(20);
}

Your original code had digitalRead() instead of analogRead().  The voltage line should be connected to an analog pin (like A0) and then VoltagePin should be the corresponding pin.   Hysteresis should be tuned for your application.

Here is what I do. I detect whether the voltage is rising or falling and adjust the threshold based on that.
int ledPin = 13;   //pin 13 will be connected to the MOSFET SS relay

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    int sensorValue = analogRead(A0); // This is the main battery voltage sensor
    int RLA1;   //this will be connected to the MOSFET SS relay
    float threshold; //  To enable some hysteresis and prevent the relay from chattering, we move the threshhold, depending on whether we are going up or down

    float Vmainold;  //  Used to detect whether we are going up or down
    float  Vmain;   // Main battery voltage.
    float Vaux;     // Auxillary battery voltage

    Vmain = sensorValue / 204.6 + 9.8;   // Add back the ~10V that the zener shifts for higher resolution

   if (Vmain > Vmainold) threshold = 13.2;  // If the voltage is rising, set threshhold to 13.2
   else
    if (Vmain < Vmainold) && (Vmainold > 12.8) threshold = 12.8 // If the voltage is falling and previous voltage is above TH, set theshhold to 12.8
    else
        if (Vmain = Vmainold) threshold = 13.2;  // If the voltage is stable, set threshhold to 13.2

   if (Vmain >= threshold) RLA1 = 1; //  Charging

   else
    if (Vmain < threshold) { RLA1 = 0;  Vmainold = Vmain; }  // Not connected

   delay(1000);
   Serial.print(Vmain);
   Serial.print("  Main  ");
   Serial.print(Vmainold);
   Serial.print("  old  ");
   Serial.println();
   Vmainold = Vmain;
   digitalWrite(ledPin, RLA1);
}

`

The state machine is a solid approach.
For this simple case, you can also solve this by implementing small dead bands around the change levels.  When the value is in a range near the transition threshold, do nothing.  Only when the value is certainly above or below the transition, make the change.  Your code would be:
// Variables will change:
int currentVoltage = 0;         // current voltage value
int previousVoltage = 0;     // previous voltage value

void loop() {
  int deadband = 5;
  // on very first loop, start with no dead band
  // this is necessary in case starting voltage is in
  // middle of a transition range
  if (0 == previousVoltage) {
    deadband = 0;
  }

  // read the voltage across the battery voltage pin:
  currentVoltage = analogRead(BatteryVoltagePin);

  // test the voltage against the three ranges
  // value above maximum threshold
  if ((699+deadband) < currentVoltage) {
    digitalWrite(GreenLedPin, HIGH);
    digitalWrite(OrangeLedPin, LOW );
    digitalWrite(RedLedPin, LOW );
  }

  //value between two thresholds (middle region)
  if (((628+deadband) < currentVoltage) && (currentVoltage <= (699-deadband))) {
    digitalWrite(GreenLedPin, LOW);
    digitalWrite(OrangeLedPin, HIGH);
    digitalWrite(RedLedPin, LOW);
  }

  // value below minimum threshold
  if (currentVoltage < (628-deadband)) {
    digitalWrite(GreenLedPin, LOW);
    digitalWrite(OrangeLedPin, LOW );
    digitalWrite(RedLedPin, HIGH);
  }

  // Note that at this point, none of the if cases above
  // might have been true.  When the voltage is right near the
  // thresholds, do nothing.  Only when the voltage is definitively
  // in the range does the LED state change.

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
  delay(10);

  return;
}

In function, this will achieve the same result as hysteresis.

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


text:
SAM3X8E (Arduino Due) Pin IO registers
How do the IO registers of Arduino Due work?
On Arduino Uno just set DDRx, then PINx to read, PORTx to write, I'd like to do the same thing with an Arduino Due, but it has many more registers, such as PIO_OWER, PIO_OSER, PIO_CODR, PIO_SODR, etc. I find no correspondence between Arduino Uno and Arduino Due registers.
There are also some useful functions such as pio_clear, pio_set, pio_get, and others, all explained here:
http://asf.atmel.com/docs/3.19.0/sam3x/html/group__sam__drivers__pio__group.html
Now, I think I've understood what the three mentioned functions do, but not others, for example:
pio_configure (Pio *p_pio, const pio_type_t ul_type, const uint32_t ul_mask, const uint32_t ul_attribute)

I can't figure out what ul_attribute and ul_type are.

Here is a GPIO class that is implemented for AVR and SAM. Might give a hint of how to use the registers: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/SAM/GPIO.h

If you have a read of section 31 of the Datasheet, available from here, things may come a little clearer for you.
Here's a summary of what I know:
PIO stands for Parallel Input/Output and offers the functionality to read and write multiple register ports at a time.  Where the datasheet mentions a register, for example PIO_OWER, the Arduino library has macros for accessing them in this format REG_PIO?_OWER where ? is either A, B, C or D for the different ports available.
I tend to still use the slow Arduino pinMode() function to set input/output on the pins as it makes the code more readable than the acronym based registers calls such as REG_PIOC_OWER = 0xdeadbeef, but then use the direct registers to set the pins for performance/synchronisation.  As yet, I haven't done anything with input, so my examples are all output based.
For basic usage, you would use REG_PIO?_SODR to set output lines high and REG_PIO?_CODR to set them low.  For example REG_PIOC_SODR = 0x00000002 would set bit 1 (numbered from zero) on PORTC (this is Due digital pin 33) high. All other pins on PORTC remain unchanged.  REG_POIC_CODR = 0x00000002 would set bit 1 on PORTC low.  Again all other pins would be unchanged.
As this is still not optimal, or synchronised if you are working with parallel data, there is a register that allows you to write all 32 bits of a port with a single call.  These are the REG_PIO?_ODSR, so REG_PIOC_ODSR = 0x00000002 would now set bit 1 on PORTC high and all other bits on PORTC would be set low instantly in a single CPU instruction.
Because it is unlikely that you would ever be in a situation where you need to set all 32 bits of a port at the same time, you would need to store the current value of the pins, perform an AND operation to mask out the ones you want to alter, perform an OR operation to set the ones you want set high then perform your write and again, and this is not optimal.  To overcome this, the CPU itself will perform the masking for you.  There is a register called OWSR (output write status register) that will mask out any bits that you write to ODSRs that don't match bits set in the OWSR.
So, now if we call REG_PIOC_OWER = 0x00000002 (this sets bit 1 of the OWSR high) and REG_PIOC_OWDR = 0xfffffffd (this clears all bits except bit 1 of the OWSR) and then call REG_PIOC_ODSR = 0x00000002 again, this time it would only change bit 1 of PORTC and all other bits remain unchanged.  Pay attention to the fact that OWER enables any bits that are set to 1 in the value you write and that OWDR disables any bits that are set to 1 in the value you write.  Even though I understood this when I read it, I still managed to make a code mistake when writing my first test code thinking that OWDR disabled bits that weren't set to 1 in the value I wrote.
I hope this has at least given you a bit of a start in understanding the PIO of the Due CPU.  Have a read and a play and if you have any further questions, I'll try to answer them.
Edit:
One more thing...
How do you know which bits of the PORTs correspond to which digital lines of the Due?  Check this out: Due Pinout

There is a fairly simple equivalence for the basic direct pin access. Below is some sample code which shows how to set a digital pin high and then low. The first is for an Arduino Due, the second is for the Arduino Uno/Mega/etc.
const unsigned int imThePin = 10; //e.g. digital Pin 10

#ifdef _LIB_SAM_

    //First lets get the pin and bit mask - this can be done once at the start and then used later in the code (as long as the variables are in scope
    Pio* imThePort = g_APinDescription[imThePin].pPort;
    unsigned int imTheMask = g_APinDescription[imThePin].ulPin;

    //Lets set the pin high
    imThePort->PIO_SODR = imTheMask;
    //And then low
    imThePort->PIO_CODR = imTheMask;

#else

    //First lets get the pin and bit mask - this can be done once at the start and then used later in the code (as long as the variables are in scope
    volatile unsigned char* imThePort = portOutputRegister(digitalPinToPort(imThePin));
    unsigned char imTheMask = digitalPinToBitMask(imThePin);

    //Lets set the pin high
    *imThePort |= imTheMask;
    //Now low
    *imThePort &= ~imTheMask;

#endif

Everything that is needed to do that should be included by default - and if not #include <Arduino.h> should be sufficient to get it there.
There are actually functions available that can be called once you have the Pio pointer to do the setting/clearing/pullup resistors/etc. using slightly cleaner looking function calls. A full list can be found in the  header file.

This is a code example that flashes a led on pin 33. Code borrowed from above - many thanks for the very helpful explanations :) This is the beginning of a project to talk to a TFT touchscreen display with dumping of 16bit color pixel data which needs fast access to the ports. I think I have the code right - particularly the line that sets the pin low. The led is happily flashing.
void setup()
{
  pinMode(33, OUTPUT);
  REG_PIOC_OWER = 0x00000002;
  REG_PIOC_OWDR = 0xfffffffd;
}

void loop()
{
  REG_PIOC_ODSR = 0x00000002;
  delay(1000);
  REG_PIOC_ODSR = 0x00000000;
  delay(1000);
}

I actually followed the above examples and did many tests that I am comfident the results will aid anyone looking into addressing the registers directly.
   void setup() {
  pinMode(25, OUTPUT);
  pinMode(26, OUTPUT);
  pinMode(27, OUTPUT);
  pinMode(28, OUTPUT);
  pinMode(29, OUTPUT);
  //REG_PIOD_SODR = 0b00000000000000000000000001001111; // written in binary form
  REG_PIOD_SODR = 0x0000004F; //written in Hexadecimal form. Note the differences. Thw two, binary and Hexadecimal are the same.
  delayMicroseconds (250000);
  //REG_PIOD_CODR = 0b00000000000000000000000001001111;
  REG_PIOD_CODR = 0x0000004F;
  delayMicroseconds (2000000);

}

void loop()
{
  //REG_PIOD_ODSR = 0b00000000000000000000000001001111; // serts all the bits set to 1 HIGH and the rest set to 0 LOW
  REG_PIOD_SODR = 0b00000000000000000000000001001111; // sets all the bits set to 1 HIGH and leaves the rest untouched
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000000100;//1
  //REG_PIOD_CODR = 0x00000004; //identical to the line above only that it is in Hexadecimal format
  //REG_PIOD_SODR = 0b00000000000000000000000000000100; // will disable the rest bits and leave only one HIGH
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000000010;//2
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000001000000;//3
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000001000; //4
  delay(500);
  REG_PIOD_CODR = 0b00000000000000000000000000000001; //5
  delay(500);

}

To explain better, all pins desired to be OUTPUTs are set via pinMode and then, it is very optional toenable them while at SETUP. In this case, I just wanted the pins to be made HIGH just once while at SETUP and then LOW before the loop starts. I've used REG_PIO?_SODR (in this case, ? is port D so it is REG_PIOD_SODR) which only make its set to 1 HIGH and the rest are left untouched. I have used both in binary and Hexadecimal format. Binary makes it easier to identify which pins to enable. For instance, bit PD0 is the right most bit in the binary number. It starts from Right going to left. For example, 0b00000000000000000000000000000001, bit 1 is PD0, PD1 will be 0b00000000000000000000000000000010 and so on.
You've seen examples provided in this format, 0xfffffffd the x means it is in hexadecimal format and b is in binary format. To convert binary to Hexadecimal, youcan use the easiest route via this link
To explain, any Hexadecimal number represents 4 binary numbers, example, Hex 0 is binary 0000, Hex F is binary 1111, Hex 4 is binary 0100, Hex A is binary 1010.
Now that is understood, going to the main loop, I have used the REG_PIOD_SODR because it gives one the freedom to address the pins one wants without touching any other pins on that port. You can use REG_PIOD_ODSR ONLY when you want to set all bits at once. This is ideal when you want many pins set HIGH and/or LOW at once. It is not the best if you want to set just a few pins HIGH/LOW and leave the rest untouched. REG_PIOD_SODR is ideal when some pins needs to be left untouched. You don't want to set one bit HIGH then all pins are HIGH. This command REG_PIOD_CODR sets the bits set 1 LOW and leave all the rest set to 0 untouched.
This code simply makes the bits selected at setup HIGH for the said time in delay then LOW for the given time. In loop, all bits selected as 1 are made HIGH and the rest untouched. The following lines simply turn the selected bits LOW one at a time until all are OFF and then the process repeats.
I hope this oversimplified explanation aided someone.


text:
Arduino TCP communication with Android phone
I am trying to communicate Arduino Uno with an android phone. What I trying to is:

Android device post a string to Arduino
Arduino post a integer to Android

So far I can post message from Android, received in Arduino board, but I can not post a integer to Android, nothing receive at Android
Arduino Code (Which can receive character "a", "b", "c", "d", and for case "z", I would like to send back the distance which is an int)  :
void loop()
{
  distance = Dist.getDistanceCentimeter();
  if(distance<=5 & distance>1)
  {
    back();
    delay(100);
    ting();
    distance=0;
  }
  if(Serial.available())
  {
    lkf = Serial.read();
  switch(lkf)
  {
  case 'a':
     front();
     servoX.write(90);
     lkf=0;
     break;
   case 'b':
     back();
     lkf=0;
     break;
   case 'c':
     left();
     lkf=0;
     break;
   case 'd':
     right();
     lkf=0;
     break;
  case 'z':
    Serial.write(distance);
    break;
    }
  }
 }

Android Code:
In Main Activity
@Override
protected TCPClient doInBackground(String... message) {

    //create TCPClient object
    mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
        @Override
        //check whether server return message
        public void messageReceived(String message) {
            f_sensor.setText(message);
            Log.d("test1","msg rece" + message);
            //publishProgress(message);
        }
    });
    mTcpClient.run();

    return null;
}

TCP Cilent
public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "192.168.8.1"; //your computer IP address
    public static final int SERVERPORT = 2001;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {

                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

                Log.d("test1",serverMessage);
                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

Your Android code purports to talk TCP, while your Arduino is talking Serial.  Somewhere in between is an unspecified translation which may be a source of trouble.  Your Android code looks improperly structured - you should not be creating a server object for a single use in an AsyncTask (which by default is now blocking) as you appear to be with doInBackground() but rather maintaining one within a background thread mechanism designed to continue running independent of others.  Finally, your Arduino code will only transmit when it receives something, and it is unclear that it is doing so.

Using serial.println instead of serial.write fixes the issue.

If you are going to use a readLine() type method on the receiver, yes, you will need to transmit a terminating newline.  However, a lot of others aspects of your design remain suspicious and potential sources of future issues, too - particularly the way you are doing threading on the Android side.

@ChrisStratton no, the issue's related to this: the .write() function sends the ASCII code, .print() converts it to a string. So Serial.write(65) would send A, Serial.print(65) would send 6, 5. The println would also add a newline character. So the issue is they were sending the ASCII code instead of the string composed of ASCII codes.

One issue.  My point is they have others as well.

Entirely replacing the poster's answer with your own words is not appropriate, especially when you still fail to state the cause of the specific observed issue (no data, not unexpected data).  If you want to offer your opinion do so in a comment, or post your own answer which may be judged by the community on its merits.


text:
Can I connect an RFID reader to the ICSP header?
I am connecting an RFID reader to my Arduino mega.  The directions that I have found say that I need to use pins 50-53.  I also noticed that the ICSP header contains (what looks like) a secondary connection to these pins:
http://arduino.cc/en/Reference/SPI
Can I connect my RFID reader to the ICSP header:

Yes you can. However the SS isn't present on that header. You can however use any pin you want for SS (if the library you use supports it, that is)


text:
Can you connect an output pin from one Arduino to the input pin of another?
I have a system that uses two Arduino boards.  One is used to control several different functions, and the other is dedicated to driving a 45 second countdown display (comprised of two large 7 segment displays.)  All this second Arduino needs is a single signal to tell it when to start.  I would like to simply connect an output pin (on #1) to an input pin (on #2) and and send a single pulse to get the clock started.  Fo something this simple, I wanted to avoid using I2C.  Can I do this?  If so, is there anything else I need to be aware of (like connecting ground to ground?)

Yes, you can. That is indeed the most easy way of communication.
And like you said, you have to connect the grounds of both arduino's.
Optionally you could add a pull-up of pull-down resistor, so the countdown doesn't accidentally start if the first arduino is still starting up, or is disconnected.

Doe the pull-up (or pull-down) ensure that the base state for the input is high (or low)?

Yes. That's what it's for.


text:
Which battery should I use to power arduino+motor shield + two 200 RPM (3.6V/1.5A)motors
I am using two motors ( from old two drill machines - same kind, these are 3.6v motors ), connected to arduino + arduino motor shield seeed studio v2.
When I measured the both motors (indvidually) using a multimeter in series with your motor and an about 3.6V power supply, I found that the both are varying from 1.46A-1.47A, (I supposed it as 1.5A)
I tried to use 18v/1.2a battery that was laying at home (from old machine ) what I have noticed is that motors are running for 3-5 seconds than stop, one of the red lights start blinking in the motor shield, then it stops for 3-5 seconds then it works again and loop.
Notes:
- The motors are working when I connect them directly to 4.5 or 6v battery. But when I try to assemle everything , it doesn't work (I am adding this just to say that motors are in good health).

I tried 14v battery I noticed the same thing.
The drill machine is small one (as big as a human hand). Motors from electric drills are designed as high-speed high-torque motors, but I don't think it's too high in my case to be a huge problem. It's 200 RPM DC motor
I spent a week looking for answer before posting this thread, I tried every single solution I came across on the web.

What are things that I should consider here, any thoughts.
What did I miss? And what kind of battery should I use ??

I have run into similar weirdness myself, and the solution that worked for me is to have separate batteries for the Arduino and the motors. This is more important if your motors run at a different voltage (e.g. 6v or 12v motors), but is useful in any case. This means that, when the motors draw to much from the batteries, the motors will slow down. If the same battery is used for the motors as for the Arduino, then the voltage drop from the motors will also apply to the Arduino; if the voltage drops in the Arduino, it will turn off (and turn back on when the voltage is restored). This is likely what you are seeing.

i've just run to try what you have said. I used 9v battery for arduino and ten (10)*1.2v batteries in serie to make a battery of 12v. WHat I ve noticed is that the motors are taking some time before they move (say 5-10 seconds). I don't use sleep() in my program. What I have made is a one command (to debug the problems) to make the both motors moving at 255. Is there any raison behind that ?? One more thing, the motors are moving slower than they supposed to do ? 12v is good voltage to make them run fast.

Check the voltage across the batteries used to power the motors, a high load may cause a voltage drop. Also, in your sketch, try turning the LED on immediately after or before turning on the motors - there may be a delay for some reason you're not expecting.


text:
snprintf crashing my program
I have to admit that I can't really use this function.
I'm trying to format some json but it crashing all the time my arduino:
char response[300];
tmp = "123";
snprintf(response, 300, "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]", tmp);

How should I use this function properly?

That's not JSON.

char response[300];
tmp = "123";
snprintf(response, 300,
    "[{Name:'Furnace',Value=%s,Alarm={MinValue=%s,MaxValue=%s}},"
    "{Name:'Room',Value=%s,Alarm={MinValue=%s,MaxValue=%s}}]",
    tmp, tmp, tmp, tmp, tmp, tmp);

In other words, you should add, after the format string, as many extra
parameters as there are %s in the format string.
PS: This looks like JSON, but it is not really valid JSON.
The format below should give valid JSON:
"[{\"Name\":\"Furnace\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}},"
"{\"Name\":\"Room\",\"Value\":%s,"
"\"Alarm\":{\"MinValue\":%s,\"MaxValue\":%s}}]",


text:
Variables not initialized in Class Constructor
I'm creating a library driver for AdaFruit's GFX library. During Constructor initialization, all the variables (set in another .cpp) are returned as zero. This code has several modular files to separate graphics functions from graphics primitives from device interfacing. What am I doing wrong?
In the Arduino sketch I call the class constructor: MB_GFX_SPI (in file MB_GFX_SPI.cpp).
In the Constructor I'm call a function: mbR.SetMatrixSize (in another file raster.cpp).
Also in the Constructor I call a function: clearScreen (in the same file MB_GFX_SPI.cpp).
The test variable  mbR.r_totNumChannels set in clearScreen is returned with 99.
All the variables set in mbR.SetMatrixSize return zero.
//Test Sketch
//Initialize both the Adafruit library and the current library.
//Instantiate an object mbGFX so all Adafruit GFX and MB_GFX add-on functions are addressed as mbGFX.xxx();
MB_GFX_SPI mbGFX = MB_GFX_SPI(Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

//In file MB_GFX_SPI.cpp

MB_GFX_SPI::MB_GFX_SPI(int Period, int numCathodeLEDS, int numAnodeLEDS,
      int CathodeSSPin, int AnodeSSPin)
      : Adafruit_GFX(numCathodeLEDS, numAnodeLEDS) {

  mbR.SetMatrixSize(numCathodeLEDS, numAnodeLEDS);
  clearScreen(0);
}
void MB_GFX_SPI::clearScreen(uint16_t color) {
   mbR.r_totNumChannels = 99;   //test set value
}

//In file mb_raster.cpp

void mbRasterClass::SetMatrixSize(int numCathodeLeds, int numAnodeLeds){
//cathodes require 1 byte per channel
//anodes require 1 bit per channel

    int numAnodeChannels = numAnodeLeds;
    int numCathodeChannels = mbX.pin2pin * numCathodeLeds; //times 1 or 3

    r_numCathodeRegisters = (int)((numCathodeChannels+7)/8);   //select next higher number of registers
    r_numCathodes = 8 * r_numCathodeRegisters;  //must be whole 8 bit registers - is every single chatode pin
    r_numAnodeRegisters = (numAnodeChannels+7)/8;       //round up to next register number
    r_numAnodes = 8 * r_numAnodeRegisters; //must be whole 8 bit registers
    r_PWMBufferSize = r_totNumChannels = r_numAnodes * r_numCathodes;

    r_PWMBuffer = (uint8_t *) realloc(r_PWMBuffer, r_totNumChannels); //resize array for PWMBuffer
}

can you give a function that shows what isn't working in code? something you would expect to do one thing, but isn't working out that way? I'm not certain I know what you mean by "the variables return zero". Also some more information about the members of an MB_GFX_SPI, and where mbR comes from.

Try initializing mbGFX with its regular constructor (GFX_SPI mbGFX(...);) instead of using copy-initialization (GFX_SPI mbGFX = MB_GFX_SPI(...);).

First, I would do what Edgar Bonet suggested, call the normal constructor:
MB_GFX_SPI mbGFX (Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

Second, I'm not keen on what you are doing in the constructor for a variable which appears to be at global scope (mbGFX).
See What's the "static initialization order fiasco"?
Basically you cannot assume that constructors in different compilation units are called in any defined sequence, you also cannot assume that the system has been initialized yet (ie. init() called).
Thus, things that address the hardware (eg. clearScreen(0);) may not work properly, or at all.

thanks for additional suggestions. I've recently installed Visual Studio+Visual Micro and have been tracing the initialization process.

authors: วิภาวรรณ เบียดกลาง


text:
How to make an arduino wifi repeater?
I am trying to make a wifi repeater. My router's signals don't come to my study and instead of buying a proper wifi repeater I prefer making one.
I want to learn how to make a simple wifi repeater that:

repeats/boosts my existing home wifi network by connecting to it.
Has some kind of a GUI or something that allows me to connect to it first (from some smartphone or PC) to configure it to my home network. It should find and show wifi networks around and then connect to the one I want it to upon my command.

I am new to electronics. Arduino is my preferred platform. If there are other easy to do alternatives that shall work too.
Any kind of help will be appreciated...tutorials, blogs, etc.

"Arduino is my preferred platform." Not for a wifi repeater it isn't.

Get a router that support OpenWRT. That way you can still "hack" the unit.

You can do three things: 1) cheapest and can use arduino 2) use a SBC (raspberry pi or derivatives) 3) hackable router. Solution 1 is to buy a cheap wifi repeater and, if you want an arduino, glue it to the front or back. Ta-da! Arduino wifi repeater... Jokes apart, the other solutions are serious. Using an SBC (like raspberry pi, or I found orange pis to be quite good) and two wifi adapters (or sometimes only one, but depends on the adapter - or if the SBC has one onboard) you can make a repeater. You will have to do all the work, starting from a bare linux environment, or use a ...continue

common distribution for routers (e.g. openwrt or ddwrt) to have almost all of its job done. Maybe the throughput won't be the maximum one, but you will have a simple and cheap solution. The alternative is to buy a router which already have openwrt or ddwrt ready for them. Look at the distribution's help pages to find a list of supported devices. Usually they are more expensive than generic routers, but YMMV...

An arduino wifi repeater would in theory be very slow. Since you need to record the bit stream to the internal memory, then switch the spi to the transmitter, and send the bit stream, im unsure about what would happen if you miss a few bits in the process.
Arduino Wifi Shield - the price of a wifi shield 85 usd
Wifi repeater ebay the price of a wifi repeater 22 usd.
This makes me question why one would go through the troubble of making a wifi repeater of an arduino.
Even investing in a raspberry pi and a wifi dongle would be less expensive.

Indeed - lots of people have bought cheap wifi access points to hack as wifi interfaces for their arduinos, because at points in recent history you have been able to get an entire wifi router for less than the cost of a wifi shield.

Get a very cheap module called ESP8266, particularly the ESP-01, then flash a program called esp_wifi_repeater (which uses the arduino IDE)
https://github.com/martin-ger/esp_wifi_repeater
I have tested it several times it is pretty fast and with a ESP to USB adapter it steps down 5vdc from USB to it's usable 3.3v of the module

Would you need 2 ESP8266 for a repeater? The ESP8266 only appears to have 1 antenna.

I tried flashing this on my esp8266 esp-015 and it wouldnt work for some reason. I got the binaries from the git repo and everything. No clue why it wont start

At this very moment, I'm making a repeater with an ESP01 and it's working great for IoT purposes. I've seen folks on Github saying it would have speed issues for regular browsing but didn't test this myself. @Leonardo, I only managed to flash my chips using esptool.py with -fs detect and -fm dout

the network parts are "owned"by the yun side of the board.
the yun acts like a mini linux pc, who can seperatly connect trough a bridge library to the arduino. so.. i think you could do it or make it a router that would probaply be easier, but this all wouldnt depend on arduino code, more depend on if there are WRT packages who can do this.. i thinks they should exist as this linux variant is in other routers too.
(better route then repeat btw, repeats puts delays on your entire lan)

authors: พี่พีช พัชรพล


text:
What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?
Datasheets

LED Matrix (p2): https://www.circuitspecialists.com/products/pdf/M105057CHR1.pdf
MAX7221: https://www.sparkfun.com/datasheets/Components/General/COM-09622-MAX7219-MAX7221.pdf

Convention

(Row, Col) Designates an LED at a particular row and column, following the convention set by the datasheet
{Anode, Cathode} Designates a anode/cathode pair to light an LED in the array
Assume that I've connected:
SEG_DP to pin 13
SEG_A to 3
SEG_B to 11
SEG_C to 10
SEG_D to 6
DIG_0 to 9
DIG_1 to 14
...
DIG_6 to 2

Question:
Suppose I'm interested in lighting (1,1). By the convention, I would have to source current to pin 13 and sink current from pin 9. What two bytes should I send to the MAX7221 to achieve this?
My Attempt:
I think it should be 0x01 and 0x80 (0000|0001|1000|0000) with MSB (D15 as it is referred to in the datasheet for MAX7221) on the far left. Code I tried using is below as an image. I checked the signals with a logic analyzer and verified that the SPI protocol was followed (I forgot to take a screenshot but I will provide one when I get a chance). The LED array did not behave as I had anticipated. All LEDs in the matrix were lit!

What about using a library? http://playground.arduino.cc/Main/LEDMatrix has a few. Even if you prefer to write your own code you should be able to find a few hints there.

Add a delay after setting the SS low. Also specify try adding PI.setDataMode(SPI_MODE0); and/or SPI.setClockDivider(SPI_CLOCK_DIV8);

can you explain the clock divider function? For reference, the MAX runs at 10Mhz and the MCU that I'm using (Arduino Uno) runs at 16Mhz