text:
How to use console.log message from nodejs server, to control led pin 13?
I want to use Arduino Yun as a client, that connects to my nodejs server, receives a message from nodejs and then change led pin 13 on/off according to the message send.
I have this example of a nodejs server:
  var express = require('express');
var http = require('http');
var url = require('url');

var app = express();

//app.set('port', 8080);

var server = http.createServer(function(request, response){
    console.log('Connection');                                                          var path = url.parse(request.url).pathname;

    switch(path){
        case'/':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Hello World');
            response.end();
            break;
        case '/arduino/digital/13/0':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Led 13 is off');
            console.log('Led 13 is off');
            response.end();
            break;
        case '/arduino/digital/13/1':
            response.writeHead(200, {'Content-Type': 'text/html'});
            response.write('Led 13 is on');
            console.log('Led 13 is on');
            response.end();
            break;
        default:
            response.writeHead(404);
            response.write("Oops, this doesn't exist - 404");
            response.end();
            break;
    }

});

//server.listen(8080);

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

server.listen(server_port, server_ip_address, function () {
  console.log( "Listening on " + server_ip_address + ", server_port " + server_port )
});

The server is running on an openshift nodejs server - It's not Localhost!
Here is the Arduino sketch I use:
/*
 Possible commands created in this shetch:
 * "http://yunobomber-cuebo.rhcloud.com"                         -> Serial Monitor "Hello World"
 * "http://yunobomber-cuebo.rhcloud.com/arduino/digital/13/1"    -> Serial Monitor "Led 13 is on"  &  digitalWrite(13, HIGH)
 * "http://yunobomber-cuebo.rhcloud.com//arduino/digital/13/0"   -> Serial Monitor "Led 13 is off" &  digitalWrite(13, LOW)
 */

#include <Bridge.h>
#include <HttpClient.h>

HttpClient client;

void setup() {
  Bridge.begin();                                                          // Bridge startup

  Serial.begin(9600);
  while (!Serial);                                                         // wait for a serial connection
}

void loop() {
  // Initialize the client library
  HttpClient client;

  // Make a HTTP request:
  client.get("http://yunobomber-cuebo.rhcloud.com");       // Insert alternative url for other commands - See explanation at top

  while (client.available()) {                             // Read message from server
    char c = client.read();
    Serial.print(c);
  }
  Serial.flush();
  delay(5000);
}

void process(HttpClient client) {
  String command = client.readStringUntil('/');

  if (command == "digital") {
    digitalCommand(client);
  }
}

void digitalCommand(HttpClient client) {
  int pin, value;

  // Read pin number
  pin = client.parseInt();

  // If the next character is a '/' it means we have an URL
  // with a value like: "/digital/13/1"
  if (client.read() == '/') {
    value = client.parseInt();
    digitalWrite(pin, value);
  }
  else {
    Serial.println('Error: Could not read url!');
  }
}

The serve works as it should, which can be seen here:
http://yunobomber-cuebo.rhcloud.com
I'm also get the message send from the server, when I read serial monitor, so the connection to the server from the Yun is also working. I can also console.log on the server side and see that a connection is established from the Yun.
The problem seems to be with the readStringUntil(); method, what I want to do is actually readStringAfter(arduino/), but such a method doesn't exist or at least I'm not sure how to make one?
Also I wonder if my approach is wrong, since I use REST calls to control the Yun, maybe I should solve it diffenrently, since I've already established a connection to and receiving input from the nodejs server?
Hope that someone can help my understand and solve this issue?


text:
How to discard same string received at Arduino
I don't want the same string to be printed again and again. I'm getting the data into an Excel sheet.
byte readValue1=0;
byte readValue2=0;
int add=0;
int row=0;
int Zigbee1=0,Zigbee2=0,Zigbee3=0;
void setup() {
    Serial.begin(9600);
        Serial.println("CLEARDATA");
        Serial.println("LABEL,Time,Zigbee,a1,a2,a3,a4,a5,a6,a7");
        row++;
}

void loop(){
  String a1,a2,a3;
  String c1,c2,c3;
  int b;

  if (Serial.available()>21){
        if(Serial.read() == 0x7E) {
            for(int i=0; i<10; i++){
                byte discard = Serial.read();
            }
                        add = Serial.read();
                       if(add == 33)
                        {
                        a1 = func1();
                        if(a1==c1){
                          b=0;
                        }
                        else
                        {
                          b = a1.length();
                        }
                        if(b != 0)
                       {
                        Zigbee=1;
                        Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                        Serial.print(","); Serial.println(a1);
                        row++;
                        }
                        }
                      else if(add == 48)
                        {
                        a2 = func1();
                        b = a2.length();
                        if(b != 0)
                      {
                        Zigbee=2;
                        if(a2!=c2){
                       Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                       Serial.print(","); Serial.println(a2);
                        }
                        c2=a2;
                       row++;
                        }
                        }

                       else if(add == 69)
                        {
                          a3 = func1();
                          b = a3.length();
                          if(b != 0)
                         {
                          Zigbee=3;
                          Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                          Serial.print(","); Serial.println(a3);
                          row++;
                    }
                        }
}
}
}

Can you give sample of the output you are getting and the output you want?

i solved it out by using comparing the received bits in that frame..
here is my code..
                   if(add == 33)
                    {
                    a1 = func1();
                    b = a1.length();
                    if(b != 0)
                   {
                    Zigbee=1;
                    if(a1!=c1)
                    {
                    Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                    Serial.print(","); Serial.println(a1);
                    }
                    c1=a1;
                    row++;
                    }
                    }
                  else if(add == 48)
                    {
                    a2 = func1();
                    b = a2.length();
                    if(b != 0)
                  {
                    Zigbee=2;
                    if(a2!=c2){
                   Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                   Serial.print(","); Serial.println(a2);
                    }
                    c2=a2;
                   row++;
                    }
                    }

                   else if(add == 69)
                    {
                      a3 = func1();
                      b = a3.length();
                      if(b != 0)
                     {
                      Zigbee=3;
                      if(a3!=c3)
                     {
                      Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                      Serial.print(","); Serial.println(a3);
                     }
                     c3=a3;
                     row++;
                }
                    }

Only print the string when he has changed?
String previousString = "";
String newString = "";

if(newString != previousString){
   println(newString);
   previousString = newString;
}

I'm not sure if it's applicable in your situation, just the first thing that came to my mind. You (kinda) should make a function of it, so that you don't have to copy/paste it all the time and it'll look way better.
EDIT:
A fuction could be made like so:
String previousString = ""; //Put this above your setup code (global variables)

void NoSpamString(String input){ //Put this block before the setup
   if(input != previousString){
      println(input);
      previousString = input;
   }
}

You can then use: NoSpamString("text"); to print a line withouth spamming it.

Thanx.. i figured it out..

but i cant make a function coz i need to check the address of every zigbee .. and im not getting how to make a function.. im a newbie..

How did you solve it then? If you believe this answer is the right solution you can use the  ✓ on the left side of the answer.

No, actually i got the solution later on my own:p

You could consider posting the solution you made, as an answer. So that other people who visit this question can use it for their project

source: Stack Exchange

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

sort: votes


text:
Arduino IDE doesn't find header file
I'm trying to start with the SainSmart 4x20 serial LCD, and copied the library to the Arduino library:

So LiquidCrystal_I2C.h is included. But when I try to compile an example sketch it says

Arduino: 1.7.0 (Windows 7), Board: "Arduino Uno"
HelloWorld_i2c.pde:2:31: fatal error: LiquidCrystal_I2C.h: No such file or directory
compilation terminated.
Error compiling.

Any ideas how to fix this?

There is no such thing as Arduino 1.7.0. At the time of writing, the latest Arduino IDE is 1.6.3 http://arduino.cc/en/Main/Software

It may be the 'Arduino.org' ripoff version. Test the same sketch in the Official Arduino IDE, the one linked by @FedericoFissore

Please, accept your owm answer to close this question.

I copied the SainSmart library to the IDE's library folder, not noticing that there was already a folder named "LiquidCrystal". Apparently the files added to the existing folder are being ignored.
Renaming the SainSmart library before adding it solves the problem.

There is not enough info to give a specific answer so I will give some troubleshooting tips:

First make sure at the top of your code you have: #include <LiquidCrystal_I2C.h> - with angle brackets
You may also need the Wire header file: #include <Wire.h>  - with angle brackets
Make sure you Include Serial
Make sure there are no extra folders in the library for example there should be a folder called liquidcrystal inside the liquidcrystal folder
If all fails copy the code from the header file make a new file in the IDE paste it in there and call it LiquidCrystal_I2C.h

Hope one of those solves your problem.

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


text:
Ken Sherriff Arduino Version Tv-Be-Gone
I am trying to make Ken Sherriff's version of the TV-Be-Gone with the Arduino using the updated v1.2 software.  He uses this setup:
His Setup

My Setup
I used the Arduino Nano with same MCU (Atmel ATmega328) as Uno but changed a few other things also. For power I supplied 9v to the vin pin but supplied the transistor with 5v from the 5v pin. I used this Instructable by the same person.  The only major change was I used a PN2222A transistor instead of 2N4401.

Problem
My problem is that even though when I push the button the infrared light blinks for a while sending the different codes my receiver won't pick it up. I checked my receiver with other remotes and it works and I tried at close and far range. My receiver just blinks if it senses any infrared command regardless of what type of remote but it doesn't work with my Arduino TV-Be-Gone. I haven't tried it with a real TV yet but would like for it to work before I try it on a real one.


text:
output of yun is not 3.3
After execute the program of below, the 13 pin output is 4.8v. Why it's not 3.3v?
void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(13, HIGH);
}

The Atheros chip on the Yún is run off 3.3V, but the AVR chip, which is what is connected to the external pins, runs off 5V. What you are seeing is normal (a bit low though, but within spec).

Nothing connected to pins... I just test it. Is it should be 5v? Is it normal that I get 4.8v when nothing connected?

It should be very close to the voltage of the 5V source, whether a regulator or the USB connection.

Thanks. I mean I don't think so 4.8v is very close to 5v. Hope it's fine when I play with it, hope components will work with it.

5% is a reasonable margin for digital supply voltages.

The Yun has no voltage regulator, so the 4.8V instead of 5V is due to the PC or USB plugpack used for power.

That's what I figured, but I should have checked the schematic to be certain.


text:
How do I update the serial monitor without printing a new line each time?
I'm testing out an accelerometer and I want to know if there's a way to make it so that the serial monitor will update the values without printing a new line. Ideally the serial monitor would say something like:
Accelerometer X: $xval
Accelerometer y: $yval

and then instead of printing two new lines each time, it just updates the values. Is there anyway to do that in Arduino? Thanks.

What happens if you make the serial monitor 20 lines long. And then print your 2 lines + 18 lines? I'm not sure, but it might fake a 'value update'

The ultra-basic "serial monitor" in the Arduino IDE cannot do what you want.
Instead you need to either write a special client program, or use a more standard serial terminal program, such as Tera Term (Windows), Minicom (Linux), etc.
These standard serial terminal programs use a special sequence of characters called ANSI escape codes which manipulate the display, doing such things as setting colours, moving the cursor around, etc.
More information on ANSI escape codes can be found here: http://en.wikipedia.org/wiki/ANSI_escape_code

No. The serial monitor does not support terminal handling. Either use a serial communications program that does and use those features, or write a custom client that will only update those values in its interface.

Okay, thanks. Is there any other client that's recommended?

Not really. Most serial programs, even Hyperterminal (or whatever Windows drags along these days) will do.

You might want to look into processing. You can use that to view the accelerometers position in 3d and see the values changing if that's what you want. The official Arduino site talks about it here.  Here is a great tutorial on it.

I would recommend this as a client option.

Probably would have been better as a comment on Ignacio
But yes processing is a good option IF you want to write code by yourself.


text:
yun manage bridge manually
in "Disabling the Bridge Script" of http://cylonjs.com/documentation/platforms/yun/
I did:

Edit the /etc/inittab file to comment out the ttyATH0 line (put a # before it)

::sysinit:/etc/init.d/rcS S boot
::shutdown:/etc/init.d/rcS K shutdown
#ttyATH0::askfirst:/bin/ash --login

But I want to turn it on or off manually. Then I can program through WiFi if I want.
How to do that?


text:
how to turn yun to ad hoc mode?
Can I turn Yun to ad hoc mode?
How to?

As the image above I can see the Ad-Hoc model in that drop down list. But only WEP for its security.


text:
Converting Arduino LCD Programs to Serial I2C LCD code
I just got a Serial LCD and wanted to test it out with a game. I found this site with game conversions and wanted to use this game.  However since my serial LCD use the LiquidCrystalic2 library the code in its current state won't work. Is there a simple method of converting or porting liquidcrystal to LiquidCrystalic2? Or if someone knows of a simple game in regards to hardware that uses a serial lcd and could direct me to a link that would be great.

i got my lcd working on I2C following the steps in this link http://forum.arduino.cc/index.php?topic=128635.0


text:
Serial structure data transfer between an Arduino and a Linux PC
I use the Arduino compatible chipKIT WF32 board. I want to transfer structure data between my board and a Linux PC. Can I do it like the following?
struct data d;
char *tx = (char*)d;
Serial.print(tx);

Even if the above code works, the data type size in Arduino and on Linux will vary. Is there a way to serialize the data, like Protocol Buffers on Arduino?

Casting to a char* will make Serial.print expect a null terminated string. So the amount of data transferred will depend on the next zero byte in memory(arbitrary).

The following solution isn't strictly portable, but it should work as long as both ends are little-endian (most platforms).
You can use the GCC attribute packed to tell the compiler not to pad the fields like this:
struct __attribute__ ((packed)) my_struct {
  char c;
  int32_t n;
};

Then you can send your struct like this:
Serial.write((uint8_t*) a_my_struct_ptr, sizeof(my_struct));

On the receiving end you just copy the received data to a similarly packed struct. If you would rather use Python over C/C++ you can use the struct module to unserialize the data.

I just googled your product and the MIPS processor is bi-endian, but I will assume that it is configured for little-endian by default. You can try and see if ints keep their value after transmit. Also remember to use explicit size types such as int16_t, uint64_t, etc.

This may get messy - is an int 32 bits on the chipkit reflecting its processor's actual word width, or is it 16 bits for compatibility with ATmega-insipired Arduinos?  It probably makes sense to use explicit width types on both ends.

Yes you are right I forgot to consider that, I've updated the answer to use fixed size types.

Is the sizeof struct really equal to the size of structure in memory? I think memory padding would pad empty bytes between variable. Correct me if I am wrong. Thanks.

@lionlai The __attribute__ ((packed)) makes sure no padding is applied. If padding was used, you would get into trouble trying to send data from eg. an 8 bit platform to a 32 bit one.
However, sizeof does represent the size of the structure in memory including padding. Try this on eg. x86 printf("%d\n", sizeof(struct {uint8_t a; uint32_t b;})); It should print 8 (remember to include stdint.h).

I usually send structures from arduino via serial port to PC and use the memcpy function to do it.
Let's say you have the struct data d (as pointed by the comments the memcpy as unnecessary. Use cast or union):
 struct data state;
 len = sizeof(state);
 Serial.write((uint8_t *)&state,len);

It is useful to create a starting and ending character to delimit your important data and make sure you receive all data and good information.
Let me give you one of my recent work example:
...

void send_state(){
 len = sizeof(state);
 Serial.write('S');
 Serial.write((uint8_t *)&state, len);
 Serial.write('E');
 return;
}
...

In this example the struct state is preceded with "S" (start) and succeeded with "E".
Then in python, for example, you can get the data using the unpack function. In my case:
...

# wait for data from arduino
myByte = port.read(1)
if myByte == 'S':
    data = port.read(39)
    myByte = port.read(1)
    if myByte == 'E':
        # is  a valid message struct
        new_values = unpack('<c6BH14B4f', data)

...

See if arduino sends data in little endian. The one I have used to send it.

What do you hope to achieve by re-buffering the data especially on the transmit side?  It is already in memory, so if you have a reason for making a copy of it, that should be stated.

Thanks for pointing out. Indeed it is not necessary (and even stupid). I do not really remember any particular reason for that, but looking at it after all this time, I would guess it was some newbie mistake due to compile error related to the Serial.write expecting uint8_t and I (stupidly) made that work around. The simple cast should be enough or more safely, as I've been learning here, using unions right?


text:
Connecting an AB phase encoder motor to arduino
i'm trying to understand how to connect this motor:
"Mitsumi 334P/R AB"
Link to the motor i bought

connections are:
GND - Obvious.
5v - Obvious.
rest of the connections are a bit confusing to me and i do not want to fry my arduino trying.

do i need a driver or this looks like a built in one?
do i need to add any electrical components like resistors and capacitors ect?

It's just a regular motor, with a (optical) rotary encoder inside. So the first two motor pins are to run the motor. So connect to VCC and GND, or GND and VCC, if you want to run it in reverse. (VCC doesn't have to be 5v; it can be 3v to 30v).
Connect A and B to a digital input pin. You can see what kind of signal you can expect in the screenshot of the oscilloscope, attached to the ebay-listing. So you can measure the speed, and relative position of the motor-shaft.

is there a way to decide (like stepper motor) to rotate 200 right/left? or this is a different kind that only measures speed and rotations?

You can turn on the motor, measure how many steps it's making, and turn off the motor when you reach 200 "steps". This is however grossly oversimplified, as in reality, due to inertia, you will probably overshoot these 200 steps. You probably need to slow down the motor (using PWM), when it's closing in on 200. Some kind of PID control.


text:
FTDI Cable to bypass USB for Arduino (Blend Micro) Programming
I bought a Blend Micro (an Arduino Micro with Bluetooth) a few months ago, and after my first experimentation with uploading the Blink sketch something went wrong with the USB connection--it would supply power, but no computer (Windows, OS X or Linux) would show it as a USB device, and Windows would complain that the device was somehow damaged. Anyway, when I plug the board in, it still boots up and runs "Blink" so I'd like to try to still use it.
I have a USB-to-FTDI cable, and it would seem fairly straight-forward to use that, but I'm a little uncertain to the appropriate wiring and whether I would need to tell the Arduino software somehow that I was using FTDI.
I can figure out these connections: (I think)

black to ground
red to 5V (VIN?)
orange to RX
yellow to TX

What about green and brown? Do one of those go to RST (Brown?) and MOSI (Green?)
I figured I would ask before accidentally burning something out.

A little more information as I've been Googling and reading. First of all, my FTDI cable is a Digi TTL-232R-3V3, so the wire colors are: black=GND, brown=CTS, red=VCC, orange=TX, yellow=RX, red=RTS. Looking at an Adafruit article I wonder if I'm out-of-luck in the Blend Micro being Leonardo-based and having USB managed inside the chip rather than using USB-to-serial on the board.

You could try re-flashing the bootloader using another arduino as ISP.

I'm afraid (a) that's a bit beyond by beginning experience, and (b) I think that would require on a Micro those six headers in the middle of the board, but those aren't exposed in the blend micro because the space is used by the Bluetooth chip. If booloader re-flashing can be done using the standard pinouts along the edges, can someone point me to a reference as a starting point?

You should be able to recover a Leonard-type board by putting it into DFU mode.

The six pin header is just for convenience. The same pins are also broken out on the side.


text:
How do I turn on or off an array of LEDs based on the value of a variable?
I've created a function whereby an int ('cleanCount') automatically goes up or down (0-1000) based on the situation. The value changes every few milliseconds.
Based on the value, I would like to turn on or off LEDs. Let's say for every increment of '100' another LED goes on. So if the value is 359 there are 3 leds on, if It would been 899 there would've been 8 LEDs on.
I could simply write
if (cleanCount <= 100) { // turn on NO LEDs
    digitalWrite(led1, LOW);
    digitalWrite(led2, LOW);
    ...
}

...

else if (cleanCount <= 500) { // turn on 4 LEDs
    ...
    digitalwrite(led3, HIGH);
    digitalwrite(led4, HIGH);
    digitalwrite(led5, LOW);
    digitalwrite(led6, LOW);
    ...
}

but that would be a big pile of code which could be way more efficient. Perhaps.. my code isn't even correct.
So how could this be more efficient or perhaps actually working?

The whole code, here below.
int cleanCount = 1000;
int softpotPin = A0; //analog pin 0

void setup () {
    Serial.begin(9600);
    digitalWrite(softpotPin, HIGH); //enable pullup resistor
}

void loop() {
    int softpotReading = analogRead(softpotPin);
    if (softpotReading < 980) { // IF AANGERAAKT
        digitalWrite(werktIeLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(16); // 5x zo snel als leeglopen
    }
    else if (softpotReading > 980) { // IF NIET AANGERAAKT
        digitalWrite(werktIeLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(64); // 1000 / 60 seconden
    }
    else {      // Als er een fout optreed..
        Serial.println("Fout!");
        digitalWrite(werktIeLED, HIGH);
        delay(250);
        digitalWrite(werktIeLED, LOW);
        delay(250);
    }

}

If you want the a bar graph effect, the arduino ide has a ino under examples>Display>barGraph maps analog values to ten LEDs

@RSM but how would I combine that example with my scope: 1 LED per 100 of my variable. That- and multiple LED's should be lid.

The code uses the map() function and will lite an LED per 100, it also keeps LEDs on below the current lit

Here is a suggestion with the led pins in an array that you loop over.
I suggest making the array global, so put it outside any functions (usually at the top):
byte led_pins[] = {pin1, pin2, pin3, pin4, pin5, pin6, pin7, pin8};

Then put this in your loop (assumes that you have a int called cleanCount that is in scope:
const int increment = 100;

for (int i = 0; i < sizeof(led_pins) / sizeof(led_pins[0]); i++) {
  boolean onOrOff = cleanCount > (i+1) * increment;
  digitalWrite(led_pins[i], onOrOff);
}

I'm pretty new to Arduino and coding for it. But uh, do I paste all of that in 'void loop' or a part above 'void setup' and a part in 'void loop' or..? Seems great and character-optimised formatted.

I updated the answer

cleanCount is stated at the top, above the setup, but has the value changing functionality in the loop. I'll post the whole code in a sec.

You can use the barGraph example from the Arduino code examples. This gives a bar-type graph and not point. I will give rough explination why it will work and the need not to re-invent the wheel.
    int sensorReading = analogRead(analogPin);
  // map the result to a range from 0 to the number of LEDs:
  int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);

  // loop over the LED array:
  for (int thisLed = 0; thisLed < ledCount; thisLed++) {
    // if the array element's index is less than ledLevel,
    // turn the pin for this element on:
    if (thisLed < ledLevel) {
      digitalWrite(ledPins[thisLed], HIGH);
    }
    // turn off all pins higher than the ledLevel:
    else {
      digitalWrite(ledPins[thisLed], LOW);
    }
  }

int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
This will give you the point in the array, 0-10, for 0-1000, if you replace 1023 with 1000
Simplified map() function:
int point = sensorReading*10/1000 this gives you a range of 0-10, the int keeps it from having decimal points.
As you can see from the for loop it turns on all the LEDs that are in the array to the end and then turns off those not needed.

Instead of repeating several calls to digitalwrite you should consider changing the pins directly as described here.
This now depends on which port your LEDs are connected to. Assuming port D you would use DDRD to define the pins as output (usually in setup()) and PORTD to set their values (in loop), e.g.
DDRD = B11111110; // define pins 1..7 as outputs, pin 0 as input

and
PORTD = B11110000; // switch on first 4 LEDs

Now all you need to do is to write a function to map your number range to suitable bit strings.
The function could look like this:
int convert(int n) {

  int res = 0;   // start with all pins off (zero)
  while (n > 100) {
    res <<= 1;   // shift pattern 1 bit (i.e. pin) to the left
    res |= 1;    // "switch on" lowest pin
    n -= 100;    // defines step size (1 LED for every  100)
  }
  return res;

}

It takes your value and returns an int that you can assign to the port. I.e. for 0..100 it returns 0, for 101..200 it returns 1, for 201..300 it returns 3 = B11, for 301..400 it returns 7 = B111 and so on. (Note that it does not do any sanity checks on the input / output but that's certainly easy for you to add if needed.)
(In response to comment: Note that the bit pattern I use as example for DDRD above is an example: It sets bit / pin 0 as input. If you use convert you would, of course, set the lowest bit of DDRD to 1 to make it an output.)

502 error on the link.. But I can use 'port manipulation arduino' as a search term. Looking at the information. Seems great!

Link works for me? I'll add a function also.

Yeah, the link is working now for me too. Although perhaps this -> http://tronixstuff.com/2011/10/22/tutorial-arduino-port-manipulation/ explains it better. Or atleast, more easy. Awaiting the function. Thanks!

I really have to read that 4 times thoroughly, as I'm a real beginner and I didn't understand it the first time, hehe. But thanks!

added some hopefully helpful comments...

Problem is that there is always one led lid, even in n<100. Secondly, the DDRD example, has pin D0 as an input, while convert will just write to bit 0. Thirdly, the PORTD example actually lights up the last four leds. Direct port manipulation is not very beginner friendly, and isn't really necessary, unless performance becomes an issue.

Firstly, I am not hired to write code to specs but trying to give hints on how to solve a problem. Adjusting the code so that it lights no led if n < 100 is something I think Sander is well capable of. Secondly, I chose this bit pattern for DDRD to make clear what it means if a bit is 0. But I will add a comment to make sure that this is not missed. Thirdly, that depends on how you define first and last, right?

@Gerben It is not a problem if the first LED is always lid. Actually, that's great because the first one is red, which suggests 'BAD'. No leds visualize less than a red lid one. Perhaps you can add that, Fuenfundachtzig.  Besides that; every suggestion is appreciated. Perhaps port manipulation is nog beginner friendly, perhaps. But I'm asking for efficient code, instead of writing every LED in an IF statement, which would be awefully bad. That might result in more mediate code, instead of beginner one. Still: Thanks!


text:
Why does the ADC overflow when using an external Aref?
I'm using an LM35 temperature sensor, and it outputs 190 mV (which agrees with 19°C). I'm using an external reference voltage which I measure as 417mV. (This is set by the pin "aRefCntrl"). So I should have a reading around 467, but I get 1023, i.e. the ADC overflows. When I use the internal 1.1V reference I get a correct reading. Any ideas?
This is my code (Arduino waits for a request from the PC to send the data):
#define lm35 A0
#define aRefCtrl 10

void setup() {
  pinMode(aRefCtrl, OUTPUT);
  digitalWrite(aRefCtrl, 0);
  analogReference(EXTERNAL);
  analogRead(lm35); // dummy read
  Serial.begin(9600);
}

void loop() {
  if ( Serial.available() ) {
    Serial.read(); // PC's request is a single byte
    int temperature = analogRead(lm35);
    Serial.println(temperature);
  }
}

follow-up on Ignacio's comment: would a decoupling capacitor do? (I can't test for the moment, I have to order some)

How much current is available from the reference?

@Ignacio: not much, the reference voltage comes from a 10k/1k divider on 5V. Isn't the voltage I measure at the aRef pin not the real reference voltage?

The minimum reference voltage is 1.0 V according to the atmega328 datasheet. See table 29-15. ADC Characteristics.

Thanks a lot! I was looking for that information in the datasheet, scanning it for all occurrences of "Aref", but it seems to appear as "Vref" :-). (Page 310, FTW.)

Hmm, Aref as in Analog Reference and Vref as in Voltage reference I think? But indeed 1.1V bandgap is a reliable (small voltage) source.


text:
Has anyone modified a 16x2 LCD shield to work with Arduino DUE?
Since the DUE works on 3.3 volts has anyone successfully modified a 5V 16x2 LCD shield to work with Arduino DUE?  I'm thinking 3.3V will be seen as a logic "1"
by the 5V LCD shield and there are no 5V outputs that feed back to the 3.3V due if the R/~W line on the LCD is simply grounded.
Would love to hear anyone's opinion on this.
Thanks,
Charlie

Is the R/W line broken out, or always connected to ground? During startup the pins are floating, which the lcd might interpret as a HIGH, outputting 5V to the data pins. You could add an external pull-down resistor to that pin, just to be safe. Other than that, you are totally correct. No problem.

I understand this is an 8yo thread, however my answer might still help someone.
I connected an unmodified no-brand LCD Shield to an Arduino DUE and it works perfectly - the only thing I had to change was the analog thresholds to identify the buttons. Just upload the sketch and read out the real values on the display then enter the averages between adjacent buttons in read_LCD_buttons function.
//Sample using LiquidCrystal library
#include <LiquidCrystal.h>

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

This program will test the LCD panel and the buttons
Mark Bramwell, July 2010

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

// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key = 0;
int adc_key_in = 0;
#define btnRIGHT 0
#define btnUP 1
#define btnDOWN 2
#define btnLEFT 3
#define btnSELECT 4
#define btnNONE 5

// read the buttons
int read_LCD_buttons()
{
adc_key_in = analogRead(0); // read the value from the sensor

if (adc_key_in < 90) return btnRIGHT;
if (adc_key_in < 297) return btnUP;
if (adc_key_in < 533) return btnDOWN;
if (adc_key_in < 814) return btnLEFT;
if (adc_key_in < 1000) return btnSELECT;

return btnNONE; // when all others fail, return this...
}

int button_count=1;

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

int i;

void setup()
{
lcd.begin(16, 2); // start the library
lcd.setCursor(0,0);
lcd.print("Push the buttons"); // print a simple message

// initialize the digital pin as an output.
pinMode(led, OUTPUT);

}

void loop()
{
  delay(100);
  lcd.setCursor(9,1); // move cursor to second line "1" and 9 spaces over
  lcd.print("        ");
  lcd.setCursor(9,1); // move cursor to second line "1" and 9 spaces over
  lcd.print(analogRead(0)); // display A0 analog input to calibrate values

  lcd.setCursor(0,1); // move to the begining of the second line
  lcd_key = read_LCD_buttons(); // read the buttons

  switch (lcd_key) // depending on which button was pushed, we perform an action
  {
    case btnRIGHT:
        lcd.print("RIGHT ");
        button_count = 2;
        break;

    case btnLEFT:
        lcd.print("LEFT ");
        button_count = 3;
        break;

    case btnUP:
        lcd.print("UP ");
        button_count = 4;
        break;

    case btnDOWN:
        lcd.print("DOWN ");
        button_count = 5;
        break;

    case btnSELECT:
        lcd.print("SELECT");
        button_count = 6;
        break;

    case btnNONE:
        lcd.print("NONE ");
        button_count = 1;
        break;
  }

}

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


text:
Arduino turns LEDs off when set 'high', opposite direction as coded
I've got a function that decreases over time (1000 / 60 seconds) and by touching a softPotentiometer you can increase that value. By every increment of 200 a LED is lid. So for 0-200, 1 LED; 201-400, 2 LEDs; etc. And since it decreases over time while doing nothing, if it drops below a certain value, a LED is shut off.
However, I've got a (amateur) coded set up, but somehow it lids the LEDs in the opposite direction. In a way that, I've coded it that if it's above 800, lid 5 LED's. However, it will only lid one LED when it's dropped below the 800, in the area of 601-800.
That's exactly the opposite of what I want. So what am I doing wrong here?

My code:
And with amateur, I mean that I didn't use arrays and therefor write everything multiple times..
int cleanCount = 1000;
int IsItWorkingLED = 13;
int softpotPin = A0; //analog pin 0
int LED1 = 1;
int LED2 = 2;
int LED3 = 4;
int LED4 = 5;
int LED5 = 7;

void setup () {
    Serial.begin(9600);
    digitalWrite(softpotPin, HIGH); //enable pullup resistor
        pinMode(1, OUTPUT);
        pinMode(2, OUTPUT);
        pinMode(4, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(7, OUTPUT);

           digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)

}

void loop() {
    int softpotReading = analogRead(softpotPin);
    if (softpotReading < 980) { // IF TOUCHED
        digitalWrite(IsItWorkingLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(16); // Drain 5 times as fast
    }
    else if (softpotReading > 980) { // IF NOT DTOUCHED
        digitalWrite(IsItWorkingLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(64); // 1000 / 60 seconds
    }
    else {      // Als er een fout optreed..
        Serial.println("Something wrong!");
        digitalWrite(IsItWorkingLED, HIGH);
        delay(250);
        digitalWrite(IsItWorkingLED, LOW);
        delay(250);
    }

        if (cleanCount >= 0 && cleanCount <= 200) {
           Serial.println("Knal 1 LED aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 201 && cleanCount <= 400) {
           Serial.println("Knal 2 LEDs aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 401 && cleanCount <= 600) {
           Serial.println("Knal 3 LEDs aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, LOW);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 601 && cleanCount <= 800) {
           Serial.println("Knal 4 LEDs aan");
           digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED4, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(LED5, LOW);   // turn the LED on (HIGH is the voltage level)
        }
        else if (cleanCount >= 801 && cleanCount <= 1000) {
           Serial.println("Knal 5 LEDs aan");
           digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
           digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
        }
        else {
          Serial.println("Just..do nothing");
        }

}

Ever thought of what would happen if the softpotReading is exactly 980?
But what if you switch ++cleanCount and --cleanCount. Not sure why you're using those, but switching them around might cause it to work like you expected? There would be a way more efficient way to map your potentiometer reading onto the leds. Don't have time to explain it at the moment. And I don't have an arduino at the moment...
Veel succes!

I've coded it that if it's above 800, lid 5 LED's. doesn't really map onto if (softpotReading < 980) { // IF TOUCHED

If your LEDs are connected anode to +5, cathode to i/o pin, they would behave this way. Cathode to ground, anode to i/o would behave as you expect.

@FuaZe His answer checks out to me, the LED is off when the IO pin matches the ground/power on the other side making the voltage diff 0, and on when the IO pin opposes the power connection making a voltage difference. Many LED's are wired so that they are lit when IO is LOW because of some electrical characteristics of the IO pins I couldn't fully explain.

Yeah, I didn't get it at first glance as I was sure something wasn't 100% in the code. But current will flow from the 5V to the arduino. And indeed putting negative to ground and positive (with current limiting resistor) to arduino will work.

Should I post a photo of my setup (wires and such?). Pretty sure it's correct. If there is software to create a schematic, tell me, else you've got to do it with a picture :)

Basically it comes down to this: if one side of the LED is attached to 5V instead of GND/0V then it will be 'inverted'

Try reversing the if statements.
You say:

I've coded it that if it's above 800, lid 5 LED's.

And your code is:
(softpotReading < 980) { // IF TOUCHED
The code describes: IF softpotReading IS SMALLER THAN 980, DO{ code.. }

In dutch (as OP is dutch, and to be honest his English somehow confuses me a bit, to be sure it's not the other way around also):
Ik denk dat je de IF statements verkeerd om hebt.
Je beschrijft dat bij een waarde hoger dan 800 de ledjes aan gaan...
Echter staat in je code (softpotReading < 980) { // IF TOUCHED
Wat dus zal betekenen dat de code wordt uitgevoerd als die < (kleiner dan) 980 is.

    if (softpotReading > 980) { // IF TOUCHED
    digitalWrite(IsItWorkingLED, HIGH);
    ++cleanCount;
    Serial.println(cleanCount);
    delay(16); // Drain 5 times as fast
}
else if (softpotReading <= 980) { // IF NOT DTOUCHED
    digitalWrite(IsItWorkingLED, LOW);
    --cleanCount;
    Serial.println(cleanCount);
    delay(64); // 1000 / 60 seconds
}

Yeah I'm Dutch ;) But I'll reply in English, for Site's sake. You really got to ignore the 'IF SoftpotReading < 980. Which is completely different. I've got a softPod module which reads out about 1000 if it's not touched. Once you touch it, it never goes above 980. You only have to look at the other statements. I could indeed reverse the IF statements. Thanks

Sander you could also try to do int softpotReading = 1024-analogRead(softpotPin); This way, your softpot wil give 0 for low to 1024 for high

Try to think of what your input is and what you want your output to be. Then you should use your code to bridge that gap.


text:
Use same ground with 2 wires?
So I have 3 ground pins, but I need 4 motors on my Arduino. Can I connect multiple motors to the same ground pin?

Arduino cannot power a motor directly

You can do it as long as the current isn't excessive. I don't think there are any specs available, but the connector and the width / thickness of the copper tracks on the PCB will be the limiting factor.

All ground is internal connected.
But anyway, you CANNOT use the Arduino's power to power a motor, you will need an external power source.And again, you will connect the external power source's ground to the Arduino's ground.

If you power a motor directly from an Arduino, the Arduino's microprocessor (e.g. AtMega328P) will get fried.

And while using the motors, make sure that  the motor does not touch the Arduino board

How do I control the motor then? I need to control the speed of the motor. How would I do this?

link for more info on how to do that.

If you are having problem in coding, comment here and I will give you some sample codes.

You can connect multiple components to a single ground pin.  IF you are using a breadboard, be sure to put the wire going to the go


text:
trying to delay between sequences
I am trying to build a set of four stars using an Arduino, potentiometer and a four channel relay to control how fast it speeds across the stars. My question is how can I delay the process, say for 20 or 30 seconds before it starts again?

Use Delay(  ).
Or this code
long previousMillis;

void setup(){
  previousMillis = millis();//in void setup
  bool lS=LOW;//in void setup
}

void loop(){
  long currentMillis= millis();//in void loop

  if(currentMillis-previousMillis>=20000){
     if (lS==LOW){
       digitalWrite(pinNo,HIGH);
       lS=HIGH;
     }
     else
     {
       digitalWrite(pinNo,LOW);
       lS=LOW;
     }
     previousMillis= millis();
  }
  delay(1);
}

While this does not serve your purpose, it shows you an how to switch on and off and LED after every 20 sec without keeping the Arduino idle for 20 sec.You could improve on it and make your own code.

Thanks FuaZe , for the edit.It looks a lot more easy to understand now , though the whole code is exactly the same to the Arduino.

If you want to just provide a delay use this function
delay(ms) -> where the argument is an integer value that represents the time in milliseconds.

For example, 1s = 1000ms
If you wanna stop everything and wait 1s, just use like that:
delay(1000);

Note that the atmega controller will stop everything it is doing and wait the amount of time. If you need to count or wait for something while other things are occurring, use timer interrupts. So the counting process is done in background and your main loop continues to do its jobs.

delay():
delay(20000); // wait for 20 seconds


text:
Serial Monitor breaks normal behaviour of Nano + NRF24l01

Couldn't find any other post that mentions Serial Monitor crippling the normal workflow of the NRF24l01, so here it goes.
I have two Arduino Nano, both with NRF24l01 attached, and an RF24 library working. Both NRF24l01 have 10uF caps soldered on them. One is only sending data, another is receiving only. Both of them flash LED on, successful transmission and successful receiving respectively.
When I run both devices, i see both LEDs flashing, so one succeeds in sending, and another one in receiving. But whenever I try to open Serial Monitor in my Arduino 1.6.1 software, the LEDs flash only every forth of fifth time of expected, and in my Serial Monitor I can see only 1 of 4 or 5 packets received (though received correctly).
Any ideas what I could have done wrong? Could Serial Monitor somehow interfere with Nano talking to NRF24l01?
The code follows, it's simple.
Sender
    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    // On Successfull Sending Blink PIN

    #define BLPIN 5

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipe = 0xF0F0F0F0E1LL;

    void setup(void)
    {
      pinMode(BLPIN, OUTPUT);

      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      radio.openWritingPipe(pipe);

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    // counter data to be sent
    unsigned long counter = 0;

    void loop(void)
    {

      // Increase the counter and send it
      counter++;
      printf("Sending counter = %lu...", counter);

      if (radio.write( &counter, sizeof(unsigned long) ))
      {
        printf("ok...\n\r");
        digitalWrite(BLPIN, HIGH);
        delay(10);
        digitalWrite(BLPIN, LOW);
      }
      else
        printf("failed.\n\r");

      // Try again 1s later
      delay(1000);
    }

Receiver
    /*
     Copyright (C) 2011 J. Coliz <maniacbug@ymail.com>

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License
     version 2 as published by the Free Software Foundation.
     */

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    // On Receiver Blink PIN

    #define BLPIN 5

    //
    // Hardware configuration
    //

    // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

    RF24 radio(9,10);

    //
    // Topology
    //

    // Radio pipe addresses for the 2 nodes to communicate.
    const uint64_t pipe = 0xF0F0F0F0E1LL;

    void setup(void)
    {
      pinMode(BLPIN, OUTPUT);

      //
      // Print preamble
      //

      Serial.begin(57600);
      printf_begin();
      printf("\n\rRF24/examples/GettingStarted/\n\r");

      //
      // Setup and configure rf radio
      //

      radio.begin();

      // optionally, increase the delay between retries & # of retries
      radio.setRetries(15,15);

      // optionally, reduce the payload size.  seems to
      // improve reliability
      radio.setPayloadSize(8);

      //
      // Open pipes to other nodes for communication
      //

      radio.openReadingPipe(1,pipe);

      //
      // Start listening
      //

      radio.startListening();

      //
      // Dump the configuration of the rf unit for debugging
      //

      radio.printDetails();
    }

    unsigned long counter;

    void loop(void)
    {
      // if there is data ready
      if (radio.available())
      {
        while( radio.available() ) {
          radio.read( &counter, sizeof(unsigned long) );
          // Dump the payloads until we've gotten everything
          printf("Got payload %lu...\n\r", counter);
        }
        digitalWrite(BLPIN, HIGH);
        delay(10);
        digitalWrite(BLPIN, LOW);
      }
    }

I had a Leonardo sending data to a FTDI-breakout-driven 3.3V Pro Mini and to a Mega2560. Both the Mini and Mega had idenctial code, except for the pipe addresses. The Mega was able to pick up every transmission (perhaps six losses out of 10,000 attempts) but the Mini was missing at least half of the packets. I changed the datarate to 2MBps (call radio.setDataRate(RF24_2MBPS) in setup() for each device) and the Mini's success rate jumped from under 50% to over 90%. It might be a bodge - the transmission has finished before the voltage has a chance to drop low enough - but it worked.

The reason for the Monitor being unable to work properly seems to be the length of the usb cable or a faulty usb port on my computer. I had a usb-cable extender, to which another (this time short) usb cable of my Arduino Nano was attached. It seemed to work fine while I was uploading things to Nano, but a quick serial exchange was, perhaps, not possible.Another usb port, or bypassing the usb cable extender brings everything back to normal.
This is a solution, while I still had no reason, how debugging through serial could influence that much on the chip behaviour itself, until now. I just thought it may well be the same power problem, as FTDI chip both powers the radio (even with the capacitor I installed!) and talks to computer through my long usb cable. If it starts talking, there could be no power for RF24 for a longer period than could be saved by my capacitor.

Are you using the FTDI chip's low-current 3.3v regulator to power your NRF24L01?  That might not be a good idea.

Try a lower baudrate than 57600.

I thought large enough cap (100uF) soldered on NRF24L01 would be enough. Am I mistaken?

When you use a very long cable you are limiting the total flow of current available to your arduino. The radio takes a lot of current. The cap only stores energy during the time you are not tx and then dumps it when you are.  If you tx less often you will have more time to recharge Inbetween dumps. It's possible you were right on the edge of your budget and that the extra cable length made it so that you were running out of juice.

The radio takes 14mA at maximum, usually a few nanoamps. It could be the capacitator from the power pins that's weak. The regulator ain't great.


text:
A LED should be lit when 'high'. Why does mine only burn with 'low'?
This is my followup question based on a serie of one project. Go my to profile to read 'm all.
So I'm building something which includes a function that has a count (1000) that decreases over time, but by pressing a soft pot meter the count increases. By every increment of 200 one LED is lit. So if the count is 837 4 LEDs are burning.
In my previous question I had issues lighting the LEDs, because they didn't burn even when the code was, as far as I could see correct. Instead it did the opposite of what I coded. Now I changed my code the opposite direction,
writing:

digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)

Which actually set the LED to bright. While is I'd write it 'HIGH' it would dim.
So my actual question is: How could my LED be lit if it's set to 'low', while you have to set it to 'high' to be actually popping off light?

My complete code:
int cleanCount = 1000;
int IsItWorkingLED = 13;
int softpotPin = A0; //analog pin 0
int LED1 = 1;
int LED2 = 2;
int LED3 = 4;
int LED4 = 5;
int LED5 = 7;

void setup () {
    Serial.begin(9600);
    digitalWrite(softpotPin, HIGH); //enable pullup resistor
    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    pinMode(LED5, OUTPUT);

    digitalWrite(LED1, HIGH);   // turn the LED on (HIGH is the voltage level)
    digitalWrite(LED2, HIGH);   // turn the LED on (HIGH is the voltage level)
    digitalWrite(LED3, HIGH);   // turn the LED on (HIGH is the voltage level)
    digitalWrite(LED4, HIGH);   // turn the LED on (HIGH is the voltage level)
    digitalWrite(LED5, HIGH);   // turn the LED on (HIGH is the voltage level)
}

void loop() {
    int softpotReading = analogRead(softpotPin);
    if (softpotReading < 980) { // IF TOUCHED
        digitalWrite(IsItWorkingLED, HIGH);
        ++cleanCount;
        Serial.println(cleanCount);
        delay(8); // Increase 5 times as fast
    }
    else if (softpotReading > 980) { // IF NOT TOUCHED
        digitalWrite(IsItWorkingLED, LOW);
        --cleanCount;
        Serial.println(cleanCount);
        delay(32); // Decrease slowly
    }
    else {      // If there is something wrong..
        Serial.println("Something wrong!");
        digitalWrite(IsItWorkingLED, HIGH);
        delay(250);
        digitalWrite(IsItWorkingLED, LOW);
        delay(250);
    }

        if (cleanCount <= 200) {
            Serial.println("Knal 1 LED aan");
            digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED2, HIGH);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED3, HIGH);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED4, HIGH);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
        }
        else if (cleanCount >= 201 && cleanCount <= 400) {
            Serial.println("Knal 2 LEDs aan");
            digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED2, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED3, HIGH);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED4, HIGH);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
        }
        else if (cleanCount >= 401 && cleanCount <= 600) {
            Serial.println("Knal 3 LEDs aan");
            digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED2, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED3, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED4, HIGH);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
        }
        else if (cleanCount >= 601 && cleanCount <= 800) {
            Serial.println("Knal 4 LEDs aan");
            digitalWrite(LED1, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED2, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED3, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED4, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(LED5, HIGH);   // turn the LED on (LOW is the voltage level)
        }
        else if (cleanCount >= 801 && cleanCount <= 1000) {
            Serial.println("Knal 5 LEDs aan");
            digitalWrite(1, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(2, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(4, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(5, LOW);   // turn the LED on (LOW is the voltage level)
            digitalWrite(7, LOW);   // turn the LED on (LOW is the voltage level)
        }
        else {
            Serial.println("Just..do nothing");
        }

}

Your assumption that a high is required to light a LED is false. All you need is to meet certain minimum voltage and current thresholds. Since the anode of the LED is tied high, the way to meet these is to bring the cathode low.

I don't got a clue what you actually mean with 'anode' and 'cathode' (beginner, as you might have guessed), but thus by setting it to 'low' it does shine. Ah okay. Thanks!

@SanderSchaeffer: Added a link and annotated symbol to hopefully make it a bit clearer.

When you command digitalWrite LOW you are basically connecting that pin to GND.  If you command digitalWrite HIGH then you are connecting that pin to +5v.  So depending on how you have the LED wired up you can use either to turn on the LED.  Since LOW turns your LED on then you must have the long lead of the LED attached to +5v supply and the short lead to the pin on the arduino.  I don't know why the LED doesn't turn all the way off when you command digitalWrite HIGH, but it should.
If you wanted to dim the leds then you should try using the analogWrite command which will send a PWM signal and will allow you to make the LEDs any intensity you want to.

An LED wants positive voltage to flow from the anode to the cathode (the + terminal to the - terminal)
You can wire it to a digital pin 2 different ways. (In both cases you'll also need a current limiting resistor to avoid burning out your LED and/or your digital pin, but ignore that for this discussion.)
You can wire the positive terminal of the LED to +5V, and the negative terminal to a digital pin. It sounds like this is what you've done. When you do that, if you set the digital output to HIGH, then both terminals of the LED are connected to +5V, so the LED will be off. Set the output to LOW, and it gets connected to ground. Now current flows out of the +5V rail, through the LED, into the grounded digital pin, and the LED lights up.
You can reverse that wiring instead. Connect the positive terminal of the LED to a digital pin and the negative side to ground. Now, when you set the pin to HIGH, +5V flows out of the pin, through the LED, and into the ground connection, so the LED lights. Set the pin to LOW and both sides of the LED are connected to ground, so it turns off.
Edit:
Note that you talk about voltage levels and dimming LEDs. If you're using digital outputs and HIGH or LOW, you can only turn the LED on or off. There's no way to vary its brightness.
You can, however, hook an LED to a PWM (Pulse Width Modulation) pin and set up that pin for analog output. In PWM, the Arduino switches the LED on and off rapidly. Set it to the highest output value, 255, and the LED stops flashing and is on 100% o the time. Set the output to 128, and the LED is on half the time and off half the time. Set the output to 64, and the LED is on 1/4 of the time and off 3/4 of the time, and so on.
When you flash a light fast enough, our eyes average out the brightness, and a light that's on 1/4 of the time looks 1/4 as bright as a light that's on 100% of the time.
Most Arduinos have a limited number of analog outputs. The Arduino model you're using might not have 7 analog outputs.

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


text:
Uploading over Bluetooth Low Energy - bootloader not responding
I'm working on sketches uploading over BLE. I had to write my own uploader (looking at avrdude sources with one eye) so i can change uploading behaviour as needed and it's working over USB just perfect but it does not get response from bootloader if trying over Bluetooth LE.
My hardware:

Arduino Uno (and i'm having Arduino Mega2560)
HM-10 BLE module

As HM-10 does not support DTR/RTS i had to add my own software reboot:
In brief: it reads incoming bytes on interrupt event and compares to reset command passed in ble_setup. If it's equal then it uses watchdog timer to reboot the board. If it's not equal it stores byte in byffer, then sketch loop() just returns incoming byes back ("echo").
#include <avr/wdt.h>

const char *ble_reset_cmd;
int ble_reset_index = 0;
int ble_available = 0;       // chars available
int ble_byte;                // income buffer as 1 char
int *ble_bytes = &ble_byte;  // income buffer
boolean delete_ble_bytes = false;

//#define BLE_DEBUG

// reboot Arduino board using Watchdog timer
void reboot() {
//    #ifdef BLE_DEBUG
    Serial.println("rebooting ...");
//    #endif

//    digitalWrite(13, HIGH);
//    delay(2000);

    wdt_enable(WDTO_15MS);
    while(1) { };
}

void ble_setup(int baud, const char *reset_cmd) {
    Serial.begin(baud);
    ble_reset_cmd = reset_cmd;
}

int Serial_available() {
    return ble_available;
}

int Serial_read() {
    if (ble_available < 0)
        return -1;

    int inByte = ble_bytes[--ble_available];
    if (ble_available == 0 && delete_ble_bytes) {
        // restore buffer as 1 char buffer
        delete[] ble_bytes;
        ble_bytes = &ble_byte;
        delete_ble_bytes = false;
    }
    return inByte;
}

void serialEvent() {
    if (Serial.available() <= 0)
        return;

    int inByte = Serial.read();
    if (inByte == ble_reset_cmd[ble_reset_index]) {
        // entered char is cmd character

        if (ble_reset_cmd[++ble_reset_index] == 0)
            reboot();

        #ifdef BLE_DEBUG
        Serial.write("ble_index = ");
        Serial.print((byte)ble_reset_index);
        Serial.write('\n');
        #endif

    } else {
        // entered char is NOT cmd character

        if (ble_reset_index > 0) {
            // got character not from cmd, so we should to return characters
            // starting ble_reset_cmd until current index and then this character

            ble_available = ble_reset_index + 1;
            ble_reset_index = 0;

            #ifdef BLE_DEBUG
            Serial.print("Copy ");
            Serial.print((byte)(ble_available - 1));
            Serial.println(" bytes");
            #endif

            // recreate input buffer using cmd characters
            ble_bytes = new int[ble_available + 1];
            delete_ble_bytes = true;
            ble_bytes[0] = inByte;
            for (int i=0; i<(ble_available-1); i++) {
              ble_bytes[i + 1] = ble_reset_cmd[ble_available - i - 2];
            }
            ble_bytes[ble_available] = 0; // null-terminated array

            #ifdef BLE_DEBUG
            Serial.print("input buffer now contains ");
            Serial.print(ble_available);
            Serial.println(" bytes");
            #endif

        } else {

            #ifdef BLE_DEBUG
            Serial.println("ble_index = 0");
            #endif

            // pass inByte next ...
            ble_available++;
            ble_byte = inByte;
        }

    }
}

// -----------------------------------

int led = 13;
int ledHIGH = 0;

void setup() {
  ble_setup(9600, "AT+RESET");
  Serial.print("ready\n");
  pinMode(led, OUTPUT);
}

void loop() {
  while (Serial_available() > 0) {
    int inByte = Serial_read();

//    Serial.write('>');
//    Serial.write(inByte);
//    Serial.write('\n');
    ledHIGH = 1- ledHIGH;
    digitalWrite(led, ledHIGH);
    Serial.write(inByte); // echo
  }
}

As i said it's working good for USB uploading:
right after rebooting bootloader waits for upload commands and start to reply:
015-04-07 21:22:10.860 Apploader[11226:303] Apploader v0.1
2015-04-07 21:22:12.772 Apploader[11226:303] DTR/RTS supported by Serial, resetting
2015-04-07 21:22:13.075 Apploader[11226:303] draining ...
2015-04-07 21:22:13.327 Apploader[11226:303] drain done
2015-04-07 21:22:13.328 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.328 Apploader[11226:303] draining ...
2015-04-07 21:22:13.723 Apploader[11226:303] drain done
2015-04-07 21:22:13.724 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.724 Apploader[11226:303] draining ...
2015-04-07 21:22:13.977 Apploader[11226:303] drain done
2015-04-07 21:22:13.978 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.979 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.980 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.980 Apploader[11226:303] Send: A [0x41]  . [0x81]   [0x20]
2015-04-07 21:22:13.984 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.984 Apploader[11226:303] Recv: . [0x04]
2015-04-07 21:22:13.985 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.985 Apploader[11226:303] Send: A [0x41]  . [0x82]   [0x20]
2015-04-07 21:22:13.988 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.988 Apploader[11226:303] Recv: . [0x04]
2015-04-07 21:22:13.989 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.989 Apploader[11226:303] Send: B [0x42]  . [0x86]  . [0x00]  . [0x01]  . [0x00]  . [0x01]  . [0x01]  . [0x01]  . [0x03]  . [0xff]  . [0xff]  . [0xff]  . [0xff]  . [0x00]  . [0x80]  . [0x04]  . [0x00]  . [0x00]  . [0x00]  . [0x80]  . [0x00]   [0x20]
2015-04-07 21:22:13.996 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.997 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:13.997 Apploader[11226:303] Send: E [0x45]  . [0x05]  . [0x04]  . [0xd7]  . [0xc2]  . [0x00]   [0x20]
2015-04-07 21:22:14.000 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:14.001 Apploader[11226:303] Recv: . [0x10]
2015-04-07 21:22:14.003 Apploader[11226:303] Send: P [0x50]   [0x20]
2015-04-07 21:22:14.004 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:14.008 Apploader[11226:303] Recv: . [0x10]

But when trying over BLE bootloader stops listening in 200ms and then launches sketch, i can see sketch setup() started as it prints "ready". Also i can see it actually reboots the board as it sends "rebooting".
015-04-07 21:23:30.287 Apploader[11253:303] Apploader v0.1
2015-04-07 21:23:30.296 Apploader[11253:1503] CBCentralManager state is 5
2015-04-07 21:23:31.297 Apploader[11253:303] BleSerialDevice: open()
2015-04-07 21:23:31.298 Apploader[11253:303] Waiting for peripheral to be discovered ...
2015-04-07 21:23:31.591 Apploader[11253:1503] Found peripheral: <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = disconnected>
2015-04-07 21:23:31.593 Apploader[11253:1503] Stop scanning
2015-04-07 21:23:31.595 Apploader[11253:1503] Connecting to <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = disconnected>
2015-04-07 21:23:32.025 Apploader[11253:1503] Connected to peripheral <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = connected>
2015-04-07 21:23:32.041 Apploader[11253:1503] Discovered services for peripheral <CBPeripheral: 0x100401940 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "Ardu", state = connected>
2015-04-07 21:23:32.042 Apploader[11253:1503] Discovered service <CBService: 0x103701450>
2015-04-07 21:23:32.043 Apploader[11253:1503] Discovered service <CBService: 0x1037015f0>
2015-04-07 21:23:32.043 Apploader[11253:1503] Discovered service <CBService: 0x103701630>
2015-04-07 21:23:32.044 Apploader[11253:1503] Discovered characteristics for service <CBService: 0x103701630>
2015-04-07 21:23:32.044 Apploader[11253:1503] Discovered characteristic <CBCharacteristic: 0x1037005c0>
2015-04-07 21:23:32.045 Apploader[11253:1503] Subscribed to Rx value
2015-04-07 21:23:32.046 Apploader[11253:303] Connected successfully
2015-04-07 21:23:33.342 Apploader[11253:303] BleSerialDevice: open()
2015-04-07 21:23:33.343 Apploader[11253:303] already connected, exiting
2015-04-07 21:23:33.343 Apploader[11253:303] DTR/RTS supported by Serial, resetting
2015-04-07 21:23:33.594 Apploader[11253:303] Within interval
2015-04-07 21:23:33.595 Apploader[11253:303] Perform reset
2015-04-07 21:23:33.596 Apploader[11253:303] Send: A [0x41] T [0x54] + [0x2b] R [0x52] E [0x45] S [0x53] E [0x45] T [0x54]
2015-04-07 21:23:33.647 Apploader[11253:303] Skip draining after reset
2015-04-07 21:23:33.648 Apploader[11253:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:23:33.648 Apploader[11253:303] Draining for 200 ms ...
2015-04-07 21:23:33.649 Apploader[11253:303] Start reading
2015-04-07 21:23:33.712 Apploader[11253:1503] Rx value received 15 bytes: r [0x72] e [0x65] b [0x62] o [0x6f] o [0x6f] t [0x74] i [0x69] n [0x6e] g [0x67]   [0x20] . [0x2e] . [0x2e] . [0x2e] . [0x0d] . [0x0a]
2015-04-07 21:23:33.713 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:33.780 Apploader[11253:1503] Rx value received 6 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79] . [0x0a]
2015-04-07 21:23:33.780 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:33.850 Apploader[11253:303] Finish reading
2015-04-07 21:23:33.851 Apploader[11253:303] Drained 21 bytes
2015-04-07 21:23:33.852 Apploader[11253:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:23:33.853 Apploader[11253:303] Draining for 200 ms ...
2015-04-07 21:23:33.853 Apploader[11253:303] Start reading
2015-04-07 21:23:33.982 Apploader[11253:1503] Rx value received 2 bytes: 0 [0x30]   [0x20]
2015-04-07 21:23:33.983 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:34.054 Apploader[11253:303] Finish reading
2015-04-07 21:23:34.055 Apploader[11253:303] Drained 2 bytes
2015-04-07 21:23:34.056 Apploader[11253:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:23:34.056 Apploader[11253:303] Reading 1 bytes ...
2015-04-07 21:23:34.057 Apploader[11253:303] Start reading
2015-04-07 21:23:34.057 Apploader[11253:303] _characterRead = false
2015-04-07 21:23:34.184 Apploader[11253:1503] Rx value received 1 bytes: . [0x00]
2015-04-07 21:23:34.185 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:34.186 Apploader[11253:303] Finish reading
2015-04-07 21:23:34.186 Apploader[11253:1503] Rx value received 2 bytes: 0 [0x30]   [0x20]
2015-04-07 21:23:34.186 Apploader[11253:1503] _characterRead = true
2015-04-07 21:23:34.186 Apploader[11253:303] Recv: . [0x00]
2015-04-07 21:23:34.187 Apploader[11253:303] stk500_getsync() attempt 1 of 5: not in sync: resp=0x00

Once again - bootloader stops listening in 200 ms instead of 1-1.5 secons as over USB:
2015-04-07 21:23:33.596 Apploader[11253:303] Send: A [0x41] T [0x54] + [0x2b] R [0x52] E [0x45] S [0x53] E [0x45] T [0x54]
...
2015-04-07 21:23:33.780 Apploader[11253:1503] Rx value received 6 bytes: r [0x72] e [0x65] a [0x61] d [0x64] y [0x79] . [0x0a]

I expect bootloader to reply with 0x14 0x10 as over USB:
2015-04-07 21:22:13.978 Apploader[11226:303] Send: 0 [0x30]   [0x20]
2015-04-07 21:22:13.979 Apploader[11226:303] Recv: . [0x14]
2015-04-07 21:22:13.980 Apploader[11226:303] Recv: . [0x10]

As you can see later communication over Bluetooth is working good, as i receive exactly what was sent (0x30 0x20)
So when sketch is launched it's ok.
My ideas what's wrong:

baud rate

Since serial.begin(N) is invoked after bootloader stops and launch sketch bootloader by default uses another baud rate? Is it correct? HM-10 default daud rate is 9600 and in sketch i also use 9600.

wrong wire connection?

Bluetooth-arduino:
rx -> tx
tx -> rx
Since its working for sketch i believe it's ok. Do i need any capacitors or resistors?
Any thoughts are highly appreciated!
UPDATE:
It seems i've found Uno bootloader source code and bootloader baud rate is 19200 by default
/* set the UART baud rate */
/* 20060803: hacked by DojoCorp */
//#define BAUD_RATE   115200
#ifndef BAUD_RATE
#define BAUD_RATE   19200
#endif

UPDATE2:
I'm in stuck as in this tutorial 115200 is used:
http://makezine.com/projects/diy-arduino-bluetooth-programming-shield/
in step 8. "build the programmer circuit" R1 2.2K is set on arduino rx pin. Why? Another thing i can't understand is that SoftwareSerial baud rate is set to 38400 but BT module baud rate is set 115200 using "AT" command. why?

It seems that's the reason why bootloader does not wait:
// Check if the WDT was used to reset, in which case we dont bootload and skip straight to the code. woot.
    if (! (ch &  _BV(EXTRF))) // if its a not an external reset...
        app_start();  // skip bootloader

Now i have another question ;) How to reboot arduino board from the sketch to jump into bootloader waiting for upload command?

The bootloader used on the Uno is optiboot. But it contains the same "feature" of skipping straight to the application program if the reset source wasn't external.
You could remove this feature and reprogram the bootloader to the chip (using an external programmer).
Alternatively you can use a dirty trick, and jump into the bootloader right after this check of the reset source happens. It happens to be right in the beginning, so not much has happened. The problem is that optiboot makes the assumption that the system is in a freshly reset state. So either you can write a flag to EEPROM to indicate that you just made an intentional WDT reset, or you can jump and hope for the best(not really recomendable).
You could also write a routine to reset the system to the same state as after a reset. But it might not be trivial since there are a lot of reserved memory addresses that Atmel (the manufacturer of AVR's the microcontroller used on the uno, mega, and others) recommends you never write to. So basically you would have to more or less manually set a lot of registers to their reset default (usually zero), in the right order (eg. first tri-state / set pins to input).
You can jump to the bootloader using this inline assembler code:
asm volatile ("jmp 0x7e00");

Optiboot fits in 512 bytes = 256 AVR words. The bootloader address can be found in the datasheet Table 27-13. Boot Size Configuration, ATmega328/328P. It is printed in the datasheet as the word address, but the avr-as assembler takes the byte address. Word address 0x3f00 * 2 = 0x7e00 byte address.
You can also see the address in optiboot_atmega328.lst where code starts at byte address 0x7e00.
In order to jump past the boot source check we find the first address in optiboot_atmega328.lst that comes after the check. It is 0x7e0a. We then modify our bootloader jump:
asm volatile ("jmp 0x7e0a");

You will want to make this jump first thing after a reset. We want to skip the Arduino initialization code. As per suggestion by user Comintern in another question you can write a main routine with a longer prototype to make the linker prefer it over the one shipped with Arduino:
int main(int argc, char** argv) {
  if (/* is your bootloader reset flag set in EEPROM */) {
    // first clear the flag
    // ...

    // Jump to bootloader, after reset source check (optiboot on atmega328)
    asm volatile ("jmp 0x7e0a");
  }

  // Else proceed same as Arduino main
  init();

  #if defined(USBCON)
      USBDevice.attach();
  #endif

  setup();

  //The one shot loop...
  loop();
  if (serialEventRun) serialEventRun();
  //Put whatever else you need to do between before the unending loop here.

  for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
  }

  return 0;
}

Note:
Using these jumps depends on your bootloader being exactly the one referenced. AFAIK that is the one the Uno ships with, but that could change in the future.
The code is untested.
The main overwrite trick depends on the linker exhibiting this behaviour which I think is also prone to change (it could be guaranteed by c/c++ standard, I don't know that).

Thanks a lot for such a detailed suggestion. In general i believe it would be better to perform reset instead of jumping into bootloader code directly and having deal with restoring state/registers/etc. Is there any possibility to perform "clean" reset to jump into bootloader just external reset button clicked or just powered on?

BTW, since i'm getting 0x14 and 0x10 i believe it's not optiboot. I'm having pretty old Uno r3 and i believe it's not using optiboot. And on the bootloader link i've sent you can see 0x14 and 0x10 are used to start/end packet

Those values are part of the STK protocol, see https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/bootloaders/optiboot/stk500.h. I'm quite sure Uno r3 has always shipped with optiboot.

The reset is taken care of by your watchdog reset. The manual reset was just an alternative suggestion to avoid using EEPROM.
The flow will be: set EEPROM flag - do watchdog reset - bootloader starts - bootloader exits because not external reset - your main  runs - read EEPROM flag - clear EEPROM flag - jump to bootloader past check
Hardware state will be very close to external reset.

ok. now i see STK_INSYNC=0x14 and STK_OK=0x10. agree special main() is the solution but it's highly undesired to make other people modify/burn bootloader. for now 1-wire reset seems to be more easy solution

Some people just connect a wire from an output to reset pin and pulls it low to reset. That isn't recommended though, because the pin won't be held low long enough to guarantee a proper reset. But supposedly it works for some people.

that's exactly what i was saying. i think for most people it's more easy than modifying bootloader

Using the special main you don't need to replace the bootloader, that's the whole point of the suggestion, but I maybe wasn't clear enough.

oh, now i see: Arduino code has 'main' and 'setup' and 'loop' functions declarations and the user just writes implementations. One can override 'main()' to longer one with clearing 'watchdog timer fired' event in EEPROM.The problem is that it should be cleared after watchdog timer fired and before bootloader starts and it seems it can't be done in overriden 'main' as it starts after bootloader finishes waiting for upload command. right?

asm volatile ("jmp 0x7e0a"); seems to do what i need (jumps into bootloader code to wait for upload commands). to be checked with BLE

working good for BLE too. For another MCUs one should find according address to jump, right?

yes, that's correct. On the mega the bootloader is different. It might not perform the check of the reset source.

How can i get .lst for Mega and other boards? I was unable to find .lst file Mega 2560 in https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/bootloaders/stk500v2, I know it uses stk500v2. The goal is to find according jump address for another boards: Nano (uses 328- to it's expected to be the same as for Uno), Leonardo (avr109 protocol, unnamed bootloader) and Pro mini.

It would have had to be provided by those who compiled it originally. You can disassemble the hex file and manually find the place, but it won't be very convenient. But I don't think the bootloader on the mega performs that check so try just jumping to the bootloader (address from hex file or datasheet).

now i'm trying to perform reset with HM-10 BLE module PIO commands. It works for Mega, but now for Uno. Can you suggest me with anything - http://arduino.stackexchange.com/questions/13146/arduino-not-responding-while-trying-to-flash-over-ble


text:
Arduino Mega 2560: Busted Atmega 16U2
I just bought an Arduino Mega2560 R3 and it doesn't connect to my Laptop. The connection is somewhat random, sometimes it connects and sometimes it doesn't.
Can someone help me identify whats the problem?
When it gets connected I can upload sketches.
I would like to remove the Atmega 16U2 and replace it with ftdi USB to Serial, would it be possible?

Did you try another USB port / another PC?

Also, the cable might be the problem. Check for that.

Yes I did both. The connection was random, now it doesn't connect at all, only an error. I can get it into DFU mode but Atmel Flip says usb device cannot be connected.

Do you have an ISP programmer / another arduino

I have bought an I |SP programmer but it will take 3 weeks to reach and no I dont have another arduino, TBH I'm scared to buy another one. I am buying an FTDI USB to TTL/Serial, could that help?

The serial cable will help to program the actual 2560 chip itself. IS the Arduino clones that you bought.

@RSM Its an original one.

You can use your USB/Serial adapter to program the 2560 as the Arduino uses the 16u2 as the same thing to program the mega. You shouldn't remove the 16u2, just wait till you get the programmers and reflash the 16u2 with its firmaware and it will work, I actually had the same problem where the DFU didn't work and the 16u2 stopped responding, after reflashing the firmware it worked. The firmaware can be found under(as of 1.6.0):
...\Arduino\hardware\arduino\avr\firmwares\atmegaxxu2\MEGA-dfu_and_usbserial_combined.hex
You need to connect the Serial pins on the FTDI and Mega in the below fashion:
 FTDI           MEGA
 GND<----------->GND
 CTS<----------->GND
 VCC<----------->VCC
 TXD<----------->RX0
 RXD<----------->TX0
 RTS/DTR<---||-->RST

The Capacitor between the DTR pin and RST pin are needed this should be 100nF.

I have bought an I |SP programmer but it will take 3 weeks to reach and no I dont have another arduino, TBH I'm scared to buy another one... –  echo_salik

If you are buying clones, those will more than likely give issues as they will be cutting back on costs in places, i.e. QC checks.

Actually the ISP is a normal one but the shipping takes time to my country. I'll try this out and let you know. How will I flash it, like what software will I use to flash it? Arduino Studio will work with it?

@echo_salik - you can use avrdude to flash the 16u2, there are a few tutorials on using it, I will add a link when I'm back at a PC

On my USB to Serial Module, it just have the following pins: 3V3 - TXD - RXD - GND - +5V Its a USB to TTL device. Could that work?

@echo_salik I think that should work, you will just be doing some fancy finger work, you will still connect serial lines as normal and the power, but on upload you will need to push reset on the board manually.

@echo_salik - brain fart, if your USB-serial chip is exposed, and you can get the pin put, see if you can solder a wire to the DTR pin? Just if the other way fails to upload.

well, TBH i think I ruined my USB-TTL, I am following this http://kaushleshchandel.com/wordpress/?p=194. No great with soldering on such small pins.

@echo_salik aside, is the board warrenty/guarantee still valid for an exchange, because if the board started out with a fault when you first used it you should be able to exchange the board. Also what seems to be the problem with the PL2303 board?

No problem, Luckily its working. I was able to unfu** (can't think of a more suitable word) it somehow. But cant upload. For how long should I hold reset?

@echo_salik - if you are just using the cable without the mod, hold it down until you see the status say 'uploading' and then release. Or push it once as it says uploading. You just have to get the timing right at that point. Again do you know if you would still be able to get the board exchanged? Thus would be a option if this gives you a bad experience.

No the items are not exchangeable. But i'll keep it for some more projects. Might come handy in future. I did buy the com port one. I'll post result with it soon.

I finally got my ATtiny44 Programmer and got it installed in Windows 8.1x64. it is listed as Atmel USB Devices > USBtiny. When I flash it I get the error usbdev_open(): did not find any USB device "usb" . What should I do?

@echo_salik - cool dude ;)

I still get the error for Arduino Device descriptor failed after successfully flashing the 16u2. So the uC is busted right?

@echo_salik - is this when you plug the board back in?

Yeah... If got flashed correctly: AVR dude Image But I still get this Device Manager

Forgot to mention, I got it to work with my USB to TTL.

@echo_salik - maybe try reinstall the drivers for the mega, the chip seems to have flashed correctly from the screen shot.

Let us continue this discussion in chat.


text:
Execute Code on power off?
Arduino newbie here.
I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.
My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.
I would configure it as a Hue remote control, e.g. with ArduinoHue; if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.
Whenever it gets power, I would have it turnOn() all lamps, and whenever its power supply is turned off, I would have it turnOff() all lamps.
The first part seems simple to me, the second part - not so much.
So here's my question:
Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down? Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?
I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.

Bonus question: am I likely to run into noticeable delays when powering on because the device needs to boot/initialize first?

2 Options:
Know, beforehand that it's going to lose power, or sense this so fast that it's able to execute the code.
Use a 'backup' chargable battery that will power the arduino until the lights have been switched off. And then put the arduino in either sleep mode or just power it off.

Is it possible that the program gets disarranged in low power mode??
I did the same with a 1F capacitor to use with a RS 232 connection and it works so far. But sometimes it stops working at all. I guess that at low power, the variables in RAM or the program gets disarranged and fail, after low power and later on power on again. I use counters in the program. Or maybe its not a good idea to use RS232 (with MAX232) where one side always get turned off and on?

You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.
If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.
However, as Hue Bulbs are Zigbee controlled, with provision ofr both iOS and Android control,  you should be able to control them via Zigbee directly without any connection to their wiring.

Hue control
Hue specifications

Thanks! Your idea of accessing the circuit from the switch is intriguing, but won't work in my particular case: not enough room there - especially for the power supply.

How would I use the capacitor to achieve this? And would I have to throw additional hardware at the system in order to sense the main power going off, or could I do this through software only?

Add a diode to the incoming power. Add the large capacitor (or multiple in parallel) after this. Connect one of the arduino pins to before the diode, so you can measure if the input voltage is low (indicating power loss)(assuming a 5v power supply). But I think you'd need a very large capacitor for this.

For the capacitor part, two one Farad supercapacitors in series (each 2.7 volts max) cost about a dollar, and there is one 10 Farad cap for two dollars each.  I guess that one of these options would work.  And the supercaps should last a very long time.  I'm not an Electrical Engineer -- just a Joule Thief hobbyist, but I thought this would contribute to your design and wouldn't cost much.
As far as balancing the supercaps, since we're close to the 2.7 volt max, I personally would just put three of the supercaps in series with a voltage divider of three 10K resistors in series tied in, but they would probably not really be necessary.
Oh, and the supercaps I spoke about are actually relatively small (10mm dia x 32mm high for each 10F, and 8mm dia. x 13.5 mm high for the 1F supercaps).  Found the 1F at $1.03 as 1572-1270-ND on Digikey.  The 10F was $1.97 each for 1572-1287-ND also on Digikey.


text:
How do I use I2C from an Arduino Uno when I have a GSM shield mounted?
This may be an extremely obvious question but I don't seem able to find a definitive answer.
I have an Arduino Uno and a Sim900 GPRS/GSM shield fitted on top of it. I had I2C working on the Arduino to communicate with a Raspberry Pi, but now that I have put the shield on top I can't get the Pi to detect the Arduino. As far as I can tell the SDA and SCL pins on the Arduino aren't being used by the shield so does anyone have any idea how I go about this?
Thanks

I had a similar issue and disconnected the coupling between the shield for A4 and A5. Seemed to work. Almost as if the GSM didn't require it but it was on the i2c network

There seems to be a number of different Sim900 shields from different suppliers? I suggest you check/post the datasheet of the one you're using. If I2C works without the shield, and does not work with the shield connected , then it seems logical that there is a pin clash.
There is a good Random Nerd Tutorial on getting started with the shield on a Uno. Maybe test it out completely before connecting to the Raspberry Pi?
The Raspberry Pi is 3.3v and the Uno is 5v. You didn't mention level shifting in your question, but it may be worthwhile.

I mean thanks for the reply, but this question is nearly 6 years old lol. At this point I haven't got the faintest recollection of how I actually fixed it

@Brae :-) No problem, I’m new to the forum and had to find some entries to contribute to to build up some points. Glad to hear your project worked out.


text:
Servo broken? Explanation, Solution
I had a question, I tried to control a servo with the arduino, to the servo I attached a stick and at the end of the stick a little weight. After runing my code my servo tried to move the stick, but maybe it had not enough torque to move it so after that I paused the code. Then I tried to control the servo again without weight and this time it didn´t moved. Is it broken? why? Is there a posible solution? Thanks

There is really no way for us to tell. Its possible that its broken but if all you did was stall it I find that pretty unlikly.

How are you driving these servo's? Bear in kind that servos are quite different from regular motors... http://handyboard.com/hb/faq/hardware-faqs/dc-vs-servo/

Without seeing the code you are using, it is difficult to know if you are attempting to drive the servo correctly.
Remember, with a servo, the PWM signal is a positioning signal, not a duty cycle signal as used with speed control on regular dc motors.

You may have broken the gears if the servo was not rated for the load applied or if the servo was rotated too far (by software) 1ms and 2ms should be your (conservative) software limits, though most servos will work from 0.7ms to 2.3ms.

Servo is probably broken, or fried.
Same thing happened to me, that too twice!
First time, I had fried the servo(overpowered it).
Second time, one of the gears had broken.(finally I managed to salvage one total servo by using gears from fried one in the one with broken gears)
First, try a different way to control the servo. If the servo fails to respond, then try opening up the servo.You might be able to salvage something.

P.S. If the servo is fried, there is not much you could do, but if one of the gears is broken, KEEP THE BOARD, as you can use it with another motor using Transistor H-Bridge.

If you are using a H-Bridge, you should probably use MOSFETs instead of the usual BJTs so that you can use larger Motors


text:
Find external router IP from Arduino Yun inside router network
I want two Arduino Yuns in different private networks to communicate, i.e., behind two distinct routers of which at least one does not have dynamic DNS, so its external IP may change from time to time.
To be reachable, this Yun could forward its router's external IP to the other Yun which has a fixed DNS name. But for this to work, it must be able to determine its router's external IP.

How can the Yun find out that the external IP of the router has changed? The Yun will be runnning all the time.
If the external router IP has changed (i.e., my Fritz.Box disconnects in the night and may receive a different IP when it reconnects), how can the Yun determine the new external IP?

If this is not the right place to ask, I'm happy for pointers to somewhere else (Server Fault SE forum?).

See this, pretty much what you want:
http://stackoverflow.com/questions/3097589/getting-my-public-ip-via-api

@Devrope This looks promising, but I can't try right now. Thanks a lot!

You could use Dyndns Service like noip.com (free for basic service) and do the publishing of the new IP within the FritzBox. On the Arduino use just the hostname you specify at the dyndns service.

You can write a program that updates its own external IP every couple of minutes/hours, or when it doesn't get a response from another Yún/PC/server.
You can use this link (or find another site of the web that gives you your external IP address): http://www.realip.info/api/p/realip.php
This link has a beautifully formatted information that you can easily extract. I have a similar solution on one of my servers that have a dynamic IP...


text:
Running C for arduino
Is there a compiler that I can use to run C on an arduino or any other way so that I can upload C programs to my arduino?

What do you mean by "run C"?  You can just compile them into your sketch.

How can I do that? I'm not very familiar with arduino software.

You basically do that every time you compile a sketch. The Arduino compiler is C++, which is backward compatible with C for the most part.

*!!!** :-)

Perhaps you should look into here
https://github.com/arduino/Arduino/wiki/Build-Process
Arduino uses avr-gcc compiler. Basically, it is a C compiler.
There is an step by step on how to customize this process using an avr-gcc compiler of your own here
http://www.wikihow.com/Write-Arduino-Software-in-C
But I best recommend you downloading the arduino IDE on the official website to get things going. It has all the serial pairing stuff you don't really need to know to get started.
Hope it helps.

GCC is a C++ compiler? Anyway, most/any C++ compiler can compile C-code as C is basically a subset of C++ (Don't quote me on this though, it'll work, but it's not that trivial)