text:
Multiplication, division. What is wrong?
const unsigned long C1 = 30 * 1000;
const unsigned long C2 = (300 * 1000)/C1; // must be = 10

void setup() {
  Serial.begin(57600);
  Serial.println("\n-------");
  Serial.print("C1 = "); Serial.println(C1);
  Serial.print("C2 = "); Serial.println(C2);

  unsigned long V1 = (300 * 1000)/C1;   // must be = 10
  Serial.print("V1 = "); Serial.println(V1);

  long V2 = (300 * 1000)/30000; // must be = 10
  Serial.print("V2 = "); Serial.println(V2);

  int V3 = (300 * 1000)/30000; // must be = 10
  Serial.print("V3 = "); Serial.println(V3);
}

void loop() {
}

Arduino UNO printed in monitor console:
C1 = 30000   (ok)
C2 = 143164  (must be = 10)
V1 = 143164  (must be = 10)
V2 = 0       (must be = 10)
V3 = 0       (must be = 10)

What is wrong?

Hack long V2 = (300 * 1000UL)/30000; printed 10

300

and
1000

are integers.
What
long V2 = (300 * 1000)/30000;

really does is take the integers 300 and 1000 multiply them. This calculation overflows, and equals -27680. Dividing that by 30000 yields 0. What you added in your comment isn't a hack, it's the proper solution. By including the suffix L or UL you tell the compiler that you want longs, not ints.

What is wrong?

You are assuming that the expression is long int but it is actually int. The literals are int. You need to convince the compiler that the expression is actually long int. That can be done by cast:
((long) 30000)

or literal long integer syntax:
30000L

The AVR GCC compiler uses int defined as 16-bit. Expression and literals are implict 16-bit.
More on the representation of C/C++ data types, expressions, and calling conventions can be found here.
Cheers!

A good practice with literal numbers which you want to divide and multiply is to always define them as double, and convert them to integer when they are used. This is often the case with frequency/period constants. This prevents most catastrophic overflow / rounding errors that integer math would have, while allowing you to use consistent units in your definitions.
 #define F_CPU 16000000.0   // in Hz
 #define F_TICK (1.0/F_CPU) // in seconds
 #define DELAY 0.001        // in seconds
 #define COUNT ((uint16)(DELAY/F_TICK))
 Serial.println(COUNT);

Of course, you can calculate the number of CPU ticks per millisecond using fixed-point math, for example by defining the frequency in MHz and the tick time in nanoseconds, but you'll have to scratch your head every time you need to convert a period to a frequency and vice versa, and you'll have to change units the moment your frequency will not be a multiple of MHz.


text:
data type error on sensor data to ethernet client
I'm having a hard time debugging this piece of code, and i'm hoping someone can point out where i am making the mistake.

My serial output is:
connected
GetData()
got data...
next stage...

I've tested with a simple network client that loops sending a hello world, and it works fine. Every time this code halts after attempting to send a value to the client. I know that  getData() is causing the issue, but i cannot work out why, or how to best resolve it.
(apologies for the code dump, i want to be thorough)
#include <LiquidCrystal.h>
#include <dht11.h>
#include <SPI.h>
#include <Ethernet.h>
dht11 DHT11;
#define DHT11PIN 8

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server(192,168,1,100);
IPAddress ip(192,168,1,50);
EthernetClient client;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int trigPin = 6;
const int echoPinOne = 7;
const int echoPinTwo = 8;
const int echoPinThree = 9;
const int echoPinFour = 10;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
  delay(1000);

  //Network
 if (Ethernet.begin(mac) == 0) {
    Serial.println("DHCP FAIL");
    Ethernet.begin(mac, ip);
  }
  delay(1000);
  Serial.println("connecting...");
  lcd.setCursor(0, 0);
  lcd.print("connecting");
  connect();
}

void connect(){

    if (client.connect(server, 8080)) {
    Serial.println("connected");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("connected");

    client.println("hello server");
    client.println();
    delay(500);
    lcd.clear();
  }
  else {
    Serial.println("connection failed");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Connection Failure");
  }
  delay(500);
}

void loop() {

   //network
  if(!client.available()){
    Serial.println("lost connection!-restart");
    lcd.println("Disconnection");
    client.stop();
    connect();
  }
  else {

    int inp[5];
    getData(inp);
    Serial.println("next stage...");
    char *output = (char *) &inp[0];
    client.println(output);

    client.println("first");

    Serial.println("sent first...");

    //here repeats the same process for the other sensors - omitted for clear reading

  }
   //end network

   delay(500);
}

void getData(){

Serial.println("GetData()");
long durationThree, inchesThree, cmThree = 0;
long durationOne, inchesOne, cmOne = 0;
long durationTwo, inchesTwo, cmTwo = 0;
long durationFour, inchesFour, cmFour = 0;

//SENSOR ONE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinOne, INPUT);
durationOne = pulseIn(echoPinOne, HIGH);

delay(100);

//SENSOR TWO
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinTwo, INPUT);
durationTwo = pulseIn(echoPinTwo, HIGH);

delay(100);

//SENSOR THREE
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinThree, INPUT);
durationThree = pulseIn(echoPinThree, HIGH);

delay(100);

//SENSOR FOUR
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

pinMode(echoPinFour, INPUT);
durationFour = pulseIn(echoPinFour, HIGH);

//DISTANCE CALCULATION
cmOne = microsecondsToCentimeters(durationOne);
cmTwo = microsecondsToCentimeters(durationTwo);
cmThree = microsecondsToCentimeters(durationThree);
cmFour = microsecondsToCentimeters(durationFour);
//Serial.println("sending...");
//char *out = (char *) &cmOne;
//Serial.println(out);
//client.println(out);
//Serial.println("sent!");      used this to test - same issue

Serial.println("got data...");
inputBuf[0] = cmOne;
inputBuf[1] = cmTwo;
inputBuf[2] = cmThree;
inputBuf[3] = cmFour;

}

long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}

The code you posted is performing incompatible casts and by thus is sending garbage to client.println.
There is no automatic conversion in C/C++ from an array of integers (int inp[]) or longs, to a C style string char *. A C Style string should end with null terminator \0, and the one in your code doesn't. For example, in this line:
char *output = (char *) &inp[0];

The inp[0] contains the first integer. The expression &inp[0] contains the address of that integer in memory.
Thus the cast to (char *) will yield a malformed C style string, since it will not end with a null terminator, and more important, will not contain the data you expect it would (this cast is saying - "hey, compiler, note that the address of that int is actually the address of a C style string").
You can, however, utilize the String type constructor that receives int/long, and send the duration in order, something similar to:
        void getData()
        {
            ... // rest of the code here
            client.println(String(cmOne));
            client.println(String(cmTwo));
            ... // etc.
        }

I believe this is what i've been looking for! i'll test later tonight when i get to the project but i'm 95% sure this is correct :) thank you!

source: Stack Exchange

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

sort: votes


text:
Simple word translator, return error: invalid array assignment
I know this is not a good question. But I am clueless with this error : invalid array assignment (at function convert). For extra information, I involved a lot of copying/pasting programs I haven't exactly understand from internet in the convert function (the strncpy ones) so.. yeah.
This is the program I've done (the menu/mn button currently not used):
#include <LiquidCrystal.h>
#define WORD 11
#define LETTER 15
LiquidCrystal lcd(7,6,5,4,3,2);
int i=0;
char input[] = "a";
char output[15];
const int dw = 8;
const int ri = 9;
const int le = 10;
const int up = 11;
const int ok = 12;
const int mn = 13;
int checker = 0;
int bounceCk = 0;

int bdw=0, bri=0, ble=0, beu=0, beo=0, bem=0;

void setup()
{
  pinMode(dw, INPUT);
  pinMode(ri, INPUT);
  pinMode(le, INPUT);
  pinMode(up, INPUT);
  pinMode(ok, INPUT);
  pinMode(mn, INPUT);
}
void intext()
{
  int lim=16;
  lcd.setCursor(0,1);
  lcd.print(input);
  for(i=0; i<lim ; )
  {
    lcd.setCursor(0,1);
    lcd.print(input);
    if(digitalRead(dw)==HIGH)
    {
      checker=digitalRead(dw);
      delay(100);
      bounceCk=digitalRead(dw);
      if(checker==bounceCk)
      {
        if(input[i]>'z')
          input[i]='a';
        input[i]=input[i]+1;
      }
    }
    if(digitalRead(up)==HIGH)
    {
      checker=digitalRead(up);
      delay(100);
      bounceCk=digitalRead(up);
      if(checker==bounceCk)
      {
        if(input[i]<'a')
          input[i]='z';
        input[i]=input[i]-1;
      }
    }
    if(digitalRead(ri)==HIGH && i<16)
    {
      checker=digitalRead(ri);
      delay(100);
      bounceCk=digitalRead(ri);
      if(checker==bounceCk)
      {
        i=i+1;
      }
    }
    if(digitalRead(le)==HIGH && i>0)
    {
      checker=digitalRead(le);
      delay(100);
      bounceCk=digitalRead(le);
      if(checker==bounceCk)
      {
        i=i-1;
      }
    }
    if(digitalRead(ok)==HIGH)
    {
      checker=digitalRead(ok);
      delay(100);
      bounceCk=digitalRead(ok);
      if(checker==bounceCk)
      {
        lim=i;
      }
    }
  }
}
void convert()
{
   char sumber[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */
   char dasar[WORD][LETTER] = {{0}};  /* declare a progmem unsigned static array of kata x huruf */

  /* copy various strings to statically declared storage SUMBER */
  strncpy (sumber[0],"memakan", strlen("memakan")+1);
  strncpy (sumber[1],"makanan", strlen("makanan")+1);
  strncpy (sumber[2],"menyuci", strlen("menyuci")+1);
  strncpy (sumber[3],"perubahan", strlen("perubahan")+1);
  strncpy (sumber[4],"penulisan", strlen("penulisan")+1);
  strncpy (sumber[5],"tercampurkan", strlen("tercampurkan")+1);
  strncpy (sumber[6],"pengelompokan", strlen("pengelompokan")+1);
  strncpy (sumber[7],"pengembangan", strlen("pengembangan")+1);
  strncpy (sumber[8],"kehebatan", strlen("kehebatan")+1);
  strncpy (sumber[9],"memotret", strlen("memotret")+1);
  strncpy (sumber[10],"melakukan", strlen("melakukan")+1);

  /* copy various strings to statically declared storage DASAR*/
  strncpy (dasar[0],"makan", strlen("makan")+1);
  strncpy (dasar[1],"makan", strlen("makan")+1);
  strncpy (dasar[2],"cuci", strlen("cuci")+1);
  strncpy (dasar[3],"ubah", strlen("ubah")+1);
  strncpy (dasar[4],"tulis", strlen("tulis")+1);
  strncpy (dasar[5],"campur", strlen("campur")+1);
  strncpy (dasar[6],"kelompok", strlen("kelompok")+1);
  strncpy (dasar[7],"kembang", strlen("kembang")+1);
  strncpy (dasar[8],"hebat", strlen("hebat")+1);
  strncpy (dasar[9],"potret", strlen("potret")+1);
  strncpy (dasar[10],"laku", strlen("laku")+1);

    /* mencari input pada sumber */
  int k=0, search=0, sel=9;

  while(search==0)
  {
    sel=strcmp(input, sumber[k]);
    if(sel==0)
    {
      output[]=dasar[k]; //!!!!THE ERROR IS HERE!!! happen to either this or output=dasar[k]
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Base Word:");
      lcd.setCursor(0,1);
      lcd.print(output);
      search=1;
    }
    else
    {
      k=k+1;
      if(k>=11)
      {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Error:NF");
        lcd.setCursor(0,1);
        lcd.print("word n found");
        search=1;
      }
    }
  }
    /*
    //print the values
    while (*sumber[i])
        printf ("  %s\n", sumber[i++]);
    */

}
void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Type your word:");
  intext();
  convert();
  delay(15000);
}

I found more errors before, I've fixed those, but can't fix this one. I think this problem is caused by the wrong instruction or wrong format. But can't found solution...yet.
The program is converting words to its basic word in Bahasa, you can compare it to English like this. You type "eaten" and it will return "eat". You type "understood" it will return "understand". When you type "stunk" it will return "stink". Or something like that.
Example in bahasa :
"memakan" (eating) -> "makan" (eat)
"makanan" (food) -> "makan" (eat)
"pengembangan" (development) -> "kembang" (becoming bigger/better)
etc
I hope someone will give me a clear hint or two (I'm not too bright, but I still need to learn how not just copying things around),
Thank you very much!

It looks like you're trying to copy the contents of a particular sub-array in dasar across to the output array. However, this isn't valid in C/C++:
output[]=dasar[k];

To copy data from one array to another, you either need to copy each element one-by-one (e.g. in a loop), or use a block memory operation like memcpy.
Here's how I would do it:
memcpy(output, dasar[k], sizeof(output));

This should work because arrays are basically just pointers in C/C++. It uses the start of output as the destination of the copy, and uses the start of dasar[k] as the source. The number of bytes it copies is taken from the total size of the output array.

So the sizeof(output) means we can use it like this sizeof(strlen(output)) ?
Thank you!

No, sizeof(strlen(output)) doesn't make any sense. It would give you the size (in bytes) of the value returned by strlen(), which has nothing to do with the contents of output. Assuming the string stored in output is properly null-terminated, simply strlen(output) should tell you how many characters it actually uses.

The program above (at the question) will not make any null characters (I guess?)... and after some reading I think I got that sizeof is kind of like strlen, except it's counting any type of data? So it is interchangeable (as those string isn't null terminated?) with strlen? But now I got it clearly about memcpy. Thank you, thank you very much for your help. really thank you.

Your strncpy operations are adding the null terminators by copying them out of the string literals (string literals are implicitly null-terminated in C/C++). sizeof isn't equivalent to strlen though. sizeof gives you the size of any object, variable, or static array in bytes. strlen is only for strings, and it keeps counting characters until it reaches a null character (even if that means it goes past the end of an array).

Just replace the line in error with:
strcpy(output, dasar[k]);

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


text:
Power on reset with arduino uno can never happen. Can this be fixed?
When an Arduino Uno is powered on, the USB chip's DTR output pin may (is, in fact) low for a while.  This means that the capacitor C5 is connected from the 328p reset pin to ground.  Thus, when power is applied, the reset pin is held low for 10's of milliseconds after power up (while C5 charges) .
Thus, when the 328p starts, the reason for reset (the MCU register) always is "external reset", not "power on reset", even when  power turns on.
This can be fixed by removing C5, or opening the "reset en" jumper, but then the chip is never reset by the falling of DTR,...that is, bootloading is disabled.
Is there a solution that allows POR and external reset for the bootloader?
Thanks!

Don't use an Arduino with a '328p.

The problem is not the 328p, but the DTR associated reset circuit.  If for example, the USB chip powered up with its pins HIGH , the capacitor would not have to charge on power up.  Unfortunately, it looks as though the USB chip on the Uno powers up with its DTR pin low or tri-stated.  This causes the 328p to report that it received an "external reset", even on power up.

I know what the problem is. And the answer is to use an Arduino that doesn't use that chip. Choose one with an ATMega32U4. It doesn't have the DTR reset system.

I connect a 2n2222 with gnd pin and with res pin..
then if send 5v or HIGH pin from any pin by 1k resister arduino restarts...

User 58927: and in this way, you can reset the chip with an output command. However, the question is about the reset at power on of the Arduino being seen by chip as an “external reset”, rather than a “power on reset”.

I have answered my own question.
   I added a pull-UP resistor on the DTR line to VCC. Now capacitor C5 does not need to be charged up on power up: both sides of the capacitor start at VCC. Thus, the 328p recognizes a power-up as a "power-up reset", instead of an "external reset", and my sketch starts after 75-milliseconds or so on power up.
    Basically, my circuit is like PimV's diagram, but with the resistor RN2D to VCC, rather than to ground.  At least for the Uno, this fix seems to work.  I suspect this relies on the USB chip (mega16u) being in reset, and it's pins tri-stated, for a while after power up.

The RN2D pulldown is in the official schematic of the Arduino Uno Rev. 3.

Thanks. I Was not looking at the Rev 3. No wonder that node stays low on power up.

See 'DTR-reset' circuit of Arduino Uno below.
After powering-on, when DTR is set low (because a sketch is coming in) the falling edge causes a negative pulse on the 328P's external reset pin of ca. 3 ms (see here). The width of this reset pulse is independent of the time that DTR stays low.
During powering-on the 328P's reset pin is low until the capacitor C5 is sufficiently charged. How long this takes depends mainly on the start-up behavior of Vcc. When DTR is low the capacitor will charge faster because RN2D (from capacitor C5 to ground) is bypassed.
But the main thing is that the power-on reset and the external reset have the same effect (see datasheet): when the rising voltage passes a certain threshold a timer is started and after it times out program execution starts at 0x0000 or at the Boot Reset Address (depending on the setting of the fuses). So, in the powering-on situation it makes no sense to differentiate between Power On Reset and External Reset.

Thank you for your answer. However, there is a reason to differentiate between Power on Reset and External Reset.  The Optiboot bootloader for Arduino will start the user immediately on POR.  On External reset, it will wait and look for bootloading data from the serial port.  Thus, with the current Arduino UNO hardware, this feature of "instant start" in the bootloader cannot be used.

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


text:
Controlling arduino over webserver
I want to control arduino through Internet without using Ethernet shield. I know there is a way. So can you help me what things I'll be needing for that

I know there is a way. - what is this way of which you speak?

I don't want to use Ethernet shield

Well, what do you want to use?

I want to control lights through wamp server

Ah, great! Go down to the corner store and buy yourself a WAMP server.

I have a wamp server running in my system.. So how can I connect using php script

Your question - both of them - is really too vague to answer in any but a vague way. Say more about what you do want to do. You need to connect to the internet in some way; what ways will you consider? You've mentioned "a wamp server running in my system" - what system, and how do you intend for it to participate in this project? There's really not enough here for anyone to be able to offer much help.

This is incredibly broad: you could use an Arduino Ethernet, which has built in Ethernet, or you could use an ENC28J60 Ethernet module, or any of the many, many WiFi peripherals.
Also, consider using the ESP8266, instead of an Arduino with an Ethernet/WiFi peripheral. The ESP8266 can be programmed directly from the Arduino IDE with Arduino-style syntax, and can also run the NodeMCU firmware (programmed in Lua).


text:
Get the distance to non perpendicular surface
So I'm using the HC-SR04 modules to get the distance to objects, the problem is that if it's not a perpendicular surface I dont get any reading, and I assume that the reason is that the ultrasounds get reflected in another direction, so they don't come back to the sensor. What's the way to get over this issue?
Thanks in advance

To use a completely different sensor.

I'm guessing that the sensor sends only one column of sound, thus it would bounce off to another angle. I'm not sure how a light sensor would work...

SO what sensor would it be?

What is the surface made of & what sort of range are we considering?

The ideal scenario would be a room inside a building, so the range would be from some cm to a few meters. The surface any kind of material I'd say

The distance from a point to a plane is defined as perpendicular.

You mean to say that you get proper reading when the surfaces are FLAT?
Ultrasonic sensors have this property that the waves emitted from then are only 15 degree from the line of sight, but this means that you can surely calculate distance of objects having a curved shape. The only condition is the object should be directly in a straight line

That's not the issue.  Rather, when the surface is sufficiently canted, most of the energy bounces off in some other direction and not back at the transducer, meaning no echo is measured.  It's not entirely different from a mirror, or bouncing a ball off a wall.

Coming in late but seeing no solutions offered yet, I'll take a stab at it:
Assume your vehicle is traveling obliquely toward the wall.
Assume you can find and measure the perpendicular distance to the wall.
Then you can calculate the travel distance from those two measurements:

Next we need to find the angle between the vehicle's heading (center-line) and the perpendicular. A rotating sensor that senses return-signal strength could probably give good results but is mechanically more complicated. Given that the ultrasonic sensors have a somewhat broad sensing angle, 3 or 5 fixed sensors (1 straight ahead and 1 or 2 to either side) may work well enough if you're just trying to avoid hitting the wall. In that case you could measure with all of the sensors, take the least distance measurement as 'p' and the known angle of that sensor as 'theta'.
What's left is to decide how to make the calculation and work with cosines. For the rotating sensor case, you'll have to find the angle of the sensor at the time of it's smallest reading, and look up in a table (or calculate) the cosine of that angle. For the multiple fixed sensors case, you already know the sensors' angles and therefore, their cosines.
If you have enough code memory it would easy to write your calculations in floating point, certainly for some quick and dirty testing. If not, or you need to speed up the calculations, you can do it in fixed point with less code. it's a little bit harder for the programmer but much easier and quicker for the MCU.

Please note that ultrasonic sensors tend to interfere with eachother depending on environments and how close they are pointed to eachother in degrees and how close a wall is

Yes, they would need to be pinged sequentially, and the smallest reading taken.


text:
collecting & visualizing sensor data - best approach?
I'm working on a kite-related project where I'm using Arduino + accelerometer to track data while a kite is in the air. I am struggling a little with the best approach - help on the following questions / issues would be a huge help:
-- how best to grab data only while the kite is in the air? just detect with numbers, use a switch? other ideas?
-- how best to collect the data and transfer to computer for visualization (likely with processing but looking at other options). i'm using this project in workshops with kids in low-income neighborhoods in brazil, so will have limited resources. a laptop will be available -but use of mobile also ideal.
Thank you!
Claudia

Since it's battery powered, you probably want to have a power switch anyways. Also, wouldn't it be interesting the detect the preparations and launch from the data visualization? Like; here it is lying on the ground; here is the person walking with it; here is where it's thrown up; etc.

YES! that's a nice idea - to visualize the full experience. thanks for the input!


text:
Openlog + Lilypad Simple board - not writing to SD card
I'm desperately trying to get my openlog to work and write data out to a micro SD card with no luck.
I'm using a battery-powered lilypad arduino simple board and have attached L-shaped female headers to to the openlog to plug it right in. I am also using an FTDI breakout with the lilypad to download code and that is working. I think i have matched the RX and TX properly by flipping the openlog over as it pictured in the images attached. I'm using the example code included on the sparkfun openlog page just to test:
https://github.com/sparkfun/OpenLog/blob/master/firmware/examples/OpenLog_Test_Sketch/OpenLog_Test_Sketch.ino
There are no lights lit on the openlog which might indicate a power issue - but it's super unclear.
Any ideas or help very welcome!

Are you sure all the pins match up, except for TX/RX?

In your picture you are using a 32  gig card. In addition to being expensive overkill, that is probably SDXC and may not be something the logger supports.

It's not overkill, it's a card I already had using it in camera. That's not the issue - it's not getting power.


text:
Fade LED strip using proximity and map() function
I'm using a sonar sensor to detect proximity, and need to control the brightness of an LED strip in direct relationship to the distance detected. For example, as someone moves toward the sonar, the strip needs to dim.
I'm using map() to do it now crudely but it's way too abrupt and I'm not sure how best to achieve the effect I'm looking for. Ideally, as the person moves toward the light, it very smoothly fades out in relationship to the person's movement/pace.
Initial thoughts / questions:
-- Can I use a more refined number type to set the LED brightness other than int?
-- Do I need to do something more complex where I detect the delta in the person's movement and use the loop to fade the LED from one value to another? Seems complicated...
Any help / ideas on this would be much appreciated! Existing code is below if it helps.
Claudia
//variables needed to store values
long pulse, inches, cm;

//LED VARIABLES
int frontPin = 6;    // front strip connected to PWN pin 5
long interval = 8000; // interval at which to do something (milliseconds)
int val;

void setup() {
  //This opens up a serial connection to shoot the results back to the PC console
  pinMode(frontPin, OUTPUT);
  pinMode(pwPin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //Used to read in the pulse that is being sent by the MaxSonar device.
  //Pulse Width representation with a scale factor of 147 uS per Inch.

  pulse = pulseIn(pwPin, HIGH);
  //147uS per inch
  inches = pulse/147;
  //change inches to centimetres
  cm = inches * 2.54;

  if (inches < 36){
    detect();
  }
}

void detect(){
  Serial.print(inches);
  Serial.print("in, ");
  Serial.println();

  val = inches;
  val = map(val, 6, 36, 0, 255);

  analogWrite(frontPin, val);
  Serial.print("mapped value is ");
  Serial.print(val);

  delay(500);

}

The biggest problem is that by forcing the code to use integral inches you've restricted it to 31 discrete values. And since the brightness response of a PWMed LED is non-linear you effectively have very large steps in brightness when the LED is dim.
pulseIn() has much more flexibility with regards to its range so use the raw value directly instead of converting it to "pretty" values.
val = map(pulse, ..., ..., 0, 255);

I agree about the step size, however sub-inch measurement may not be a full solution.  Non-linear mapping may be needed.  Something in the time domain, which ramps the level up or down one step at a time (with delay) to seek a function of the current distance or recent average thereof might or might not also help.

Thanks Ignacio!! I gave it a shot and it needs a little tweaking but gets me closer. However, to Chris' point, it still seems a little abrupt as it shifts. Chris - any tips on approach to what you're talking about? I think that's where I probably need to go...

@claudybee: Implement a lookup table using one of the formulas in the linked question. Don't be afraid to use more than 256 values if it ends up working better.


text:
Need a simple accelerometer visualization example!
I'm doing a project using the ADXL335 accelerometer from SparkFun. The actual project I'm using P5 and it's working great. I'm running workshops in parallel and want to demo the chip in real-time but am currently out of time to build something from scratch. I'm desperate for a simple processing (or something else) sketch that takes my x, y, z values being printed to the serial port from Arduino and visualizes them in some way. Can anyone point me to anything that won't need a lot of coding time and effort just now?
Thank you!
Claudia

After some quick searching I found an Instructable which uses your same sensor and plots the data thanks to a Python script. You'll need to install Python if you want to replicate this project, but any programming language with a drawing library will work.

https://learn.adafruit.com/ahrs-for-adafruits-9-dof-10-dof-breakout/visualizing-data

Here's my Python implementation.
It's desined for AOK-D but can be easily converted to work with external sensor
IMU+AHRS

A simple and fast solution would be implement a chart using a JavaScript library called Chart.js. it is simple and you can visualize your data in realtime.
Try node.js to make the back-end by communicating via serial (serialport package is good) and send the data using socket.io.
It is simple and you can set everything in less than 2 hours.
Chart.js
I recently made some video tutorials about this and you see them here. The audio is in Portuguese but you can just skip and go directly to coding sections.

All great answers - thanks for each of them!! A processing forum user provided me with a processing script that worked great for my purposes. You can view the thread here:http://forum.processing.org/two/discussion/comment/40648

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


text:
Timer1 arduino makes Serial not work
Running the code below, when I send any character in the Serial arduino is not printing "a" back. I think it's something wrong with the timer1 code but it should work cause this code was given by my teacher in C class.
ISR(TIMER1_COMPA_vect){

}

void setup() {

    Serial.begin(115200);

    //http://www.instructables.com/id/Arduino-Timer-Interrupts/?ALLSTEPS
    noInterrupts();
    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1000000hz increments with 8 bits prescaler
    OCR1A = 1;// = (16*10^6) / (1000000*8) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS11 bit for 8 prescaler. Each timer has a different bit code to each prescaler
    TCCR1B |= (1 << CS11);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);
    interrupts();

}

void loop() {

    if (Serial.available()) {

     Serial.println("a");

    }

}

does it work when you take all the timer register code out?

yes it works fine.

OCR1A = 1 is a really really low value. This will mean almost all the time is spend inside the ISR routine (called once every 16 clock cycles). Try with something higher first (e.g. 255).

Another question is: what will go inside your ISR? Its empty here but what do you have planned for it. Spending too long in an ISR is bad news

This is a more complicated question than the standard Arduino questions, so I took a lot of time to look into it and find out the exact answer--since I was also curious. I have posted a very thorough answer to your question here on Stack Exchange, so please look there: https://stackoverflow.com/questions/28880226/timer1-arduino-makes-serial-not-work/28887781#28887781
I should also note that Gerben's comment is spot-on. I recommend a value no less than 20, since you configured the counter to increment once per 0.5us. This way, a value of 20 only calls the ISR every 10us, which should keep the ISR from occurring so often that it locks up your code.  As you'll see in my link above, the other main problem is you forgot to define your ISR function that is required when you enable the interrupt.
If this meets your needs, please put a green check next to my answer to mark it as correct.


text:
Op Amp Understanding + Holiday Lights Tutorial
I am following Jeremy Blum's tutorial for Holiday Lights: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds
I am just trying to set up the circuit for one of the audio channels. I believe I followed the breadboard schematic. However, when I connect the Arduino the power, but without any audio input, the LED lights up. I would've thought that would not be the case.
Can someone help me correct my understanding here? Thanks.
Image of my breadboard: http://postimg.org/image/ibqfvezqp/

Did you try adjusting the trim pot to reduce the gain?

Per Jeremy Blum:

If the input doesn’t have a audio input plugged in, then it’s said to be “floating” and you >can’t really count on the circuit to do what you would expect. The audio input connection >introduces a known voltage (0 when no sound is playing) connection between the positive op->amp input and GND that we then amplify. Try connecting the input to GND and you should see >the LED turn off.

Source: http://www.jeremyblum.com/2011/12/25/tutorial-14-for-arduino-holiday-lights-and-sounds/comment-page-2/#comment-1373392


text:
How to know if my Bluetooth HC-05 is connected through serial monitor
I want to connect a Bluetooth module to arduino and check if my module is connected or not.. Through serial monitor. Is there and particular code to connect with that?

If your board is actually a HC-05, you can

Pull the KEY pin to Vcc (see note)
Write the serial command AT on the serial interface
Look at the output: if you receive AT or OK then the module is connected, otherwise it is not

Note: The key pin is the number 34 on the SMT module (with the antenna pointing upwards, its the pin in the top-right corner). If you have a THT module (so the one with about 6 pins) MAYBE this pin is connected to one of the pins you don't usually use (they are named EN, STATE, ...). Check with a multimeter if it is connected to one of these. If it is not, then you'll have to solder a wire from it to an arduino pin.
If, on the other hand, your board is a HC-06 (almost identical to HC-05, but with a different firmware - it is a slave-only bt device), then keep it disconnected from the master and perform steps 2 and 3: when not connected, in fact, the HC-06 is already in AT mode.
More information on this webpage


text:
Can not connect with Bluetooth hc-05
I connect my Bluetooth hc-05. But the blind led in the Bluetooth module is not stable when I connect with my Android phone. Help help me to solve this.

It is very simple really.
Initially the Bluetooth got paired automatically with my Android, but apparently the variable transmission was not complete.
If this is the case with your module,it will be blinking with high frequency.
So here is what I did:

Hit the RESET button on HC-05 once
Go to Android Bluetooth Settings and UNPAIR HC-05
Now Pair it again by clicking on it
You will be prompted to enter password- '1234'
Open your Bluetooth Terminal and you will find your data appearing
on Android

P.S.-A 2 Hz blinking frequency on HC-05 should signify proper connection

Through which android app you are connecting because normally android only pair and will connect to device if you are sharing some data or files or you can connect to android device using any bluetooth app like bluetooth terminal or dual bluetooth chat

I'm using BT voice


text:
How to control Adruino through Internet
I want to control my Adruino through Internet without Ethernet or wifi shield. So what are the ways I can do?

Guess you need to use a pc, and a program to receive commands and send them along to the arduino by serial.

So can you tell me how to do that.....

You need a backend that will listen for incoming commands. You can start with Django or Ruby on Rails or some microframework. The backend residing on PC should forward commands to Arduino board.

You need access to the Internet. Since you dont want to use an Ethernet or WiFi shield/module, then, for the most part, you are left with:

Using a GSM module with the Arduino to receive data over the Internet
Using a PC as a web server to receive data over the internet and forward it to the Arduino over a wired connection (UART) or a wireless connection (e.g. bluetooth)

The most direct would be the second method over UART. So it could be seen like this: Client/Sending PC -> Over the Internet -> Server/Receiving PC -> Over UART -> Arduino. So you are now faced with 3 main interfaces: Internet->PC for the server and client as well as the PC->Arduino interface on the server/receiver side.
To handle the Internet -> PC interface for the client, the client PC would need to run a program that will connect to the server PC over the Internet (using the server's public IP) and send the Arduino control data. Similarly, the Internet-PC interface for the server PC would require a constantly-running server program that will listen for incoming connections from the client PC and receive the data being sent. Assuming you know Python, with Python you can have both programs up and running within minutes. This site should help with the programs.
Note that port forwarding will need to be implemented on the router on the server side so that packets from outside its local network can get to it, given that its behind a router. This software can help with setting port forwarding rules.
The PC->Arduino interface will require the pyserial package (if you're still using Python). Pyserial can be used to forward the control data received over the internet, to the Arduino over Serial UART. This site should help with using Pyserial for Python 3. Search for other tutorials.
Finally, the Arduino itself must regularly check the Serial buffer for any received characters from the PC. It must then act on the received data, depending on rules you should have established. A simple example would be: 'a' = Write HIGH to pin 13. This means if ASCII char 'a' were received over Serial, the Arduino would interpret this to mean a command to digitalWrite(13, HIGH). You can make use of the built-in serialEvent() to regularly poll the serial buffer. A simple sketch to illustrate this:
void setup(){
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop(){}

void serialEvent(){
  if (Serial.read() == 'a')
    digitalwrite(13, HIGH);
  else  //any other character turns off the LED
    digitalWrite(13, LOW);
}

This is, by no means, the only way to do this, only very straightforward IMO. For example, you could also upload your control data to some cheap server and have your PC regularly poll that server for any new commands. Of course, this would be greatly simplified if you decided to use a WiFi module, like the cheap ESP-01, directly with the Arduino.

I heard that through Processing IDE we can connect with adruino.  How how it is possible?

@user18794 yeah, i forgot that...you could use Processing to receive data over the web and then send this control data to the Arduino over UART. Check here (https://processing.org/reference/libraries/net/) for more details on using Processing for the web.


text:
How to remote control Arduino using an old 2.4Ghz toy remote controller?
I have been wondering how to remote control my arduino robot using an old 2.4ghz car toy transmitter which has 4 buttons, up down left and right.
I have the nRF24L01(+) 2.4GHz transceiver to use it as a receiver.
Is there anyway to detect the signals going out from the remote controller and use them to make my arduino works,
I am a newbie so i am sorry if any mistake.
Thanks guys!

You have two options:

Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.

Its actually not entirely impossible that the existing system is on-air compatible with an nrf24l01 - many are based on workalike chips and have been reverse engineered.  But without recognizing it as one of the known schemes for compatible chips, or recognizing the chip used and sniffing its spi traffic to determine the scheme, steps like you recomend would indeed be necessary.  The fact that it has buttons and not proportional sticks may point to a cheap, unique chipset and not a distinct MCU and transceiver.

@ChrisStratton Not impossible, granted, but either not likely or, as you say, too much work to decypher the protocol. Chances are it's all just a CoB anyway.


text:
SD card initialization fails randomly
I have a SD card reader that is working fine exept that sometimes SD.begin fails for no apparent reason.
To work around this issue I have put the SD.begin in a while loop and then I display the error on my LCD. When the error happens I then remove and reinsert the card witch works usualy on the first or second try. I have never seen any problem ones the card is initilized.
Does anyone has any idea what might be the problem?

Which reader? Link? Possibly you are running too fast a clock for it. There are means of slowing down the SD library.

https://www.arduino.cc/en/Main/GTFT I do not use the TFT but only the SD card reader. If SPI where to fast should I not see random errors after a successful init when reading and writing to it to?

I don't know. There have been reports that some SD cards work better than others. During initialization there might be negotiation about which protocol to use. Possibly try adding a small delay in setup to give the card time to power up.

I have seen SD cards that do not like this section of code:
  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

Some SD cards (mine, of course) seem to need a little quiet time to finish their INIT process.  Adding a delay of <something> made the INIT process complete successfully, first time through the loop.
I'm guessing that the SD card spends so much time handling the repeated CMD0 commands (continuously sent by above loop) that they don't get to spend time on the INIT process.  IIRC, the standard says the card is allowed to take up to 2 seconds to INIT (!).  I can't recall, but I think I tried 150ms or so:
  // command to go idle in SPI mode
  while (cardCommand(CMD0, 0) != R1_IDLE_STATE) {
    delay( 150 ); // let SD get some time to work
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
      error(SD_CARD_ERROR_CMD0);
      goto fail;
    }
  }

I do recall that reinserting the card would sometimes make it work.  I have suggested this to at least one SD card library maintainer, but I think we're all reluctant to impose a delay on all cards.  OTOH, it is just during ::begin.
It might work for you, though.  The above snippet is from SdSpiCard.cpp, but you may have to go looking for it in other places, depending on which library and version you're using.


text:
What variables to declare for controlling a motor with high power motor controller
I was getting started with programming a motor controller with the Arduino Uno, in this case it's a mega motor shield (the motor driver shield I'm using).
The problem I have doing this is that I'm not sure what variables to use for the motor which is connected to two outputs labeled MA and MB.  I used motorValue to set the speed previously and used motorPin for writing the speed with the Arduino and a breadboard, but I'm not sure what to use in place of that for the motor being connected to the driver shield outputs.

Do you care about both direction and speed?

Variables are just names assigned to numbers. The names, as far as your program is concerned, are completely meaningless.
It's the numbers you assign to the variables and, more importantly, what you do with those variables that is important.
Your shield seems to have jumpers to select what I/O pins perform which function, so you just need to write the software to control the chosen I/O pins in the right way.


text:
How to deal with launch4j error
It seems that the last several times I've tried to open Arduino IDE I've encountered an error that says Launch4j, "an error occurred while starting the application".  It takes some time before that happens.  I think I've seen some stuff online about this, however I've seen some mixed answers and results for how to solve that problem.  I'm using it on a Windows 7, 64 bit system.  I've tried opening it up while my Arduino was connected and it didn't work.


text:
Why does this method return an unprintable character, how do I convert it to display correctly?
Page 14 says that the method should return the value 'h17'
typedef struct  {
  uint8_t data;
  uint8_t timestamp;
  unsigned char crc;
} tData;

int main(void)
{
  unsigned char* tempData = "snap";

    for(;;)
    {
      tData payload;
      payload.crc = crc8(tempData,sizeof(tempData));
      UDR0 = payload.crc;
    }

    return 0;
}

Because “h17” is an unprintable character, namely ASCII ETB. The 'h' in “h17” stands for “hexadecimal”, like the 0x usually used in C.
You should convert the value to an ASCII number if you want to print it, using for example Serial.print(payload.crc, 16); or – if you are not using Arduino core – (s)printf().

Edit: here is an implementation of my comment “sprintf() into a
buffer and dump the buffer to UDR0 one byte at a time”:
#include <stdio.h>

void print_byte_in_hex(uint8_t byte)
{
    // Print the byte in ASCII into an internal buffer.
    char buffer[8];
    sprintf(buffer, "%02x\r\n", byte);

    // Send it one byte at a time through the USART.
    for (char * p = buffer; *p; p++) {
        loop_until_bit_is_set(UCSR0A, UDRE0);
        UDR0 = *p;
    }
}

I'm not using Arduino core in this instance. What is (s)? So something like: UDR0 = printf(payload.crc)

@SensationSama: I mean you either sprintf() into a buffer and dump the buffer to UDR0 one byte at a time, or you set up stdin to print through the serial port and then do something like printf("%02x\n", (unsigned int) payload.crc).

Okay great. Can you spoon feed me the buffer process a bit?

@SensationSama: done in the edit, but not tested.

Thanks, seems to work perfectly! One last follow-up question. If h17 is hexadecimal, and the decimal equivalent is 23, than why is my terminal printing 99?

@SensationSama: Hard to say without seeing the whole program. What does it print if you print_byte_in_hex(0x17)?

You're able to see all the code that is interacting here. That parameter results in a print of 17.


text:
Expected Initializer?
I keep getting the error "Expected initializer" at different points in my code whenever I try to verify it. Currently, the error exists before "void setup." How can I fix this error and not allow it to happen in the future?
int ledPins[] = {9, 8, 7, 6};
int index;
int currentLED

void setup();
  {
  pinMode(Led1Pin, OUTPUT);
  pinMode(Led2Pin, OUTPUT);
  pinMode(Led3Pin, OUTPUT);
  pinMode(Led4Pin, OUTPUT);
  pinMode(Led5Pin, OUTPUT);
  pinMode(ButtonPin, INPUT);

  Serial.begin(9600);

  //Start a new game.

 for(index = 0; index <= 4; index++)
  {
    pinMode(ledPins[index],OUTPUT);
    // ledPins[index] is replaced by the value in the array.
    // For example, ledPins[0] is 2
  }
}

void loop()
{

  oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

}

void oneAfterAnotherNoLoop()
{
  int delayTime = 200; // time (milliseconds) to pause between LEDs
                   // make this smaller for faster switching
  // turn all the LEDs on:
  int Index;

for (Index = 0; Index <=3; Index++) {
  digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
for (Index = 3; Index >= 0; Index--) {
    digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
}

void loop();
{
    // Check if the button is pressed at the right moment

   if (digitalRead(10) == 0)
   {
    if (currentLED == 8)
    {
      // Blink the orrect (green) LED
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
      delay(200);
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
    }
    }
  }

For starters, int currentLED is not a valid C++ declaration: you're missing a semicolon. On the other hand, void setup();{} has an extra semicolon which should be removed.

int currentLED

You are missing a semicolon there.

void setup();

There should not be a semicolon here.

Do some tutorials on the C or C++ language. They will help you.


text:
Connect Arduino to Galaxy S2 using USB OTG
I want to connect an Android Galaxy S2 phone to my UNO Arduino using USB OTG functionality.
I can upgrade/root the android to any version I want. My goal is to be able to communicate between the devices (send/receive data).
I've tried to search for whether that's possible but found conflicting answers whether Galaxy S2 and the Arduino UNO would be able to be connected this way.
Anyone knows whether this is possible? If yes - Do I need to do anything special - such as rooting the device, flashing it to a certain rom or something like that?
Thanks in advance!

This is off topic here, as it hinges on Android capabilities and development, not Arduino.  The proper site is stackoverflow itself, where you will find it has essentially already been answered.

@ChrisStratton I disagree about this being off-topic here. While it may be primarily an issue for the Android side of things, I think it's still a relevant question about the practicalities of using Arduino.

No.  Given how the SE system works, it's off topic here because as fundamentally an android question it is already answered many times on SO.

If you use a bluetooth serial module - e.g. google hc 06 - you can do it wirelessly. I have a had good results with this - you can hook it up to pins 0 & 1, then use the stock arduino serial code. Probably not a good idea to hook up to both the bluetooth module and the USB (e.g. for programming) at the same time, they may interfere with each other.

Method 1. Basically you do not need root permission to communicate over USB. I am making app for Android for my project and using this FTDriver
Method 2. If you are not programming in JAVA then you can try third party apps like:

Arduino Uno Communicator

Uno doesn't have FT232 chip so I found it a bit harder. So instead I have FT232 chip and use SoftwareSerial.
Method 3. To communicate with Arduino you can use Bluetooth with HC-06 module. There are lots of third party apps to connect and send/receive data. Bluetooth Terminal

In my opinion, you have to use this shield to do this: http://arduino.cc/en/Main/ArduinoUSBHostShield
We can't plug in to use Flash Memorys into Android Phones micro USB via OTG Cable. I guess, tablets and maybe phablets can do that because these devices have USB Host Circuits inside. On the link, there is USB Host library for examples. This shield can attach onto your Arduino Uno.
Edit: I have already tried to do this by doing right like you. I couldn't find any solution then I get the shield, but I still can not do to make any control from both Arduino Uno and my Android phone. Anyway, I know this is about our phones not to have USB Host Component

That distinction is untrue.  Many phones have USB host, while many tablets do not.


text:
Calibrate motors using arduino
I'm trying to create a car that's being controlled by an Arduino.
I'm using the following chasis:
http://www.aliexpress.com/item-img/New-2WD-car-chassis-DC-gear-motor-wheels-easy-assembly-and-expansion-car-toys-robot-toys/32310649967.html
And L298N motor driver.
The problem is it's hard to make the car go straight. Giving the same PWM value to the motors still makes them spin in different speeds, trying to calibrate the value is hard and every time I recharge my batteries the value changes.
What are my options on making the car go straight when I want (well, sometimes I'll want to turn it around of course)?
I've thought about using an encoder but I wish to avoid that since it will complicate the whole project, is there any other viable option? and even when using an encoder, Does it means I will need to keep track all the time and always adjust the motors value continuously? is there some built-in library for that?
Thanks in advance!

You may find Robotics Stackexchange also useful for questions like this.

With a separate motor for each wheel, a couple of encoders and a feedback loop seem unavoidable.

You might be able to use a "hall effect sensor" or "reed switch" and a magnet. It won't be as pretty as a encoder. But it can be used to sync both the wheel speeds.

@my past self. It sounds fairly stupid to use a hall effect sensor near a electric motor. (Never mind that suggestion.)

An old method is that if you have access early in the gear train where speed is high and torque low, a pair of magnets can mechanically synchronize two motors when their drive is comparable but still allow them to turn at substantially different speeds/directions when driven differently.

I used a simple optical encoder and the little disks that came with my kit.  The encoders cost < £1 for 2 of them.
Failing that use an accelerometer and measure the lateral motion, should also cost about £1.

Modern tiny $20 toy quadcopters use a magnetometer to maintain a steady heading.    Duplicating that effect could be cheaper and more reliable than dual encoders.  On certain surfaces, like carpet, even perfect encoding with perfect voltage and wheels can't guarantee maintaining the heading.
One viable option might be to drive one wheel with your control system, drive the other wheel to maintain the magnetometer heading, and then steer by adjusting the target heading.

Actually the cheap ones try to integrate the gyro.  Magnetometers only come in at a higher price point.  Even if you do get a magnetometer it will be harder to interpret and more interference prone than encoders.  But it is possible with care if an external reference is what is desired.


text:
Arduino cannot communicate with PC after running servo
I was messing around with my arduino uno r3 and servo today. The book I got said to run the servo through the arduino. Everything was fine. I started changing the code, and then things started to get bad. I noticed that if I did not put a delay in between the servo movements, the board would freeze, and I would have to get lucky. Well now I just can't communicate with the board. I plug the board in to my pc, windows 7 makes the connection sound, the board turns on the ON light, the L light flashes, then goes steady. In the arduino software, the COM3 port, which is where I'm plugging it in, is not coming up. Only COM1 is there. I'm not sure what to do. The board is still functioning, the servo moves. I tried to plug it in with a different port and with the servo disconnected but it still doesn't want to communicate with my pc. The code I'm using is below
#include <Servo.h>

Servo servo1;

void setup()
{
  servo1.attach(9);
}

void loop()
{
  servo1.write(50);
  delay(500);
  servo1.write(90);
  delay(500);
  servo1.write(140);
  delay(1000);

  for(int i = 50;i<140;i+=10){
    servo1.write(i);
    delay(10);
  }
}

I would also like to add that I understand that you shouldn't run the servos through an arduino. I was following the book, and began researching when things went down hill.

Look at your serial devices or unkown devices in device manager.  It only takes a pullup resistor to get the device sound, quite a bit more has to be intact for a functioning port.

I've had some problems in the past reprogramming my Arduino Uno if it writes to the serial port - I don't know if the problem is the same, but here's how I got around it:
Option 1: Hold down the reset switch, then plug your Arduino into the USB port. Select the right COM port (if needed), compile your code (something ultra simple, e.g. blink led), and then, JUST BEFORE IT STARTS UPLOADING, release the reset switch. Wash, rinse, repeat, until you get it to work, through blind luck.
Option 2: Get hold of a ICSP (such as the one I got, USBASP made by FreeTronics  http://www.freetronics.com.au/products/usbasp-icsp-programmer-for-avr-arduino#.VL8Vv3WjlIc which I am v. happy with), plug it into the serial port, plug the other end onto your Arduino UNO ICSP header (6 pins, opposite end of the board from USB), then select Tools -> Burn Bootloader. Overwrites any program, works 100% of the time. Now you can unplug your USBASP, and plug your Uno back in and program it normally. This is also a great tool if you end up using AtMega (or AtTiny) chips directly (AtMega is the chip used to do all the work on the Arduino).
To avoid this, I have gotten into the habit of putting a 5 second delay as the first thing in the startup code.
FOR FUTURE GENERATIONS: I got mine here in New Zealand, so that will probably not help most people. FreeTronics makes them, and I am very happy I got their one (they have a "slow clock" jumper that is very convenient when programming Atmel chips not on an Arduino board), I expect that any USBASP would do the trick too - in response to the question, Amazon has a couple under $4, and I expect that the price will not go up.
Search for "USBASP". Make sure you get a ribbon cable. For Arduino Uno, you need a 6-pin ribbon cable. It is also possible to use these cables to communicated directly with a running Arduino over these same pins.

I would do option 1 however I cannot select COM3/4, which is where I plug my arduino in. Can you point me in the direction of an USBASP. Preferably an Amazon Prime item so that I can get the product quickly.

It just started communicating with the pc again... strange but thankful. Quickly added what you suggested (the 5 second delay) to the start. Thanks for the help.


text:
LED and LCD game
I am making a game where four different colored LEDs are flashing randomly, and when the green LED lights up, the user presses a button. If the user pushes the button when the LED is green, I want my 16x2 LCD screen to record points. And when the user presses the button on the wrong LED, i want the LCD screen to start over at "0 points."
Can you give me some place to start on a code that will feed "data" from  each time the button is pushed to the LCD screen?

Welcome to Arduino SE! Could you please explain further what have you triedand did the examples work that are included with the LCD library?

You need an example that shows you how to right to a screen and an example that shows you how to detect a button press, also you need to be able to light LEDs.  These are all examples supplied with the Arduino IDE, are you using that?  Look at each example in turn, setup the circuit get to understand them, then disect them and understand how they work and can get them to do what you want.
Button presses can be trouble some, you may need to investigate denouncing, either software or hardware.
Hope that gives you a starting point.


text:
"Return" Code Not Working
I'm trying to experiment with a "return" function. Yet each time I try to run my program, there happens to be an error, like "expected declaration before '}' token."
Can someone explain the basics of a return function, and look at my code below to possibly see what the problem could be?
{
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;
else{

return 0;
 }
}

What is the line int checkInput(); supposed to achieve?

return isn't a function, it's a statement. In case the answers didn't make it clear, you change int checkInput(); to checkInput();

That piece of "code" is, I am afraid to say, complete gibberish.
Passed through Artistic Style to reformat it ends up with:
{
    int index;

    pinMode(10, INPUT); //button input

    int checkInput();

    if (digitalRead(10) == 0) {
        return 1;
        else {
            return 0;
        }
    }

Starting from the top of the program the errors are:

You have a bracket hanging at the front of the snippet for some reason
int checkInput(); is a function prototype (forward declaration) and doesn't do anything other than tell the compiler that you will define this function somewhere else in your sketch.
You are lacking the balancing bracket for the first portion of your if statement, so your else { return 0; } never runs.
There is no balancing bracket for the strange one by itself at the start of the snippet.

In short, I have a feeling you need to learn the basics of C syntax.

It has nothing to do with the retun statements. You have to close each { with a }. you are missing one.
   {
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;}
else{

return 0;
 }
}

authors: مؤسسة الصيعري


text:
Posting Arduino data via ethernet to PHP server problems
I am currently having difficulties sending data from an Arduino using an ethernet shield to a PHP database in MySQL. My problem is that it appears that the server is receiving the data as there is a time stamp when I send it from the Arduino however, the other values it is receiving are incorrect (see images below). The server says the values of "data", and "serial_number" are 0 but they are supposed to be 10 and 24. Along with that the Arduino is saying that the data has been sent successfully. My code for both the server and the Arduino is listed below. Any ideas on how to fix this or what is going on are much appreciated.

Arduino Code:
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x00, 0xAB, 0xBA, 0xBC, 0xDD, 0x02 };
EthernetClient client;
String data;
int t;
int h;

void setup() {
  Serial.begin(9600);
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  Serial.println("still working here");

}

void loop() {
t = 10;
h = 24;

data = "temp1=";

data.concat(t);

data.concat("&hum1=");

data.concat(h);

  if (client.connect("www.smartwater.x10host.com",80)) {
    Serial.println(data);
    client.print("POST /add.php HTTP/1.1\n");
    client.print("Host: www.smartwater.x10host.com\n");
    client.print("Connection: close\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(data.length());
    client.print("\n\n");
    client.print(data);
    Serial.println("Successfull");

  }

  if (client.connected()) {
    client.stop();
  }

  delay(20000);
}

add.php (Server Code)
<?php
    include("connect.php");

    $link=Connection();

    $temp1=$_POST["data"];
    $hum1=$_POST["serial_number"];

    $query = "INSERT INTO `Main` (`data`, `serial_number`)
        VALUES ('".$temp1."','".$hum1."')";

    mysql_query($query,$link);
    mysql_close($link);

    header("Location: index.php");
?>

connect.php (Server Code)
<?php

    function Connection(){
        $server="localhost";
        $user="smartwat_arduino";
        $pass="*****";
        $db="smartwat_Main";

        $connection = mysql_connect($server, $user, $pass);

        if (!$connection) {
            die('MySQL ERROR: ' . mysql_error());
        }

        mysql_select_db($db) or die( 'MySQL ERROR: '. mysql_error() );

        return $connection;
    }
?>

index.php (Server Code)
<?php

    include("connect.php");

    $link=Connection();

    $result=mysql_query("SELECT * FROM `Main` ORDER BY `timeStamp` DESC",$link);
?>

      <title>Data</title>

Stuff

             Timestamp
             Data
             Serial Number

      <?php
          if($result!==FALSE){
             while($row = mysql_fetch_array($result)) {
                printf("
  %s 	  %s  	  %s
",
                   $row["timeStamp"], $row["data"], $row["serial_number"]);
             }
             mysql_free_result($result);
             mysql_close();
          }
      ?>

In your Arduino code, the function call that send the real data within the HTTP-POST call, is this:
[...]
client.print(data);
[...]

When executed, the content of the data variable is sent to the server.
Supposing data is a String object then data.concat() is this function, allowing "... String, string, char, byte, int, unsigned int, long, unsigned long, float, double..." as argument.
So, after the execution, data should contain:
temp1=10&hum1=24
and such content is exactly what is passed, via POST to the /add.php script.
Basically, you're passing two variables, called "temp1" and "hum1". Please keep note of those variable names!
Now let's switch the the PHP script, where you have:
[...]
$temp1=$_POST["data"];
$hum1=$_POST["serial_number"];
[...]

Above two statements, asks PHP to retrieve, via the $_POST function, the content of the two variables data and serial_number.
As such variables are undefined (the variables you passed were temp1 and hum1), PHP consider them like 0 and, as such, assign 0 to $temp1 and $hum1.
I bet that to solve your problem you only need to change above PHP with:
[...]
$temp1=$_POST["temp1"];
$hum1=$_POST["hum1"];
[...]

BTW: please note that what is inside the $_POST call is totally unrelated with the names of the variables you have on the left of the = sign: they are really different things!

Data = 10 is not the characters making 1 and 0 but an ascii character with value
10, your php script doesn't understand that.
Try using itoa function to make character array 1 and 0 for your php to understand.

You get a timestamp from running the php file. That doest mean that there is a number in $data or $serialnmber.
What happens if you fill in a value in your php file instead of the variables $data and serialnumber. If the dbase gets filled, you know that than your variables were empty. If they arent filled something is wrong in your php coding


text:
vrdude stk 500 not responding error inspeed control of dc motor using arduino uno board .how to solve this issue
vrdude stk 500 not responding error inspeed control of dc motor using arduino uno board  .how to solve this issue

...COM1...? Are you sure about that?

Yes i do only one usb port in the system

Have you tried turning it off and on again?


text:
Arduino sensors with various periods
Right now I have DHT11, PIR sensor, relay, and a photocell on the same board. I am planning to upload the data to a web server. But I want both DHT11 and photocell to be uploaded hourly; PIR and relay by every 3s. Is it possible for a single Arduino to perform such thing?

Yes. Perfectly possible.
How accurate do you need the "hourly"? If you want any form of accuracy at all you will really want to use an RTC module to provide the real time.
Otherwise that, and the higher speed 3s updates, can be timed using the millis() function.  The BlinkWithoutDelay example in the IDE shows you the basic idea of working with timestamps to examine elapsed time.
Also there are simple libraries that could help you, such as SimpleTimer.


text:
Changes to array not reflected
Here's a simple sketch. I have an array data and a variable idx.
I'm assigning a value to each of the array element, and then sending them to my serial monitor.
volatile uint16_t data[5];
volatile uint16_t idx = 5;

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

  while (!Serial) { }
  Serial.println("\nHello!");

  data[0] = 1010;
  data[1] = 1011;
  data[2] = 1012;
  data[3] = 1013;
  data[4] = 1014;

  for(int i = 0; i< idx; ++i)
  {
    Serial.print(data[idx]);
    Serial.write(",");
  }

  while(1){  }
}

void loop() {}

When I look into my serial monitor, I get this:
Hello!
0,0,0,0,0,

Why is this happening? Did I overlook something fundamental? I'd appreciate if you could offer your thoughts on this.
I'm testing this code on Arduino Mega2560.

You got confused here:
Serial.print(data[idx]);

You're printing array slice 5 (the sixth entry in a 5 entry array) 5 times.
You probably meant to write:
Serial.print(data[i]);

To improve clarity you may want to #define it instead:
#define DATA_SIZE 5
uint16_t data[DATA_SIZE];

...

for (int i = 0; i < DATA_SIZE; i++) {
    ....
}

Or you can do it the other way round (get the size from the array):
uint16_t data[5];
#define DATA_SIZE (sizeof(data) / sizeof(data[0]))

It's easy to go code-blind ;)

Terrible. Can't believe I missed such a simple thing. Perhaps I would've noticed if I labeled 'idx' as 'last_idx' or something clearer.

For those kind of constants it's better to use a #define and use all capitals.  I'll show you an example in my answer.

It's not a constant, but an incrementing index as I populate an array. ;-)

Ah, right. Well, don't forget that the array size itself is fixed (something many users here don't realise), so you need to allocate all the memory up front.


text:
avrdude: stk500_recv(): programmer is not responding
Arduino IDE is throwing this error when uploading sketches - avrdude: stk500_recv(): programmer is not responding
The problem arose just after I uploaded a blink sketch to my Arduino Mini, which worked absolutely fine. After the successful upload I tried to upload a different sketch and got the error.
I thought I had destroyed the boot loader somehow and was about to get out the Bus Pirate for ICSP but I decided to try another Arduino Mini I had lying around (albeit from another manufacturer) and got the same error.
So I'm convinced it's a driver issue as I successfully uploaded a sketch (it still runs as we speak!) then just magically without changing ANYTHING I can no longer upload.
In a futile attempt to get back to work I've done the following:
Switched the RX-TX lines (clearly not the issue as the first upload worked)
Used a different FTDI cable
used a  different programmer
(FTDI 5V/3.3V USB to TTL Basic FT232 FIO Programmer)
(USB to TTL Serial UART RS232 Adaptor (PL2303HX)
I'm fairly certain these use different drivers - FTDI and Prolific
Please help me I'm about to murder something :'(
Screencaps of error and device manager - Imgur

The error appears when you overwrite the bootloader. Only the bootloader makes the standard Upload button work.

i am having same problem in uno, I checked all of possible situation(board/COM), what to do? and aslo please tell me which programmer I need to choose?

Answer is below. You need to press the button on the arduino board as you are uploading the sketch.    https://www.arduino.cc/en/Guide/ArduinoMini

Did you check the pin alignment of your FTDI connector with the 6-pin connector on your Arduino board? Although the FTDI adapters look the same, the 6-pin connector may actually have been swapped. BTW, my FTDI adapter resolves the need to reset the Arduino before uploading by bringing out the DTR signal on pin 6. However, it was made backwards from other ones.

Please post this as "Comment" because it ISNT an answer!

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Is it this?
"To upload a new sketch to the Arduino Mini, you need to press the reset button >on the board immediately before pressing the upload button in the Arduino >environment."
https://www.arduino.cc/en/Guide/ArduinoMini

You sir, are a hero.
I don't even know how I accidentally did this sequence to upload the first sketch... Perhaps I plugged the USB to Serial UART in to the USB port and quickly pressed upload? Having got the first sketch on there really mixed me up :/
Solution:

Click upload sketch - It will show 'Compiling Sketch'
Immediately after clicking upload, hold the reset button down on the Arduino mini
Release the reset button when 'Compiling Sketch' turns in to 'Uploading'

Is it this?
"To upload a new sketch to the Arduino Mini, you need to press the reset button on the board immediately before pressing the upload button in the Arduino environment."
https://www.arduino.cc/en/Guide/ArduinoMini

avrdude: stk500_recv(): programmer is not responding
I have the same problem (Arduino uno)
I reset the Arduino several times, but finally i fixed the problem.
so you must change the pic of the arduino and make sure it was instilled correctly on the arduino board.
hope it work...


text:
How to modify an Arduino Due native USB port VID and PID?
I would like to know if it is possible to modify the VID and PID of the Native USB port of an Arduino Due.

in C:\Users\<user>\AppData\Local\Arduino15\packages\arduino\hardware\sam\<version>\boards.txt. but better create a custom definition this way

No wait, probably I did not write it correctly. I would like to set up the native USB to have a different VID or PID from the current one VID_03EB PID_6124.

the values from boards.txt are used in the USB handling part in the uploaded sketch


text:
MegaCore ATmega2560 PB7 activation randomly at boot
I uploaded in my custom board (ATmega2560 with an external oscillator 16MHz) the MegaCore bootloader using the AVR pinout. I found that when I switch on the board the pin PB7 is activated 2 short times. This happens even with a blank Arduino sketch.
I found out that the problem was the reset pin connection. When the reset pin (for uploading a new sketch) is connected to the board I got the previous behaviour.
How can the reset pin affect only the pin PB7?
PS I found this issue even in the Arduino Mega standard bootloader.

PB7 is pin 13. That's the traditional LED pin.
The bootloader blinks that LED to indicate it's active.
If you want other behaviour then you will have to compile your own version of the bootloader that doesn't blink the LED.

Many thanks, I thought it was that.


text:
WebClientRepeating not printing response to Serial
I'm following the tutorial in WebClientRepeating and it says that "The content of the page is viewable through your Arduino's serial window." However the output in my Serial window is just saying "Connecting..." repeatedly.

Here is my code:
    /*
  Repeating Web client

 This sketch connects to a a web server and makes a request
 using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
 the Adafruit Ethernet shield, either one will work, as long as it's got
 a Wiznet Ethernet module on board.

 This example uses DNS, by assigning the Ethernet client with a MAC address,
 IP address, and DNS address.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13

 created 19 Apr 2012
 by Tom Igoe
 modified 21 Jan 2014
 by Federico Vanzati

 http://www.arduino.cc/en/Tutorial/WebClientRepeating
 This code is in the public domain.

 */

#include <SPI.h>
#include <Ethernet.h>

// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
// fill in an available IP address on your network here,
// for manual configuration:
IPAddress ip(10, 1, 1, 4);

// fill in your Domain Name Server address here:
IPAddress myDns(10, 1, 1, 1);

// initialize the library instance:
EthernetClient client;

char server[] = "www.arduino.cc";
//IPAddress server(64,131,82,241);

unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
// the "L" is needed to use long type numbers

void setup() {
  // start serial port:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  // if ten seconds have passed since your last connection,
  // then connect again and send data:
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }

}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connecting...");
    // send the HTTP GET request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}

Here are my Mac's network settings.

It's my understanding that I can assign an IP address to my Ethernet shield by just changing the last number of my computers IP address. Hence I changed 10.1.1.5 to 10.1.1.4.
Can anyone see any obvious errors? This is not really my area of expertise :)

Might be another device on 10.1.1.4. Try another IP address such as 10.1.1.104.

Your computer's IP address has no relevance to the Ethernet Shields IP address other than they can't both be the same if connected to the same network. Is your ethernet shield connected to your network/router with a cat5 cable?

Thanks for your help. I am using a cat5 cable but the port it was plugged into seemed to be faulty. I tried another one and that seems to have fixed it.


text:
Push to 2D array (log) but last value pushed is everywhere
I have this simple that is supposed to keep a log for me with a fixed number of entries. When I add to the log the oldest replaced is by the second oldest etc and the new entry added. Except when I add another entry both that and the one before have the same value (My C isn't any good, I'm more a ruby and lua guy).
What am I doing wrong here?
void setup(void) {
  Serial.begin(9600);
}

#define log_size 5
#define line_height 12
char *log_lines[log_size] = {"Hello", "World"};

void addToLog(char *text) {
  for(int i = log_size - 1; i > 0; i--) {
    log_lines[i] = log_lines[i-1];
  }
  log_lines[0] = text;
}

void printLog() {
  for(int i = 0; i < log_size; i++) {
    Serial.print(i);
    Serial.print(" ");
    Serial.println(log_lines[i]);
  }
}

void loop(void)
{
  char msg[20];
  sprintf(msg, "%d", millis());
  addToLog(msg);
  printLog();
  delay(1000);
}

The output after the first addToLog is
0 1000
1 Hello
2 World

second addToLog is
0 2001
1 2001
2 Hello
3 World

It is easy - in your log you store POINTERS to strings.
And you then create variable on the stack (ouch) and put its address to the log.
Then you leave the function (loop) (so that variable is forgotten and can be overwritten by anything). I will not say it is luck, that nothing uses the stack enought to make a problem before the loop is called again, as it disguise the problem. The POINTER in log_lines[0] points to UNALLOCATED place (where the variable msg once was).
Then the loop allocates variable msg (at the same place, as its previous run by the chance) so the POINTER stored in log_lines[0] (still pointing to the same place) points to the variable msg (and its content). By pure (bad) luck.
Then you overwrite the variable msg with a new value, so the log_lines[0] point to that new value.
Then you move the content of log_lines up, so the log_lines[1] now points to the variable msg (and its NEW value) as well as log_lines[0].
Then you assign log_lines[0] with address of variable msg (which it accidetally already contains)
Then you wonder, why variable msg accesed via log_lines[1] is exactly same as the (same) variable msg accesed vial log_lines[0] and why it contains the last (NEW) value, which you assigned into it.

Some of possible solutions are:
1) allocate place on heap (memaloc it) in the addToLog function, copy the text into it and store pointer to THIS place (and do not forget deallocate   last log_lines before overwriting it - if it is not null (as untinitialized values are all 0)) which could lead to (relativelly) expensive heap manipulations and possible memory fragmentation.
2) allocate log_lines as array of char arrays of given len, copy the content of each line in another loop inside addToLog and then copy(and possibly truncate) the text to the log_line[0]
3) keep static index of last used log_line and in addToLog just increment it (wrapping around the len of the array), then overwrite the line pointed by index with (truncated) text and in printLog just start cycle on the index and climb (wrapping around len of the array) until you are again at index (which you would not print again and stop)

Thank you for pointing out those three solutions.
The first on, in loop() was char  *msg = (char *) malloc(20); and you're right, the memory did skyrocket without free(log_lines[log_size-1]); in the addToLog function. Thank you.

That is easy too - you created new variable each time you went to loop() (every second as the delay(1000) on the end), but did not free that memory on the end of loop().  This is why you should (in this variant) allocate memory in the addToLog, copy the text there and deallocate the last log_line there. Otherwise you are heading to problems if you call addToLog more times in the loop (double free ot he same variable, storing the same pointer multiple times and overwrite the logged messages) as well as if you are not calling it at all (not freeing memory at all,skyrocketing heap).

Usually you should deallocate at the same level you allocate and each allocate should be paired with deallocate. Actually having msg as normal variable in loop() is good approach, allocate copy in addToLog (cause there are you copying a text to your array) and deallocate there the array rows from previous calls, when rolled out. This way you can use the log as it is meant - to log some history of interesting points and show it on request.

Here is a solution which does not use dynamic allocation nor does it
copy any log message. It's essentially a zero-copy implementation of
gilhad's solution 3. The idea is: instead of having an addToLog()
function that takes an already prepared message (which it would need to
copy), you have a get_log_buffer() function that tells you where to
write the message in the first place. This way you can snprintf()
directly into the right place in memory.
const size_t LOG_SIZE = 5;
const size_t MSG_SIZE = 20;

char log_stack[LOG_SIZE][MSG_SIZE];  // circular log buffer
size_t log_index;  // next available slot in the circular buffer

// Return the address of the next available message slot.
char *get_log_buffer()
{
    char *buffer = log_stack[log_index];
    if (++log_index == LOG_SIZE) log_index = 0;  // increment index
    return buffer;
}

void print_log()
{
    Serial.println(F("--------"));
    for (size_t i = 0, j = log_index; i < LOG_SIZE; i++) {
        j = (j ? j : LOG_SIZE) - 1;  // decrement index
        if (log_stack[j][0]) {  // should be a non-empty message
            Serial.print(i);
            Serial.print(" ");
            Serial.println(log_stack[j]);
        }
    }
}

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

void loop()
{
    snprintf(get_log_buffer(), MSG_SIZE, "%lu", millis());
    print_log();
    delay(1000);
}

Note that log_stack and log_index are zero-initialized by the C
runtime. Note also the use of snprintf() instead of sprintf() in
order to avoid buffer overruns.

The problem is, that user MUST limit the lenght of the message to the right size everytime. Which is possible to do right in small script, but it will be pain to do right if the log is in its own library and may dynamically react to aviable size of memory. Basically it is better, when functions/objects are responsible for thier internal state, than to rely on correct user input. One mistake then can do a lot of sideeffect, like overwriting other logs, other variables, stack and such, which are really hard to trace. So while this approach works, I would not recomend it if there is other way.

@gilhad: It very much depends on the use case. Obviously, you won't use an arbitrary string limit in a general purpose library. But in a self-contained program, avoiding dynamic memory allocation can make a lot of sense.

Yes, but it is easier to check (and change) on the one place, where you store the message, than everywhere in the code, where you want to log something. So I do not forbid this approach, but I strongly suggest it, as is less error prone and commonly better practice for someone starting to write programs in C and have this kind of problems. And you can see, that 2 of 3 variants in my answer are based on static allocation. But the author have to know, if he needs variable size string, or if fixed leght works for him better. I just elaborate on what he (or you) provided.

I personally would allocate just array of chars , trim messages to its lenght and manage two pointers on where the log starts and where it ends, deleting necessary number of lines to accomodate new message. So buffer would be used to max and history len would depend on size of respective messages. (and I would empty the buffer after dumping it to not have duplicate entries in the log print. And probabely started any log with timestamp too. But it is way more complicated to implement for someone not used to pointers and C strings)


text:
Arduino digital pin reading string numbers
Using for example 433MHz RF Receiver modules, they are connected to a digital input pin with interrupt. Looking at the most basic meaning of digital readings (e.g. 1/0, on/off, HIGH/LOW), how does the Arduino convert the signal readings to a number/string?
From my limited understanding, I'm assuming it has something to do with the (external) libraries, or it might just be that my understanding about digital readings are too limited.

From the official Arduino site, See DigitalWrite :
If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW.
The exact definitions can be found here for reading a signal: Constants
When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.
HIGH
The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report HIGH if:
-a voltage greater than 3.0V is present at the pin (5V boards);
-a voltage greater than 2.0V is present at the pin (3.3V boards);
A pin may also be configured as an INPUT with pinMode(), and subsequently made HIGH with digitalWrite(). This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This is how INPUT_PULLUP works and is described below in more detail.
When a pin is configured to OUTPUT with pinMode(), and set to HIGH with digitalWrite(), the pin is at:
-5 volts (5V boards);
-3.3 volts (3.3V boards);
In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.
LOW
The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report LOW if:
-a voltage less than 1.5V is present at the pin (5V boards);
-a voltage less than 1.0V (Approx) is present at the pin (3.3V boards);
When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).
Probably, HIGH is 1, LOW is 0, and ON is 1, OFF is 0.
Than 1 is mapped to 5V or 3.3V depending on the Arduino and 0 is mapped to 0V.
These mappings and the definitions of HIGH/LOW/ON/OFF are in the Arduino libraries.

A digital pin can only tell you if a signal is HIGH or LOW at any instant in time. That itself isn't enough to transfer data (as in a stream of 1 and 0) since it's just the state at that moment.
To transfer data you need to introduce the extra parameter of time. That is, the amount of time a pin is HIGH or LOW and when exactly it changes.
UART data works this way. Both ends of the connection agree on a certain time for each "bit" of data (symbol) and read or set the pin at the agreed rate. That is the baud rate of the connection. Without that pre-arranged agreement on the time there is no way one end can know what the other is saying.
Other methods involve looking not at the current state of the pin but instead looking at how and when it changes from HIGH to LOW or LOW to HIGH. One example of this is Manchester Coding which encodes the different bits 0 and 1 as different sequences of transitions between HIGH and LOW or LOW and HIGH.
A third method, which is what SPI and I2C use, is to employ another pin to indicate to the receiver when it should look at the pin - this is sending the clock to the receiver.
Fourth, you get the way IR remote controls work. These use different length pulses of HIGH/LOW to indicate a 1 or a 0. A long HIGH and short LOW could be a 1, and a short HIGH and long LOW could be a 0.

In other words, the receiver sends the data in binary (1s and 0s) to the Arduino? (and the library converts it to string code)


text:
Which GSM-shield is most efficient for GPRS communication?
I tried Google, I tried a bunch of forums and I searched here. This question needs a final answer:
Which GSM-shield is most efficient for GPRS communication?
Since Arduino is the amateurs best friend for home automation and IoT, an "efficient" shield has a very low power consumption.
I am currently developing a system that collects some data from different sensors at a place far, far away, with limited access to power (e.g. it has a very small solar panel and a battery). It is also in pocket-size which makes a car battery a bad option.
Anyway, this specific device reads these sensors every 20 minutes, and if there's a deviation since the previous reading it starts the GSM module to send the new data to my API.
SMS and call features are of absolutely no interest at all.
Since these GSM-power-absorbing-current-eating-devils really like power I must think outside the box and compare different alternatives. So besides the primary question in this post, is there any way you can limit the power consumed, for example by limit the connection speed or anything like that? I'm using a M590 module at the moment, and that beast can eat around 2A if it's hungry.
Thanks in advance :)

Three main things come to mind here...
Overall hardware power consumption: if you can make the arduino sleep for those 19ish minutes and are willing to do some of the things below/linked. Adding a RTC module using the alarms to trigger a GPIO to wake the arduino might be something depending on your hardware options as well.
Software / clock speed / timing: having the perfect code will make all the difference here as well. if your test code takes say 30 seconds to wake up, read the sensors, arrange the data, wake up gprs and transmit then fall asleep again. that might be pretty good. But say for example FONA shields have a 7second wake up.. This time can be used to sample sensors and arrange the data. Then transmit straight away when it wakes up.. could save a few seconds. also switch it off asap before any other code n so on.
GPS/GPRS Reception: If you can establish a connection quickly, you will be able to put it all back to sleep quicker and draw less power. Also possibly pre-select your providers baud rate to stop it trying and waiting.
As for point 1 above,
If you are powering it via the DC jack, then it is simply using a regulator (at least on the arduino side) that is not efficient (7805)...
So one suggestion is to get a 5v switching power supply and power it via the header pins or cut/splice a usb cable. this could gain you about 20% give or take.
Finding power hacks and running mini arduino's and alternatives can get you down even lower on power consumption.
I'm not going to give references from these listings, there just a quick few results. but basically from memory and glance its a case of removing resistors/regulators/redirecting/modifying/all that stuff and then also some software hacks along with changing the clock rate as well.
https://playground.arduino.cc/Learning/ArduinoSleepCode
http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/
https://learn.sparkfun.com/tutorials/reducing-arduino-power-consumption
https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption
https://www.hackster.io/techduino/reducing-arduino-power-consumption-9bcaf1
Atmega328 with minimal circuit schematics

I didn't know this thread was still alive. This was a very good and
thorough answer. I actually made a lot of tweaks since I wrote it, and switching power supply is one of them. Thanks for a great answer, and I hope someone else will also find it useful. Cheers!

GSM, by its very nature, is power hungry.  Even the most "efficient" one will blow your power budget many times over.  Since everything on GSM goes down the same digital transmission channel there would be no real difference between one with call and SMS and one without. It's all just data at the end of the day.
That said, the most efficient GSM module is one that consumes absolutely now power. And that is, at least for most of the time, perfectly possible.  By making the Arduino control the power supply to the GSM modem it can be literally turned off until an update is needed to be sent. Worst case that is on for maybe a minute (give it time to register on the network and what have you) and then off for 19 minutes. That's only on for 5% of the time - less if there isn't a change since the last time, of course.

So with that information in mind, the shield of choice is nothing that actually needs deeper consideration? The key is therefore to shut it down when it's not in use - which I already do. I did have some hope that there's tweaks I just hadn't heard of yet :)


text:
No sketches will upload to Arduino Uno board; says "access denied"
I'm using an Arduino Uno board with an HP computer running Windows 10 and IDE version 1.6.8. Arduino was working fine for me until a few days ago, when (and I suspect this is the root of the problem) I accidentally tried to upload software with something connected to the RX and TX pins on the board. Now I continually get the error message below:

avrdude: ser_open(): can't open device "\.\COM2": Access is denied.

The only other thing that changed is I disconnected a bluetooth dongle (Kinivo BTD-400 Bluetooth 4.0 USB Adapter for Windows) without uninstalling any software, so I suspect that software may be searching for open COM ports and disrupting the Arduino upload.
I've tried everything I could find about troubleshooting online, including that "did I brick my arduino" post elsewhere on this forum, and nothing has worked or even changed the problem - please help! I believe I've narrowed down the problem to my computer scanning open COM ports, but I can't find any reliable way to make sure that doesn't happen.
Thanks

Have you tried powering down your PC and turning the power-plug in the socket the other way around? This often fixes this issue. (Given you're using AC power)

It sounds like Windows thinks that port is in use and isn't letting the ArduinoIDE access it. If it's the same port your dongle had been using, try plugging the dongle back in, then dismounting it before you remove it. Hopefully that will clear the port for other uses.