text:
Program an ATMega328P and use it without Arduino board
I'd like to use an ATMega328P for my project, I hope to do it without the Arduino board.
I know with the Arduino IDE and an Arduino board I can program the microcontroller. However, would it be possible once I've programmed and debugged the program with Arduino IDE + Arduino board, to take away the microcontroller from the Arduino board and to use the ATMega328P separately, without the board?
If yes, what additional configurations I should do the ATMega328P to work correctly on the breadboard?

Use ATMEGA328 P-PU with Arduino UNO bootloader....you can find it in hobby stores and online and stuff ☺

Using the bare chip is absolutely feasible and no problem whatsoever.

This is not the same question as your but you might get some bits of information from it.  https://arduino.stackexchange.com/questions/32970/sense-checking-arduino-uno-barebones-schematic

You can follow answers of This Question

Yes you can use ATMega328P without arduino board. I always use the IC without arduino. There are two ways of doing it.

You can use arduino board with the IC. Program the IC and then take it out and use it in your circuit. You will have to use 16MHZ Oscillator with capacitors.
If you don't have arduino board, you can use other programmers like USBasp to program your Atmega328p. In this case, do not use the direct upload button instead use the upload using programmer options from file menu. Do not forget to select board as Arduino Pro or Pro Mini (5v, 16mhz) With ATmega328 and programmer as USBasp.

NOTE: Refer to Atmega328p Pin Mapping and program your device accordingly. Enjoy!

You can remove an ATMEGA from an Arduino and use it in your own board, however when used on a typical Arduino board the chip will be fused for an external crystal as a clock source, rather than the (simpler but less accurate) internal clock.
You cannot change the clock source over ISP unless the clock source the chip is currently expecting is operational, so if you want to change the clock selection you will want to do that before removing the chip from the Arduino.
However, you can also provide a clock crystal and its two capacitors (or a substitute resonator which often has this built in) on your external board.
Typically chips (even those pre-flashed with a bootloader as a convenience) are cheaper than boards, so it's unclear why you would want to move the same chip off the Arduino as opposed to using another.  You will want a USB-logical level serial adapter anyway, and once you have that you can do development on the bare chip on your board, even if you do initial testing on the Arduino.  In a pinch if you don't have the USB converter you can either pull the chip out of an Arduino board and run wires from its D1 and D0, or hold the on-board chip in reset to allow you to borrow those serial lines without interference.

My idea is to use only a microcontroller without a board. As it is easy to program an Arduino, I thought I may chose an ATMega. So, I have an Arduino uno, my idea is to buy only one ATMega and to program it and debug it using the uno board. However, I've just reaslised that if I separate the ATMega from the Arduino, I would need to add components(crystal, pull up resitances..). Can you please explain what you mean in the last paragraph of your post? Is there a simple way to program directly an ATMega(or any other microcontroller) without using the arduino IDE? Thanks.

While you can skip the IDE, using it or not is essentially irrelevant to the complexity of your circuit, as you can either use the IDE or not with a circuit that either has or doesn't have an external clock and either using a USB-serial on your target board, on a cable, or by programming your sketch with an ISP programmer.  Yanking a chip off a board gets you nothing compared to just buying a chip either with a bootloader or without and loading one yourself, potentially using your intact Arduino as an ISP programmer, or using ISP to directly load your sketch without a bootloader.

Search for "Build an Arduino" - you'll find tons of how-to articles about doing just that. You'd need to be able to solder connections on a printed-circuit board (and not even that if you wanted to use a solderless breadboard), but it's really straightforward. You can even build it first and program the MCU on the PCB using an FTDI cable. I use an Arduino board and a solderless breadboard to experiment with unfamiliar parts, but I usually go immediately to a hand-built board once I'm familiar with all of the components I'll be using.
Prototyping with the Arduino board lets you throw together a bunch of parts and get something working quickly, and if the Arduino is more capable than your final target - f/ex, a Mega 2650 - you can temporarily ignore the memory and I/O constraints of the smaller device.

It's fairly easy to use a standalone Arduino chip. The one tricky thing about the chip used for the official boards is that they are fused to use the faster (and more accurate) external oscillator that's mounted on the board. This applies even when you purchase the loose chips, since most are resold with intention of being installed in an Arduino board to replace a burned-out one, with exception of perhaps the ones from Digikey.
Caveats: The Arduino is designed as a prototyping board, and few things do better than it does at this task. You may want to leave the chip on the Arduino board until you are done designing and testing your circuit. Only then do you connect it directly. It can be used in-place if you have a clock circuit in place, or you can change the fuses (see later) and reprogram the Arduino with an ISP adapter and a clock speed of 8mhz (PlatformIO lets you do this (and allows direct imports of an Arduino sketch) -- check their docs page for the Atmel AVR plugin, but you can also look up a number of guides on how to add a board file to Arduino to tell it to use the 8mhz option for a bare chip)
If you remove the chip for use in a different circuit, it either needs that clock circuit added back in, or to have its fuses changed (I'll get to that in a minute). It will also be hard to program, for a number of reasons, so you'll want to purchase a bit of fairly cheap hardware:
Programming a standalone chip: The Arduino's CPU is not natively designed to talk to a computer. You need an intermediary. On the Uno, this is done via a second Atmel chip that has USB capability, and a bootloader on the main chip. What that does, is that it uses the UART for upload of the program while the USB chip converts the PC's messages to UART signals. Since the bootloader is somewhat of a pain when the chip is on its own (since UART is picky and installing it sets the chip to use an external clock as a result), you'll want to buy an ISP programmer for the Arduino (or follow the Arduino-as-ISP sketch and instructions to make your own, which requires an Arduino with chip present, so you'd need a second to be programmed).
These can program the ATMega 328 directly over SPI, without a bootloader (there are many instructions on the Internet; search "program bare ATMega 328P with USBAsp", for instance). This makes it a lot easier to change and debug your program outside of popping the chip out and back into the original Arduino board. You also need one to change the clock settings if you don't want to use an external crystal.
If you want to debug the chip, it's useful to also purchase a FTDI adapter or other USB-to-UART converter. Note that without the reset circuit part of the board (or again, adding your own), this still won't let you program the ATMega even with the bootloader, though. For that, connect the ground, RX, and TX pins to the adapter. You may or may not want to connect the VCC line, but it's advised to not do so if there's a lot of things connected to the chip and/or it has its own power supply. Note that the RX and TX need to be swapped when you connect them; that is, RX to TX and TX to RX -- you want the chip to RX (receive) what the adapter is TX( transmit)ing, and vice versa.
The clock circuit is not hard to build, but it requires a few components you may not have. So, to change the clock source, go to http://www.engbedded.com/fusecalc/ and select the ATMega 328P. The defaults are good, but you may want to enable EEPROM keep-on-erase and disable the clock divide-by-8 or adjust the brownout settings. Don't touch anything else (disabling reset or SPI or enabling DebugWire result in "fun" that requires a HV programmer to fix). When done, paste the command it provides to the AVRDude command. You will need to change the -c options (-p is already set to the ATMega 328P, but will fail for non-P 328s -- don't buy those), and perhaps add the -P option (for Port). Do not omit the lowercase -u option, or it will refuse to update the fuses.
avrdude -p m328p -v -c usbasp -B 100 -u [add extras here: (-P <PORT>) <fuse set command here>]

Note that if you purchase a USBASP (make sure it has three sets of jumpers!), for all that they are my favorite programmer, they may not have the updated firmware that supports the -B option (which you'll probably need). That means that you need to attach it to an Arduino via the six-pin programming port, in the exact same way that you'd use it to program the Arduino's bootloader, but then use the Arduino-as-ISP sketch to program the new firmware to the programmer (search "update the usbasp firmware via arduino-as-isp")! For reference, that usually means that the cable faces away from the body of the board, and you'll probably have to program the sketch before connecting the cable. Also enable the power-from-programmer jumper on the USBASP (5V), and the "self-program" one. (see https://forum.arduino.cc/index.php?topic=560719.0 for the location of the power and program jumpers (JP2)).

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


text:
two 7HC595 and only 12 outputs
im new to arduino and thinking to create a LED project.
im creating a LED project and i want to control 12 LED's. so i use two 7HC595 but problem i face is how can i only control 12 outputs ?
and i want to create multiple blink patterns with 12 LED, please be kind enough to provide blink patterns that i can modify and create different partners.
i have found many shift-out programs but i do not understand how to limit it to 12 outputs and create multiple blink patterns.
thanks

Other than only outputting 12 bits?

Just act like there are 16 leds, but keep the last 4 leds off all the time.

How can i code it. Any examples?

Is Google not working? Try here.

Thanks for the grate tutorial.  How can i make multiple blink patterns

Do not worry about limiting it to 12 bits, send all 16 and use just the twelve you need.  You never know you may expand the project.  Whatever is on the unused bits is irrelevant. they do nothing.

If you use 74HC595, you have to send data to all the bits no matter what. Even if you only want to change 1 bit, you have to resend the whole bit sequence.

source: Stack Exchange

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

sort: votes


text:
Is it possible to create an interface between Teensy 3.2 and a DSP?
I realize that this is a forum for Arduino but since the Teensy 3.2 is compatible with the Arduino IDE I thought it would be appropriate to ask the question here.
Anyway, can I create an interface between the Teensy 3.2 and a DSP, more specifically the TMS320C5534-Fixed-Point Digital Signal Processor and how could I go about it?
What I am trying to do do is capture an EEG and EoG (electrooculogram) signal, amplify it, filter the signal, use the DSP for ADC and signal processing and finally get this information from the DSP to the Teensy 3.2, which will then make a decision based on the signal obtained from the DSP.
Maybe this is a simple question but I couldn't find any answers online. I am pretty new to the world of microcontrollers.
Thank you guys!

Why can't the DSP make the decision?

Because this involves obtaining and analyzing large amounts of data in real time. I though it would be faster If I used the DSP strictly for signal processing, which is intensive in this case, and then send the processed signal to the microcontroller to compare this information with the signal that I am looking for (i.e a certain brain wave and a pattern of eye movement). If a match was found then the microcontroller has to send a notification wireless to a mobile device saying that a match has been found.

the microcontroller would also monitor that there is good contact with the electrodes. So, I guess in short it would be to make the whole system faster, but I am not sure it that would be the result.

Yes, you can do it - for example if the data rates are moderate with an asynchronous serial interface.  But don't even bother trying to implement pattern recognition and decisioning on a microcontroller, until you have fully validated your algorithm on a PC, possibly against a large set of recorded data, and ultimately against data transmitted from the DSP sampler.  Until you have done that it is premature to select a micro as you can't reliably know what your computational and memory needs are.

I would use one of the serial interfaces and connect them together that way.  If Asyinc run as fast as reliable.

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


text:
Arduino snake on 5110 screen - some help needed
I'm trying to make a snake game using the u8g lib. But for now, only the second body part of the snake follows the head, where I want the whole body to follow the snake's head and I don't understand why it doesn't work.
Here is the code:
#include "U8glib.h"

U8GLIB_PCD8544 u8g(13, 11, 10, 9, 8);    // SPI Com: SCK = 13, MOSI = 11, CS = 10, A0 = 9, Reset = 8

const int SNAKEMAXSIZE = 10;

bool title = true;
bool gameRunning = false;

enum direction {HAUT, BAS, GAUCHE, DROITE};

int snakeDirection = GAUCHE;

class snakeCell
{
  private:
  int x;
  int y;

  public:

  snakeCell(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  snakeCell()
  {
    x = 42;
    y = 24;
  }

  void setX(int x)
  {
    this->x = x;
  }

  void setY(int y)
  {
    this->y = y;
  }

  int getX()
  {
    return x;
  }

  int getY()
  {
    return y;
  }

  void draw()
  {
    u8g.drawBox(x, y, 5,5);
  }
};

class Pomme
{
  public:
  int x;
  int y;

  Pomme(int x, int y)
  {
    this->x = x;
    this->y = y;
  }

  Pomme()
  {
    x = 42;
    y = 24;
  }

  void randomSpawn()
  {
    x = random(48);
    y = random(84);
  }

  void draw()
  {
    u8g.drawCircle(x, y, 5);
  }
};

snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(52,39)};

Pomme pomme = Pomme();

void draw(void) {
  // graphic commands to redraw the complete screen should be placed here
  u8g.setFont(u8g_font_6x13);
  //u8g.setFont(u8g_font_osb21);
  u8g.drawRFrame(0, 0, 84, 48, 0);   //Screen frame
  printTitle();
  game();
}

void setup(void) {
  // flip screen, if required
   //u8g.setRot180();

  // set SPI backup if required
  //u8g.setHardwareBackup(u8g_backup_avr_spi);

  // assign default color value

  randomSeed(analogRead(0));

  if ( u8g.getMode() == U8G_MODE_R3G3B2 ) {
    u8g.setColorIndex(255);     // white
  }
  else if ( u8g.getMode() == U8G_MODE_GRAY2BIT ) {
    u8g.setColorIndex(3);         // max intensity
  }
  else if ( u8g.getMode() == U8G_MODE_BW ) {
    u8g.setColorIndex(1);         // pixel on
  }
  else if ( u8g.getMode() == U8G_MODE_HICOLOR ) {
    u8g.setHiColorByRGB(255,255,255);
  }

}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

  // rebuild the picture after some delay
  delay(50);
}

void printTitle()
{
  if(title == true)
  {
    u8g.setFont(u8g_font_6x13);
    //u8g.drawStr( 26, 30, "SNAKE");
    delay(2000);
    title = false;
    gameRunning = true;
  }
}

void moveSnake()
{
  //move head accordingly to movement
  if(snakeDirection == GAUCHE)
  {
    snake[0].setX(snake[0].getX() - 1);
  }
  else if(snakeDirection == DROITE)
  {
    snake[0].setX(snake[0].getX() + 1);
  }
  else if(snakeDirection == BAS)
  {
    snake[0].setY(snake[0].getY() + 1);
  }
  else if(snakeDirection == HAUT)
  {
    snake[0].setY(snake[0].getY() - 1);
  }

  //tail follow head
  for(int i = 9; i > 0; i--)
  {
    snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
  }
  delay(100);
}

void restart()
{
  //snakeCell snake[10] = {snakeCell(), snakeCell(47,24), snakeCell(52,24), snakeCell(57,24), snakeCell(62,24), snakeCell(62,29), snakeCell(62,34), snakeCell(57,34), snakeCell(52,34), snakeCell(47,34)};
}

void drawSnake()
{
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    snake[i].draw();
  }
}

void spawnApple()
{
  pomme = Pomme();
  pomme.randomSpawn();
}

void checkCollision()
{
  // detect if apple eaten
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    if((snake[i].getX() == pomme.x) && (snake[i].getY() == pomme.y))
    {
      pomme.randomSpawn();
    }
  }
  // detect if snake hit wall
  for(int i = 0; i < SNAKEMAXSIZE; i++)
  {
    if((snake[i].getX() >= 84) || (snake[i].getX() <= 0) || (snake[i].getY() >= 48) || (snake[i].getY() <= 0))
    {
      //gameOver();
      restart();
    }
  }
}

void gameOver()
{
  gameRunning = false;
  //u8g.setFont(u8g_font_6x13);
  //u8g.drawStr( 14, 30, "GAME OVER");
  //delay(1000);
  restart();
  gameRunning = true;
}

void game()
{
  if(gameRunning == true)
  {
    checkCollision();
    moveSnake();
    drawSnake();
  }
}

Thanks in advance.

There might be a problem with going through your snake array from the back.
I'm not sure if you're filling it from front or back, but you should read it from there aswell.
And, every time you re-draw your snake, you're creating a new snakeCell?
//tail follow head
  for(int i = 9; i > 0; i--)
  {
    snake[i] = snakeCell(snake[i-1].getX(),snake[i-1].getY());
  }

You should differentiate between a snakeCell that is active or not. And just re-position and draw it when it's active.
Be sure to check if you're not placing them ontop of eachother. You should put each piece of the tail in the previous position of the preceding part.
Also: You shouldn't really be mixing up French and English naming in your code.


text:
How to read RC receiver channels without using pulsein() command with arduino
I am building a quad-copter, the problem is of stability and for better stability lesser sampling time is required. For lesser sampling time I need to have faster loop() function. But the Pulsein() command takes very large time which in turn expands the sampling time. Is there any method to read the rc channels in background and read them from an integer.

Why not have a look at some of the open-source ATMEGA-based quadcopter firmwares, at least to examine for ideas?  I don't know if you will find some that are based on the Arduino libraries, but you should find some that will run on the hardware.  That said, fundamentally you cannot measure pulses faster than they occur, which is typically a repetition rate of only around 50 times a second.  You can write code which accomplishes other things while waiting for the pulses, but you can't speed them up unless you change the receiver, for example directly talking to the 2.4 GHz chip.

The keyword you are looking for here is interrupt.  What is a pulse but a signal that goes from low to high followed by going from high to low, with some period of time between them?
Instead of sitting there waiting for the pulse to arrive then measuring how long it is, which is essentially what pulseIn() does, you need to attach the signal to an interrupt pin.  Then you write an interrupt routine that triggers when the signal changes from one level to another which looks to see what the level actually is.
If the signal has risen from low to high then you record the time it happened.  If the signal has fallen from high to low then you look what the time is, and subtract the time you remembered from when the signal rose.  That difference is then the width of the pulse, which you can store in an integer to read in your main loop.
If you have a number of signals you want to monitor you might want to look into using the pin change interrupt which allows you to use any pin as an interrupt source.

While you can use interrupts to allow potentially accomplishing other things while waiting for the pulses, they won't permit an input-based control loop to run at a higher rate than the inputs themselves arrive at - for a legacy PWM output, that is typically in the neighborhood of 50 Hz repetition rate.  Of course it is possible to run the on-board stabilization algorithm at some multiple of the radio data rate, if desired.

@ChrisStratton I think you are misinterpreting the question. When he talks about "sampling" I am assuming (and I think quite rightly) that he is talking about sampling something else - accelerometers maybe - since he says waiting for the pulses slows down the sampling that he is doing, and it's the sampling he needs to do faster, not the reading of the pulses.

I agree with Majenko here. pulseIn blocks, which is what I gather he is trying to avoid. Using interrupts would help in this situation.

yes i am using accelerometer, for faster data reading. can i use interupts for all of 6 channels in RC reciever

@Majenko I have read your answer and got information from it. but Now the problem i am asking in other quesstion is how to read multiple channels with one interupt. thats the headache now,

@BilalAyub And in this answer I mention that if you have lots of channels to read you should investigate the pin change interrupts.

that is not easy work, i have asked the other question for that type of help

Simple enough: Step 1: ask google for library. Step 2: install library. Step 3: Write interrupt routine to check which pins have changed.

You may find my answer to another question –  Read RC receiver channels using Interrupt instead of PulseIn – useful.  It includes the sketch shown below, which is intended for background timing of four RC channels attached to pins A0-A3.  See the other answer for further comments about the code, example output, etc.
/*  rcTiming.ino -- JW, 30 November 2015 --
 * Uses pin-change interrupts on A0-A4 to time RC pulses
 *
 * Ref: https://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein
 *
 */
#include <Streaming.h>
static   byte rcOld;        // Prev. states of inputs
volatile unsigned long rcRises[4]; // times of prev. rising edges
volatile unsigned long rcTimes[4]; // recent pulse lengths
volatile unsigned int  rcChange=0; // Change-counter

// Be sure to call setup_rcTiming() from setup()
void setup_rcTiming() {
  rcOld = 0;
  pinMode(A0, INPUT);  // pin 14, A0, PC0, for pin-change interrupt
  pinMode(A1, INPUT);  // pin 15, A1, PC1, for pin-change interrupt
  pinMode(A2, INPUT);
  pinMode(A3, INPUT);
  PCMSK1 |= 0x0F;       // Four-bit mask for four channels
  PCIFR  |= 0x02;       // clear pin-change interrupts if any
  PCICR  |= 0x02;       // enable pin-change interrupts
}
// Define the service routine for PCI vector 1
ISR(PCINT1_vect) {
  byte rcNew = PINC & 15;   // Get low 4 bits, A0-A3
  byte changes = rcNew^rcOld;   // Notice changed bits
  byte channel = 0;
  unsigned long now = micros(); // micros() is ok in int routine
  while (changes) {
    if ((changes & 1)) {  // Did current channel change?
      if ((rcNew & (1<<channel))) { // Check rising edge
        rcRises[channel] = now;     // Is rising edge
      } else {              // Is falling edge
        rcTimes[channel] = now-rcRises[channel];
      }
    }
    changes >>= 1;      // shift out the done bit
    ++channel;
    ++rcChange;
  }
  rcOld = rcNew;        // Save new state
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting RC Timing Test");
  setup_rcTiming();
}

void loop() {
  unsigned long rcT[4]; // copy of recent pulse lengths
  unsigned int rcN;
  if (rcChange) {

    // Data is subject to races if interrupted, so off interrupts
    cli();          // Disable interrupts
    rcN = rcChange;
    rcChange = 0;       // Zero the change counter
    rcT[0] = rcTimes[0];
    rcT[1] = rcTimes[1];
    rcT[2] = rcTimes[2];
    rcT[3] = rcTimes[3];
    sei();          // reenable interrupts

    Serial << "t=" << millis() << " " << rcT[0] << " " << rcT[1]
       << " " << rcT[2] << " " << rcT[3] << " " << rcN << endl;
  }
  sei();            // reenable interrupts
}


text:
NRF24L01+ how much supply ripple is acceptable?
I'm trying to get a simple TX/RX pair to work. I've got identical Nanos and I'm using the example from:
http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
I followed the advice about adding a cap across the Vcc GND on the nrf board, and added a 10uF electrolytic to both.
I still haven't received a packet yet, and I wondering how to eliminate the power supply as a cause. I scoped the power pins, and even without a cap I got about 250mV of ripple. With the cap it goes down to about 100mV. Is this within tolerance? What kind of caps does anyone else use, and has anyone scoped the result to see where the threshold lies?
Aside form that, are there any other clever ways to debug this issue?
Update 20160122. I finally tested using those cheap piggyback 3.3v regulator boards that plug straight into the nrf board. Works perfectly, not one lost packet over 5000 packets sent. Interestingly, the RX side appears to be the fussy one. Thanks to everyones' suggestions. For a total combined cost of about 4$ per node, I have a great wireless TX/RX solution.

Having two units too close to each other can cause problems. Either have them apart, or lower the transmit power.

If you have, try a bit bigger capacitors. Capacitors on my modules are 100uF and they work.

In the end I put a scope across a 10Ohm resistor in series with the nrf power leads to see what kind of current draw the TX was using, and also played with adding different caps. You're right, the recomended 0.1uF to 10uF doesn't seem to be enough. I get best results with a 470uF electrolytic. But I still get about 20% packet loss across my desk. And the voltage on RX side is very noisy. Both boards are being powered by the 3,3v nano on-board regulator. I've ordered some piggyback regulator board for the nrf so I'll test with those when they arrive.

20% packet loss? Whoa, what are you using to power the regulator? Have you tried decoupling the power supply even more?

Right now I'm using the Nano on board 3.3V reg for both T and RX. They are plugged into the USB port on my laptop. The TX side seems to be quite stable. The RX side shows lots of noise, with Vpp of about 100mV. Strangely, using PowerOff, delay and PowerOn to try to limit the current draw on RX doesn't seem to have any effect. Whereas decreasing the retries on the TX shows a corresponding decrease in power consumption. And 20% loss is my best so far. If I use a 10uF cap I often get no packets at all.

I would suggest using a different power supply, that appears to be your problem.  250mV is 1/4 of a volt, that is a lot of noise/ripple.  I am assuming it is ripple from the AC mains.  The series resister is way to large, try something about 0.1 ohm.  Also put a filter cap on the load side of the resister.  If you have high frequency noise add a 0.01 cap that will help.  Be sure the grounds between the units are solid.
Gil
I have a feeling it is narrow fast rising spikes.  If so the odds are very high it is the power supply.  Can you try an analog one and see if the problem goes away?  Try adding more bulk capacitance, at the rate of at least 1000uF per amp.

Thanks for the suggestions. The ripple is of a much higher frequency than mains hum. I'm collecting together a few ideas and I'll test them when the alternative power supplies turn up. I'm pretty sure it's the receiver that is having trouble. I'm also not ruling out interference from other traffic in that frequency.

@mjk It's also worth mentioning clone modules have worse receiving ability. Check if you have original modules, it might solve your issue.

Thanks for the info. I tested using the 3.3v regulated piggy back boards last night, and they worked perfectly.

@mjk So you've fixed your issue?

Yes, as far as I can tell, the issue lay int he power supply. I tried direct from the Arduino 3.3v regulator. I also tried an external 3.3v supply from a bench supply, and all sorts of variations of caps to filter ripple. Funny thing is, as far as I can tell, the piggy back board has the same 3.3v regulator as the arduino. Same package size at least, with a few smd caps. Yet the result is clear. for the extra buck, I'll be buying a piggy back board with each radio device. All I have to do now is test the range, but for my current app, I  only need <10m max.

The additional load on the 3.3V regulator may be putting it at its limit and causing it to oscillate.  By adding the additional regulator you did two major things, first you reduced the length of the power line from the regulator and took some load off the regulator on the Arduino.  I remember reading a while back that that and several other modules reach the current limit of the Arduino.  Your solution is a good one and should remain stable over time.


text:
How to select a 0.1" header in Fritzing
Does Fritzing support the standard 0.1" break-away header?
When I search for "header" in its parts database, I see several examples, and some even seem to reference 0.1 headers, but I can't actually seem to select the physical part.
For example, if I select the "Header 3" part, the description specifically refers to 0.1 break away headers, but the "package" field references a completely different part, causing it to render incorrectly. If I click that dropdown to try and select a different package, there are dozens listed, but none look like a 0.1 header.


text:
Help making LEDs blink like blinkers in a car
I am trying to make blinkers and hazards lights for a car.  I can get
the left and right blinkers to work. I cannot figure out how to get
the lights to blink simultaneously like hazard lights would.
What I think I want is that when both inputs are HIGH then Both LEDs will
blink together at the same time.
I left the garbage and comments in the code so you can see what I have
tried.
Thanks for your help.
/*
 Blinkers and Hazard Lights

 Simulates a vehicles blinkers and Hazard Lights
 left button connected to pin 2 using a pushdown resister
 right button connected to pin 3 using a pushdown resister
 left LED connected to pin 9
 right LED connected to pin 10
 Hazard LED is Pin 13 At one point I was trying to make pin 13 represent the hazard lights but that is not what I want to do.

 When left button is pushed Left LED will Blink
 When Right Button Is pushed Right LED will Blink

 If this worked the way I wanted it to. when both buttons where HIGH both LED 9 & 10 would blink simultaneously.

 created 2015
 by thomsl41@gmail.com

*/

// constants won't change. They're used here to
// set pin numbers:
const int buttonPinLeft = 2;     // the number of the pushbutton pin
const int buttonPinRight = 3;
const int buttonPinHazard = 2 && 3;
const int ledPinLeft = 9;      // the number of the LED pin
const int ledPinRight = 10;
const int ledPinHazard = 13;

// variables will change:
int buttonStateLeft = 0;         // variable for reading the pushbutton status
int buttonStateRight = 0;
int buttonStateHazard = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPinLeft, OUTPUT);
   pinMode(ledPinRight, OUTPUT);
   pinMode(ledPinHazard, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPinLeft, INPUT);
  pinMode(buttonPinRight, INPUT);
  pinMode(buttonPinHazard, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonStateLeft = digitalRead(buttonPinLeft);
  buttonStateRight = digitalRead(buttonPinRight);
  buttonStateHazard = digitalRead(buttonPinHazard);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonStateLeft == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinLeft, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second
  }
 else {
    // turn LED off:
    digitalWrite(ledPinLeft, LOW);
  }

if (buttonStateRight == HIGH) {
    // turn LED on:
  digitalWrite(ledPinRight, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);              // wait for a second
  digitalWrite(ledPinRight, LOW);    // turn the LED off by making the voltage LOW
  delay(500);              // wait for a second

}
  else {
    // turn LED off:
    digitalWrite(ledPinRight, LOW);
  }
}

/*if (buttonStateHazard == HIGH) {
    // turn LED on:
  digitalWrite(ledPinLeft, LOW);
  digitalWrite(ledPinRight, LOW);
  digitalWrite(ledPinHazard, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2000);              // wait for a second
  digitalWrite(ledPinHazard, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
  //}
 //else {
    // turn LED off:
   // digitalWrite(ledPinHazard, LOW);
 }

}
*/

A "state machine" would help here. In a loop where you decide whether or not to turn on the left or right LED, you could turn them both on if you want the hazard flashers. Then a half second later you turn them all off.

It looks like you need to do something like:
if ((buttonStateRight == HIGH) && (buttonStateLeft == HIGH)) {
    digitalWrite(ledPinRight, HIGH);
    digitalWrite(ledPinLeft, HIGH);
}
else if (buttonStateRight == HIGH) {
    digitalWrite(ledPinRight, HIGH);
}
else if (buttonStateLeft == HIGH) {
    digitalWrite(ledPinleft, HIGH);
}
//One delay for all
delay(500);
//Shut anything off that might be on after the delay
digitalWrite(ledPinRight, LOW);
digitalWrite(ledPinLeft, LOW);

Your code is really hard to read but it may mostly be because you need to insert four spaces at the beginning of each line of code to make it look right on this forum.


text:
Problems with Arduino BT
I have an Arduino BT and I can't connect it to any device I have. I've tried in 3 different situations:
Win7 - If I choose 'Connect without a PIN code', the device seems properly detected but it doesn't appears in Device Manager. In the case of the connection with the PIN code, it throws a timeout error.
Win8 - Don't even ask me for the PIN code. A message 'This isn't working. Try again and verify if the device is still visible' appears.
Android 5.0 - When I try to pair and write the PIN code, I get a message 'Invalid PIN or password'.
The PIN is 12345, by Arduino.cc page.
Another different thing is that in the documentation, the board has the Blink code by default. But the orange light on the board doesn't blink, and don't turn green either. I didn't find anything about the color of the LED in this board.
Can anyone help me?


text:
Reading Arduino serial stream in Java using jSerialComm
I'm having issues reading the actual double values from my Arduino Serial.println() in my Java app. I've tried following usage examples found here but get what I guess is a hex value. The serial monitor within the Arduino program is displaying the correct values.
This is the code: I'm fairly new to this and would appreciate any comments regarding style/problems/inefficiencies within my code!
import com.fazecast.jSerialComm.*;
import java.util.*;
import java.io.*;

public class PortRead {
  public static SerialPort userPort;
  static InputStream in;

  public static void main(String args[]) {
    Scanner input = new Scanner(System.in);
    /*
     This returns an array of commport addresses, not useful for the client
     but useful for iterating through to get an actual list of com parts available
    */
    SerialPort ports[] = SerialPort.getCommPorts();
    int i = 1;
    //User port selection
    System.out.println("COM Ports available on machine");
    for (SerialPort port : ports) {
      //iterator to pass through port array
      System.out.println(i++ + ": " + port.getSystemPortName()); //print windows com ports
    }
    System.out.println("Please select COM PORT: 'COM#'");
    SerialPort userPort = SerialPort.getCommPort(input.nextLine());

    //Initializing port
    userPort.openPort();
    if (userPort.isOpen()) {
    System.out.println("Port initialized!");
    //timeout not needed for event based reading
    //userPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 100, 0);
    } else {
    System.out.println("Port not available");
    return;
    }

    userPort.addDataListener(new SerialPortDataListener() {
      @Override
      public int getListeningEvents() {
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
      }
      public void serialEvent(SerialPortEvent event) {
        if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE)
        return;
        byte[] newData = new byte[userPort.bytesAvailable()];
        int numRead = userPort.readBytes(newData, newData.length);
        System.out.println("Read " + numRead + " bytes.");
      }
    });
  }
}

Your code is reading characters and displaying the numeric value of the character codes.  You need instead to collect full strings (perhaps until a newline, not merely the amount of data vailable when your call returns!) and then parse numeric values out of that.  This is really a Stackoverflow question, not an Arduino-specific one.

Above code reading data sent by arduino and storing into byte [ ], instead of showing how much contents you have read, you need to show the total string.

related: Sending a floating point number from python to arduino

Since you are reading received data into array newData, you should replace System.out.println("Read " + numRead + " bytes."); with System.out.print(newData); (not sure about the syntax, since I dont know Java) if you want to print the actual data received and not just the number of bytes received.


text:
VC0706 card failed, or not present
I'm trying to follow this tutorial here:
https://learn.adafruit.com/ttl-serial-camera/using-the-camera
Here's what my serial log is printing-- I've added a few commands for logging:
Arduino version is: 10605
Chip Select is: 4
VC0706 Camera snapshot test
Card failed, or not present

I know my SD card works because when I use this program: https://www.arduino.cc/en/Tutorial/ReadWrite
it works just fine. What am I messing up?
I'm using an arduino uno with wifi shield.
Thanks!

Comparing and contrasting with the SD card file -- I've found that if you comment out the following -- it works. Maybe this will help someone.
//#if !defined(SOFTWARE_SPI)
//#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//  if(chipSelect != 53) pinMode(53, OUTPUT); // SS on Mega
//#else
//  if(chipSelect != 10) pinMode(10, OUTPUT); // SS on Uno, etc.
//#endif
//#endif


text:
Driving multiple LED arrays with shift registers
The project I'm building requires multiple LED arrays. I'm going to wire these LEDs in parallel and then connect the arrays to individual pins on a shift register. In addition to the LEDs running in parallel I've connected resistors in series to each LED. I've been prototyping this on a couple of breadboards and I've noticed my parallel LEDs are much more dim then my LEDs I have in series. The resistors I'm using are around 550 OHMs and I'm powering the registers through my arduino uno. I think this may be part of the reason why they're so dim, as the arduino is only providing 5V. My question is, can I/should I have my registers connected to my arduino via the data connections and power them using an external source? Will this provide me with brighter LEDs? I don't want to dump the resistors, and I have around 21 arrays, if it matters, each with a varying number of LEDs

To more clearly and definitely present your circuits, please include  schematic circuit diagrams.  Numerous free circuit diagram maker programs are available.

What shift registers are you using? How many LEDs are you running in parallel per pin?

What shift register? Multiple LEDs in parallel will share the output of an output pin, so to get 20 mA per LED with 5 in parallel would require 100 mA from the output pin.

You haven't provided enough information to allow definitive answers to your questions, but you can apply LED resistor calculators and formulas to determine how much current is available to drive LEDs of various voltages.
Here is an example:  Suppose you hook up a red LED that drops about 1.6 V when it's on and operating at a current of 5 to 25 mA.  Suppose the LED is in series with a 550 Ω resistor, between a 5 V source and ground.  Current will be about (5-1.6)/550 A ≈ 0.0062 A = 6.2 mA.
If you wished to limit current through Arduino Uno pins to safe-area amounts like 25 mA, you could drive at most 4 such LEDs per output pin.  If you decrease the resistor to get more current, the number of LEDs allowed per pin decreases too.
Because pin voltage drops slightly as the pin drives more current, LED brightnesses will also decrease slightly as more LEDs are attached to a pin, so putting different numbers of LEDs on different pins is likely to make light levels uneven.
Limits on output currents from 74HC595 shift register pins are similar to those on Arduino Uno pins; eg 35 mA absolute max ratings for the Qn pins.
Rather than driving LEDs directly from Uno pins or '595 pins, you can use transistor driver stages.  Most transistor drivers will allow higher voltages (ie more LEDs in series, rather than in parallel) and higher currents.  Also consider using LED driver chips; many of them contain PWM circuitry for brightness control and registers for storing drive levels.


text:
How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?
How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.

avrdude: usbdev_open(): did not find any USB device "usb"

I've already added myself to the dialout group,

sudo usermod -aG dialout $USER

And, I did that after I confirmed the dialout group owns the device (in my case /dev/ttyACM0:
$ ls /dev/ttyACM0 -l
crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]

Try "Tools> Port:> then select your board"
Make sure your pc hasn't assigned new com port to the attached usb (Arduino)


text:
How to read 6 RC remote channels using Attachinterupt for every channel
How can i use the attach interupt command and read rc channels in background. I am in doubt that attach interupt is only applied to 2 pins just and cant be used to get data from other pins.

Please spell out what you mean by "rc channel"; eg add a link to a specification for rc channels.  Note, the Uno has plenty of pin-change-interrupt pins, which can be used (eg) for software-serial i/o [with one software-serial channel active at once, in typical software-serial implementation]

I mean external interupts,(radio control channels).

You can use PCINTs. The only downside is that they all share one single interrupt routine (ISR).

Bilal, please edit the question and spell out what you mean by "radio control channel".  Is it an input? An output? Are you talking about controlling RC servos?  Edit the question and add a link to an actual specification.

I already tell you what you should investigate in your other question on the same topic. If you'd read the entire answer there you would know the answer to this question already.

I am not sure what you are asking but you can have as many interrupt sources on a single interrupt pin as you want.  When the interrupt happens in your ISR (Interrupt Service Routine) you simply check each one and process the ones that are valid.  Be sure to do one final check before exiting as another could happen while servicing the first one.
Gil


text:
How to cast float into four bytes?
I'm trying to save GPS coordinates to an EEPROM.
In this example I feed it the latitude of 56060066 as the argument float x
void writeFloat(unsigned int addr, float x)
{
  byte seriesOfBytes[3];
  *((float *)seriesOfBytes) = x;
  // Write all four bytes.
  for(int i = 0; i < 4; i++)
  {
    i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
    Serial.println(seriesOfBytes[i],BIN);  // Debug line
  }
}

I'm expecting to receive the following four bytes from the serial print:
00000011
01010111
01101000
10100010

Instead I'm getting these:
00101000
11011010
01010101
01001100

I've tried changing all sorts of parameters, but can't seem to find the problem. Can anyone spot the issue?

If you were to enable the display of warnings you would most likely see it complain about "dereferencing type-punned pointer will break strict-aliasing rules" which is what you are doing here.
Basically you are trying to cast an array of four 8-bit values which can have any alignment they like (byte alignment) to a 32-bit float value which needs 4-byte alignment.  And the two just don't mesh.
Instead you need to work the other way around - cast a type that has smaller alignment requirements over the type that has larger requirements.
So instead of getting 4 bytes and trying to fill them as a float you get a float and read it as 4 bytes:
byte *b = (byte *)&floatVal;

Then you can access b[0] to b[3] quite happily.
Another way to do it is with a union:
union {
    float fval;
    byte bval[4];
} floatAsBytes;

floatAsBytes.fval = floatVal;
EEPROM.write(0, floatAsBytes.bval[0]);
EEPROM.write(1, floatAsBytes.bval[1]);
EEPROM.write(2, floatAsBytes.bval[2]);
EEPROM.write(3, floatAsBytes.bval[3]);

Also, in your code, you only allocated enough room for 3 bytes, not 4...

Thanks. I just tried the union you suggested, but it's showing the same result! Compiler is not showing any warnings. Would you expect the serial print with BIN parameter to show the correct result?

@blarg Have you considered that maybe you are expecting the wrong values? Where did you get those values from?

You are getting exactly what you said you want. 4 bytes representing the number in float format.
What you are expecting to get, is 4 bytes representing the number in big-endian integer format.
Using Majenkos solution for casting, you need to change the types and reverse the for loop for big-endinaness.
I also used int32_t because the size of the int is 16-bit (2-byte) on the Arduino Uno (and other ATMega based boards) and on the Arduino Due it's 32-bit (4-byte). Its better to define the exact int in this case.
union {
    int32_t ival;
    byte bval[4];
} int32AsBytes;

void writeInt32(unsigned int addr, int32_t x)
{
    int32AsBytes.ival = x;
    for(int i = 3; i >= 0; i--) // reverse for big-endian
    {
        i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM
        Serial.println(int32AsBytes.bval[i], BIN);  // Debug line
    }
}

This mucking around with casts and arrays is far too complex.
See: Reading and Writing Data Structures to EEPROM
The library EEPROMAnything.h will accomplish this.

EEPROMAnything.h
The library just consists of this file. Save into your "libraries" folder under the folder name EEPROMAnything.
#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

Example code
#include <EEPROM.h>
#include <EEPROMAnything.h>

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  float foo = 56060066;
  EEPROM_writeAnything (0, foo);

  float bar;
  EEPROM_readAnything (0, bar);

  Serial.println (bar);
  }  // end of setup

void loop ()
  {
  }  // end of loop

Output from above
56060064.00

Note you don't get exactly the same number back. This is because of the precision of 4-bytes floats.

After re-reading the question I see you are using I2C EEPROM. That changes the answer a bit, but you can see an adaptation of that library for I2C here. The general idea is the same though.

i2c_eeprom_write_byte(0x57, addr, myFloat.bytes[i]); // Write byte to EEPROM

Your code seems to be writing all of the bytes to the same address, I don't know how that could work.

union Float {
    float    m_float;
    uint8_t  m_bytes[sizeof(float)];
};

float        pi,pi1;
uint8_t      bytes[sizeof(float)];
uint8_t      bytes1[sizeof(float)];
Float        myFloat;

#include <Wire.h>
#define disk1 0x50    //Address of 24LC256 eeprom chip
void setup(void)
{
  unsigned int address = 0;
  Serial.begin(9600);
  Wire.begin();
  pi = 300.78;
  Serial.println("*******************************************");
  Serial.println("pi = "+ String(pi));
  Serial.println("***** Conversion by using type casting *****");
  *(float*)(bytes) = pi;
  for(int i=0;i<4;i++) Serial.println( bytes[i]);
  Serial.println("*******************************************");
  for( int i=0;i<4;i++){
      writeEEPROM(disk1, address, bytes[i]);
      address=address+sizeof(bytes[i]);
  }
   address=0;
   for( int i=0;i<4;i++){
      bytes1[i]=(readEEPROM(disk1, address));
      address++;
      Serial.println(bytes1[i]);
   }
   Serial.println("************Conver Byte to Float*************************");
 pi1 = *(float*)(bytes1);
 Serial.println("pi = "+String( pi1));
 Serial.println("********* Conversion by using union *********");
 myFloat.m_float = pi1;   // assign a float to union
 Serial.println("myFloat.m_Float = "+String( myFloat.m_float));
 Serial.println("myFloat.m_Bytes = "+String(myFloat.m_bytes[0])+String(myFloat.m_bytes[1])+String(myFloat.m_bytes[2])+String(myFloat.m_bytes[3]));  // get the bytes
}
void loop(){}
void writeEEPROM(int deviceaddress, unsigned int eeaddress, byte data )
{
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));   // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB  Wire.send(data);
  Wire.write(data);
  Wire.endTransmission();
  delay(5);
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{

Hope This could help. Just done a fews min ago. good luck

Please add a few sentences to accompany the code.  It may help those who are trying to understand it.

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


text:
How can program/arduino restarted by IDE?
I wrote my custom sketch, where I am printing some greeting text inside setup() method.
I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again.
How can this happen? I was thinking setup() method run once, when Arduino is powered up by connecting to the USB socket?
If it is possible to restart it already connected, then how this can be done?
UPDATE
Code is follows:
#include <Wire.h>
#include <Adafruit_BMP085.h>

Adafruit_BMP085 bmp;

String command;

String awaitingMessage = "Temperature and pressure sensor awaiting commands\r\nCommand \'help\' is for help";

void awaiting() {
  Serial.println(awaitingMessage);
}

void help() {
  Serial.println("Temperature and pressure sensor commands:");
  Serial.println("temp\t- output temperature in degrees Celsius");
  Serial.println("press\t- output pressure in Pascals");
  Serial.println("wait\t- print awaiting message");
  Serial.println("help\t- output this text");
}

void temperature() {
  Serial.println(bmp.readTemperature());
}

void pressure() {
  Serial.println(bmp.readPressure());
}

void unknown() {
  if( command.length() > 0 ) {
      Serial.println("Unknown command was \'" + command + "'");
    }
}

void setup() {
   Serial.setTimeout(50000);
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
  else {
    awaiting();
  }
}

void loop() {
  command = Serial.readStringUntil('\n');

  if( command.startsWith("temp") ) {
    temperature();
  }

  else if( command.startsWith("press") ) {
    pressure();
  }

  else if( command.startsWith("wait") ) {
    awaiting();
  }

  else if( command.startsWith("help") ) {
    help();
  }

  else {
    unknown();
    //awaiting();
  }

}

Video is here: https://youtu.be/-QBleGVxaus

When you open the serial monitor (or even just go to the serial port menu) the serial port is opened. When the serial port is opened the DTR line is asserted.  This is the method that the Arduino uses to reset so that you can access the bootloader and upload a new sketch.
Every time you open the serial port - through whatever means you choose - you reset the board, whether you like it or not.
There are a number of "fixes" for this - the simplest is to add a large (say 10µF) capacitor between the RESET and GND pins of the Arduino to filter out the reset pulse that would otherwise reboot the board.
There are also ways of disabling the reset within Windows, but that requires you to write your own software to interface with the board instead of using the serial monitor.
Some boards also come with a method of completely detaching the reset signal from the USB interface, but modifying the board itself isn't for beginners.
Just remember that once you have disabled reset through whatever means you will have to re-enable it (resolder the track you cut, remove the capacitor, whatever) before you can upload a new sketch.

So, how to use this for good? How to restart Arduino by means of /dev/ttyUSB0 device?

Note, that my Arduino is connected by USB, I don't believe there are some DTR line activating when I "open" the port. Also I don't understand, what is "opening" at all

The DTR line is generated by the USB interface chip form the USB protocol's line state data.  You can disable reset on Linux with stty -F /dev/ttyUSB0 -hupcl and re-enable it again with stty -F /dev/ttyUSB0 hupcl

I like the reset feature. How to use it for good? Suppose I did /dev/ttyUSB0 hupcl. Now how can I restart arduino?

You just need to open the port.  The simplest way from the command line is echo >/dev/ttyUSB0

If I just read /dev/ttryUSB0 with read or tail command, will this open the port also? Can I conserve power this way? May I start Arduino only once port readen and then shut it down again? I would like to read temperature each 5 min or similar, can I start arduino once per 5 minute then?

Yes, reading also opens the port. Any action on the /dev/ttyUSB0 device opens the port - even the stty command used to disable or enable resets.  You can't really use it to conserve power unless you put the chip into sleep mode after you have finished what you are doing when a reset would then start your sketch from the start again.  It may be usable like that, or not, depending on what you want to achieve.  You would always run once regardless, and then sleep until you next open the port.

This means your Arduino or ATmega328 is restarting due to another issue. Usually the Arduino will reboot when there is too much amperage draw which is called a brown-out.
It can also mean there is a bug in your code.
Please also note as you mentioned

I found, that each time I am restarting IDE, and opening serial monitor, a greeting text is printed there again, i.e. setup() method running again

The Arduino will reboot when opening the serial monitor.

How can restart happen exactly when I run IDE? How can "other reasons" know that I am restarting an IDE?

Can you post your code?

See my update please

See my edit to my answer


text:
Servos and ultrasonic at the same time
So recently I started making a sonar out of ultrasonic HC-SR04 sensor and servo motor. The idea was to slowly rotate servo 180 degrees while measuring distance.
Soon after I noticed that regular pulseIn() command could wait 20ms while doing nothing. So I started learning interrupts. I came up with a code which sends TRIG signal and records sending time with micros() function. When an interrupt occurs on ECHO pin, we subtract current time with TRIG time and get time of round trip of the sound.
The code works as intended without servos connected, but it behaves interestingly ! I always get distance which is 8 cm bigger than actual distance. So I had to subtract 8 cm every time ! Also I noticed that max reliable range decreased , using pulseIn() I could measure distance of 400cm, and with mine code it starts to show weird numbers after 150cm...
So i thought that 150cm is enough for me, and tried to run the code with servos attached. everything ran as intended, until the servos started to move. Now I was getting distance along with pretty much random numbers, periodically positive and negative.
I could just use one the fancy libraries out there, but I am curious what am I doing wrong, why i need to subtract 8cm each time , why my reliable range decreased so much, and most importantly why am I getting weird values while servos are on ?
CODE :
#include <Servo.h>

#define ECHO 2
#define TRIG 7

 Servo servo;
 int distance;
 volatile long echoTime = 0;
 long trigTime = 0,sendTime = 0,timeServo = 0;
 bool scanning = false;
 byte servoDir = -1,servoAngle = 0;

void setup()
{
  servo.attach(12);
  Serial.begin(115200);
  pinMode(ECHO,INPUT);
  pinMode(TRIG,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(ECHO), echo_interupt, FALLING);

}
void loop()
{
  // SERVO

   if((millis() - timeServo > 10)){
     if(servoAngle <= 0 || servoAngle >= 180)servoDir = -servoDir;
     servoAngle += servoDir;
     servo.write(servoAngle);
     timeServo = millis();
   }

  // GETTING RESULTS
  if(echoTime > 0){
    distance = echoTime - trigTime;
    distance /= 58;
    echoTime = 0;
    trigTime = 0;
    Serial.println(distance - 8);
  }
  // SENDING PULSE
  if(millis() - sendTime > 20){
  digitalWrite(TRIG,LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG,HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG,LOW);
  trigTime = micros();
  sendTime = millis();
  }
}

 // INTERUPT
void echo_interupt(){
  echoTime = micros();
}

8cm is 233µs of sound travel time.  There and back again would be 466µs.  466µs, at 16MHz, is around 7400 instructions.
When an interrupt is triggered you don't get an instant response.  First the built in interrupt function is called. That then looks to see if you have registered an interrupt function.  It then calls that interrupt function.
All that takes time, and when you're working with microseconds it makes a big difference.
And then you have to go and get the current micros() value, which again takes time to do.
So it all adds up to a delay.  Not ideal.
For greater accuracy you should investigate using input capture which will start a timer running when you send the trigger and the timer will automatically stop the nanosecond the echo is received.  From that you can calculate a much more precise distance.
As for why you are getting strange results with the servos on?  Most likely because you are moving the receiving head while the pulse is being received.  I made a similar system while playing once and found that the best results were achieved by moving the head to the desired position, waiting a moment for any vibration to settle, do the ping and get the result, then move the head to the next position.
Oh, and by the way, the HC-SR04 is (from memory) only really rated for up to 2m - I have never achieved anything more than around 1.8m with any accuracy.

Great, now I can work on time calculation. Regarding strange results, ultrasonic head wasn't mounted on servo at all, it was in different place and standing still, only connected to the same Arduino board. I'll work on time calculation , perhaps it could solve the problem.

@boofati: You could bypass the arduino library and declare your real isr. Here's a short tutorial: http://www.avr-tutorials.com/interrupts/avr-external-interrupt-c-programming

@Majenko: the downside of input capture is that it uses an IP block, so it doesn't scale easily - unless you consider adding more AVRs as scaling :-)

@IgorStoppa Or switching to a real microcontroller instead ;)

@Majenko: then where is the fun? Yes, any Cortex M-something could do it much better, but really, then there is no more challenge :-)

@IgorStoppa You want challenge?  Then break into a navy base and nick the sonar systems from a submarine in dry dock ;)

Apparently someone has been playing MGS too much :-D

@Majenko - the Arduinos I have here are real. :P

I had problems with Servo library and VirtualWire. They both use the same internal timer. The solution was to change Servo.h to ServoTimer2.h lib.


text:
Can i run brushless ESC from any digital pin of arduino
{assume arming is done}
Can i connect the brushless ESC to any digital pin and give writemicroseconds() to it? Will this work. because i have connected my 4 ESC's to "~" pins. so i thinks that other will not work.

It should work.
The Servo library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.

Yes, RC servos can be attached to non-PWM pins, but  a “brushless ESC” is not an RC servo but instead  a PWM-controlled Electronic Speed Control for brushless DC motors.


text:
How to connect Arduino device to Linux?
I wrote Arduino sketch and it works. It waits for a command and answers text on response.

Simultaneously, I can't get any response with command line tools.
For example, I have the following code to get temperature:
#!/bin/bash
tty=/dev/ttyUSB0
exec 4<$tty 5>$tty
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
#stty -F $tty 9600 -echo
#printf "temp\n" >&5
echo temp >&5
read reply <&4
echo "$reply"
#tail -n 1 - <&4

It returns empty or hang under different circumstances.
Also, if I run built-in Serial Monitor, I can see responses on command lines like:
echo temp > /dev/ttyUSB0

But I see nothing with commands like tail -f /dev/ttyUSB0
What I am doing wrong?

I really want to say using Linux is where you going wrong, but that would be childish. :)  I'm not sure if I read it right, but are you trying to connect two apps to the same console port?  I wouldn't expect that to work, but I only use Windows, does that work on Linux?

Add the flag -hupcl to your stty command.  That will disable the assertion of DTR which is resetting the board.
 hupcl (-hupcl)
             Stop asserting modem control (do not stop asserting modem
             control) on last close.

The first time it is run there will be a reset, since setting that flag entails opening the port, which causes a reset.  So you need to add a delay long enough to get past the bootloader - minimum 2 seconds, best make it 3.
You can do that with the sleep command: sleep 3
Note that you now won't be able to upload a new sketch since you have disabled the auto-reset feature that allows you to enter the bootloader, so before uploading a new sketch you need to turn the reset back on with
stty -F $tty hupcl

If you don't disable the reset then every operation in your script that opens and then closes the serial port will trigger a reset of the board.  So in summary try this:
#!/bin/bash
tty=/dev/ttyUSB0
stty -F $tty cs8 9600 ignbrk -brkint -icrnl -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts -hupcl
sleep 3
echo temp >$tty
read reply <$tty
echo "$reply"
stty -F $tty hupcl

I was wishing to use reset feature. Why doesn't it work with it?

In that case leave the stty as it is, but just add the three second delay so it can get past the bootloader before you send your request.

I was waiting long enough with tail -f, also I was observing directly, that Serial Monitor does see the output, while tail -f does not.

You can't read the data with two things at once - only one thing will get it.  Also you have to wait before sending "temp" otherwise it just won't ever get it.

By the way, what are exact conditions for resetting? I have 3 commands in the script, touching the port: stty, echo and read. Will it reset 3 times or only one, how to know?

One more thing: every operation you perform from your shell script will trigger a new reset.  You should disable reset at the beginning (which will make it reset once) then enable it again afterwards.

As it happens I was answering that at the same time as you asked it - the same thought occurred to me ;)

Why can I see the answers with Serial Monitor? Why doesn't it reset then?

While it is open it is open - it's only when the last file descriptor is closed that it resets the board. While the serial monitor is open there will always be an active file descriptor.

Isn't it possible with shell script to keep port opened?

Not really, no.  It executes a series of distinct commands with little to no state between them.  You want to use Perl or Python or something if you want to do that kind of thing.  I can recommend Device::SerialPort in perl, and people do keep trying to use PySerial

Okay, but why doesn't read command wait until it get something? Why should I make explicit delay? Why can't I initiate reset, then wait for ANYTHING with read, then read it, then exit?

You are sending first to initiate a read from what I understand. It's that initial write (echo) that must be delayed.

PySerial is not too bad to use if one wants to transfer text. What is somewhat more problematic, as it goes against the grain of Python, is to do byte-oriented data transfer, but it's not impossible, it requires a bit of juggling.

@IgorStoppa That's why I say "try and use it" ;)  Personally I do it all in pure C...

@Majenko: it depends on the overall language you want to use in a project ... using multiple languages is not necessarily the kindest act toward who will read it later on :-)   - anyway, it's not that long/complicated: https://github.com/01org-AutomatedFlasherTester/pem/blob/master/src/mappedbuffer.py

@IgorStoppa Urgh - I feel dirty now. I need to go and scrub my eyeballs.

@Majenko you mean, that no synchronization or buffering occur? Computer does not feel that Arduino is not on and just blindly send bits, which turn lost?

@Dims The computer has no concept of what an Arduino is.  When you send data the Arduino receives it.  If the Arduino is in the bootloader, which it is for 2 seconds after reboot, then the bootloader receives the text, not your sketch.  Only once the bootloader is finished with will any text sent to the Arduino make it to your sketch.

@Majenko see my separate question on it: http://arduino.stackexchange.com/questions/16781/doesnt-arduino-reports-dsr-data-set-ready-correctly
I agree, that computer has no concept of Arduino. But computer should has concept of obeying the protocol.

@Majenko: it's portable (as in: works without recompiling) and doesn't require using also perl (no, writing everything in perl was not an option and anyway I would have not liked it)

@Dims The Arduino is ready to receive the moment the reset is performed. It's just your sketch that isn't ready to receive because the Arduino is busy doing other things first for 2 seconds before your sketch is run


text:
Concatenate string constants
Please take a look at following example (I have Java background):
const char* BT_ADDRESS = "abcd,ef,ghijkl";

void bar(const char* string) {
  ...
}

void foo() {
   bar("AT+BIND=" + BT_ADDRESS);
   bar("AT+LINK=" + BT_ADDRESS);
}

How to achieve this with "Arduino-C++" so BT_ADDRESS only has to be entered at one location?

That depends on what print does.

There is, as you may expect with C, many different ways of doing this.
The simplest is probably to use, instead of a const variable, a preprocessor macro.
In C you can concatenate string literals like this:
print("AT+BIND=" "abcd,ef,ghijkl");

Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.
Now you can, of course, replace one of those with a preprocessor macro:
#define BT_ADDRESS "abcd,ef,ghijkl"
print("AT+BIND=" BT_ADDRESS);
print("AT+LINK=" BT_ADDRESS);

The preprocessing replaces BT_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.
Other options, depending on what print does, is to expand it to take two const char * parameters and deal with them both separately.  For instance, you might have:
void print(const char *command, const char *data) {
    Serial.print(command);
    Serial.println(data);
}

print("AT+BIND=", BT_ADDRESS);

If you don't know how many parameters you may want to pass you could use variadic arguments:
#include <stdarg.h>

void print(int count, ...) {
    va_list args;
    va_start args, count);

    for (int i = 0; i < count; i++) {
        const char *arg = va_arg(args, const char *);
        Serial.print(arg);
    }
    va_end(args);
}

print(2, "AT+BIND=", BT_ADDRESS);

Yet another option is to pre-format the data into a single string using the various string operators.  For example:
int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
char temp[len + 1]; // Be sure to keep space for the terminating NULL.
strcpy(temp, "AT+BIND=");
strcat(BT_ADDRESS);
print(temp);

I could go on all night with different options...  The first one using the preprocessor is probably easiest though.

Get rid of strange print() and use standard stdout, fprintf() and % format tokens.
#include <stdio.h>
#include <Stream.h>

// printf to file support http://arduino.cc/playground/Main/Printf
// we need fundamental FILE definitions and printf declarations
// apparently it eats 1k FLASH by saves to much copy&paste and hopefully even FLASH

// create a output function
// This works because Serial.write, although of
// type virtual, already exists.
static int stream_putchar (char c, FILE *stream) {
    ((Stream*)(stream->udata))->write(c);
    return 0;
}

void SetupFileStream(FILE* file, Print* stream) {
    fdev_setup_stream(file, stream_putchar, NULL, _FDEV_SETUP_WRITE);
    file->udata = stream;
}

#ifdef UDRE0
// non interrupt transmit function
static int uart_putchar (char c, FILE *stream) {
    volatile byte *ucsrna = (byte*)(stream->udata);
    while ( !bitRead( ucsrna[0], UDRE0) ) {;}  // wait for transmit buffer is empty
    ucsrna[&UDR0-&UCSR0A] = c;
    return 0;
}

void SetupUartStream(FILE* file, volatile byte *ucsrna) {
    fdev_setup_stream(file, uart_putchar, NULL, _FDEV_SETUP_WRITE);
    file->udata = (void*) ucsrna;
}
#endif

#define INFO(fmt, args...) \
    fprintf_P(stderr, PROGSTR("INFO: " fmt), ## args);

// create a FILE structure to reference our UART output function in main project file
static FILE myStdOut = {0};
void setup() {
....
    Serial.begin(19200);
    SetupUartStream(&myStdOut, &UCSR0A);   // when debugging in AvrStudio then debugger is saturated by debug messages in user data empty interrupt handler if used buffered stream output
    // The uart is the standard output device STDOUT
    stdout = &myStdOut;
    stderr = stdout;
...
}

....
const char* BT_ADDRESS_RAM = "abcd,ef,ghijkl";
const char* PROGMEM BT_ADDRESS_FLASH = "abcd,ef,ghijkl";

INFO("AT+BIND=%s", BT_ADDRESS_RAM);
INFO("AT+BIND=%S", BT_ADDRESS_FLASH);

print was just an example name of a method.

If print() is just example and you need concatenated string (not streamed output) then you can use standard sprintf(), strcat() or so. Because you have initialized variable const char* you must do in runtime, bar("AT+LINK=" + BT_ADDRESS) is attempt to do it in compilation time.

Concatenating at compilation time (where possible) is what I need.

Then you can use:
#define BT_ADDRESS "abcd,ef,ghijkl"
bar("AT+BIND" BT_ADDRESS);
But you should clarify what means entered at one location, because it can mean to avoid copy pasting or to save FLASH memory avoiding duplicate strings there.


text:
Doesn't Arduino reports DSR (Data Set Ready) correctly?
I was told, that when computer opens port, it sends DTR (Data Terminal Ready) signal to Arduino, which initiates Arduino reboot.
This looks like part of DTR / DSR flow control. According to this, in response to DTR, Arduino should no only reboot, but also raise DSR (Data Set Ready) signal when it is ready to receive data
And computer should wait for it.
Does it happen so?

No, this doesn't happen.
DTR is used purely for resetting the board.  Personally I would have chosen the RTS signal instead, but the wise guys at Arduino decided on DTR.
The Arduino has no knowledge of the DTR signal, it only knows that it has been rebooted.  Whether that reboot came from DTR, or from the reset button, or wherever, it has no knowledge.
So the DTR is being (in my opinion ab-) used to perform the resetting in order to make uploading a sketch easier and that is all.

If you have no control over the other device and don't want your arduino to reset you can check the 328P datasheet: "The External Reset can be disabled by the RSTDISBL fuse, see Table 28-7 on page 282."

Also, there is a possiblity to have knowledge of what has resetted your Arduino. It does go a bit further than Arduino only and involves reading the register: "11.9.1 MCUSR – MCU Status Register
The MCU Status Register provides information on which reset source caused an MCU reset."

@FuaZe That will only tell you that something lowered the reset pin - it can't know what that something is, and there's more than one thing on an Arduino that can lower that reset pin.

No, it does not, and can not for the simple reason that there is no DSR line connected to the processor.
Generally host software / serial driver configuration ignores DSR.
On the boards with an 8u2/16u2 the custom firmware therein can report whatever virtual state of the signal it is programmed to. On those with hardware USB-serial they will report however the pin is hard wired, or whatever value it is pulled to or floating at.
None of these (possibly excepting a Leonardo type board or an ARM one with native USB) reflect anything about the state of the target processor, so software hoping to talk to an Arduino should ignore the DSR signal.


text:
How to apply a programme to all values in a list simultaneously
I'm attempting to turn on a set of LED's one at a time and then switch them all off at the same time, I am stuck however on turning them off at the same time.
That is my code:
int ledpins[] = {2,3,4,5,6,7,8,9}; //creates a list of the pins in use

void setup() {
  for (int i = 0; i < 8; i++){
    pinMode(ledpins[i], OUTPUT);  // iterates over the list led pins from the 0 pin to the pins before the eigth
  }
}

void loop() {
  for (int i = 0; i < 8; i++){
    digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  }

  delay(100); //when all on will wait 100 ms
  digitalWrite(ledpins[0,7], LOW); //turns off all the leds at once
  delay(100);
}

The annotations are for my own understanding.
I just need help turning all the LED's off at once which I dont know the command for.

You have already done it twice, why are you struggling the third time?
for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
}

// turns all the pins of one at a time

Except that it is happening so fast you can't see then doing it individually. So just do the same but set them to LOW:
for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], LOW); // turns all the pins off one at a time
}

Now you might want to add a delay into the loop that turns them on so you can see them turn on individually instead of all at once:
for (int i = 0; i < 8; i++){
  digitalWrite(ledpins[i], HIGH); // turns all the pins of one at a time
  delay(50);
}

There is another approach that is to use direct port manipulation. It is a lot faster than using digitalWrite in the sense that it requires less clock cycles to execute and allows you to change one port at a time (the UNO has 3 ports called D, B and C). You can find an introduction to port manipulation on this page: https://www.arduino.cc/en/Reference/PortManipulation
Here is an example that toggles the LED you chose:
void setup()
{
    DDRD |= B11111100; // Pin 2 to 7 as outputs
    DDRB |= B00000011; // Pin 8 to 9 as outputs
}

void loop()
{
    // Pin 2 to 7 HIGH
    PORTD |= ( 1<<2 ) | ( 1<<3 ) | ( 1<<4 ) | ( 1<<5 ) | ( 1<<6 ) | ( 1<<7 );
    // Pin 8 to 9 HIGH
    PORTB |= ( 1<<0 ) | ( 1<<1 );

    _delay_ms( 500 );

    // Pin 2 to 7 LOW
    PORTD &= ~( 1<<2 ) & ~( 1<<3 ) & ~( 1<<4 ) & ~( 1<<5 ) & ~( 1<<6 ) & ~( 1<<7 );
    // Pin 8 to 9 LOW
    PORTB &= ~( 1<<0 ) & ~( 1<<1 );

    _delay_ms( 500 );
}


text:
Powering multiple servos on external battery
I am working on a project with my school's 3D Printing Club where we are making a humanoid robot and I am attempting to wire the arm at the moment, and program the hands to translate text to sign language. The portion of the arm I am currently working with uses six TowerPro 5010 servos, one for each finger, and another for the wrist, and I am controlling it with an Arduino Uno. I have a 9v wall plug that I am powering the Arduino with, and a 4xAA battery pack (wired in series for 6v, last measured at 5.7) that I would like to use for the servos.
Initially, I wired the servo ground pins to the Arduino GND output, and the servo power pins to the battery pack's 6v output, I connected the ground on the battery to the ground on the Arduino, and I attached the servo motors to their IO pins. This approach worked perfectly for two servos, barely for three, and not at all for four. Even with most of the motors staying still (I was only moving one at a time with three and four servos, but I can move two simultaneously no problem with nothing else connected). Not sure how to describe the load on them quantitatively, but they are pulling on fishing line that has a good deal of resistance, but nothing excessive, or near their limits.
I have been googling around for hours, and I found some tutorials where a similar battery was powering eight servos at a time, and so I am unsure why mine was cutting out so soon.
I tried to reduce the load of the servos, but nothing I tried worked. At one point I tried wiring the servos on a shift register to only power the ones I needed, but then I realized this was a dumb idea because my shift register would never be able to output enough current to power even one servo. I have some 5v voltage regulators, but I don't think they will help since the servo takes from 4v to 6v, and I looked through all my transistors, but they are all designed for very small currents. I have a relay which should be able to switch that voltage that voltage easily, but only one of them. If possible I would like to try and do this without purchasing any additional components such as motor controllers or specialized batteries, but I understand that if I need to I need to.
If anyone has any advice on how to proceed I would greatly appreciate it. Thanks.

If you dont mind to use a bit of space for a dedicated board that controls your servo and power them, I would suggest to use http://www.adafruit.com/product/815 which is very good.
Your issue might become a power draining where the batteries cant keep up to give enough amper to use 3 or 4 servos at the same time.
I am not sure what kind of batteries you are using, probably not rechargeable ones but I would suggest to get an ampermeter to get the real draining on your circuit.
After that you will understand a bit better what is going on and why this issue is happening on your configuration.
I cant find the power consummation of this servo so I Cant give much more information.

I have a multimeter, but measuring current through a servo is difficult because it is non constant. Also I fear the autorange feature on my multimeter may be making it too slow to react to the changes. Do you have any advice on measuring this?

Also the batteries are four standard alkaline AAs wired in series.


text:
What type of sensor could I use to determine the mass of a small object (under 1 kg)?
I'm building a robot that needs to pick up a piece of material and then determine its mass. My robot will retrieve the material using a scoop at the ended of a mechanized arm. Once the material is in the scoop, the arm will tilt upwards until the material slides down the arm and into the chassis.
I hope to weigh the material while its in the chassis, but I'm not sure how to do this. I've found that load sensors are useful for taking masses, but I'm not clear on how they're implemented. For example, I've found load beam cells, but how would I implement one in my design? Does it require a metal plate of some sort (like a weighing pan) on top of it like a laboratory scale? The sensor must be able to communicate with an Arduino.
My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!

The problem is that there are cheap kitchen scales with obscure electrical output decoded and compensated in specialized circuitry you would need to re-engineer from scratch and then there are expensive load cells and sensors with documented output.  An intermediate might be a USB postage scale, at some price premium and probably suggesting something more than an Arduino to host it.

Just a little brainstorming:
If you have a spring, then you can easily calculate the physical force (mass) needed to stretch the spring to a certain extent. The law is called:
 Hookes's Law
 - you could then just measure the increase in distance between the initial position and the position with load. Use a servo or any distance measure.

I wouldn't really use a servo as a distance measure?
You could use any distance sensor below it or a potentiometer that will turn based on the position of your weighing pan.

Servo for the angle though. I was thinking faster, than I typed. But yes a potentiometer does the trick as well.

I like the distance sensor and potentiometer ideas. Could you please elaborate on the pontentiometer idea? How would I rig one up to turn based on the position of the weighing pan?

it depends on how your weighting pan is linked to the robot. if you have a schematic drawing, I could wrap my mind round it.

A load beam cell would be good.  Put it as one leg of your robot, and calibrate it with the arm in a particular location dangling over the cell.   You'd need the beam load cell, and an instrumentation op amp, or HX711 (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide) to do the interfacing.
Also good would be the cells from a bathroom scale as the four feet -- you could hook them up like https://electronics.stackexchange.com/a/199907/30711 or https://electronics.stackexchange.com/a/199470/30711
One thing cool about using the robot feet for measurement is that you could calibrate for more sensitive measurements while reaching far from the base, and rougher measurements closer.  You could also calculate how far you could reach without toppling over.


text:
NeoPixel Ring Usage Without Arduino
I am looking at purchasing a NeoPixel Ring for a project, but need it to work without an Arduino. Once the NeoPixel has been programmed by the Arduino, will it function when powered without the Arduino? I am not looking at changing colors or anything, I want to set the LEDs to solid red and not change.
I have found in the Adafruit website that it says "NeoPixels don’t just light up on their own; they require a microcontroller (such as Arduino) and some programming." But is this only to get them working initially, or do they require an microcontroller permanently?

No, the settings for the colors are stored in RAM on the individual devices so they need to be reprogrammed every time they are powered on.
On the other hand, it is possible to use a much smaller device such as a surface-mount ATtiny85 to program them, and light_ws2812 runs on said device just fine. And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power.

"And once they have been programmed it is possible to put the MCU in deep sleep so that it consumes almost no power." -- Why bother when the MCU running flat out consumes about 0.0001% the power of the average ws2812 chain?

I recently completed a project using one of these LED rings. I knew these were normally used with an arduino for control, but at the time I was still testing things, so I decided to buy one and mess with it.
I soldered a standard 3-pin ARGB cable to the 5v, GRN, and Data In to the ring and connected it to one of the argb headers on my PC. The results were as follows:

The ring did light up and stayed illuminated with the PC.

The ARGB header was connected to a splitter which came from a ASUS motherboard header.

Armoury Crate (ASUS’s argb software) was already set up on my computer and this software was what was sending signal to the ring via a splitter.

There were SOME LEDs on the ring that behaved as expected based on the colors and pattern set up in Armoury Crate. However, some LEDs although we’re illuminated, we’re flashing various colors that didn’t match to how it was set up in Armoury Crate.

Take aways:
These NeoPixel rings DO work without an arduino in terms in terms of receiving voltage and lighting up. However, because of how these are programmed they may not behave as expected or intended if connected to a non-arduino controller.
For my application, the multi-color pattern ended up looking nice, so I decided to keep it as is.


text:
BH1750 Light sensor always giving output as 54612lx
urgently need some inputs,
Connection:
VCC-5v
GND-GND
SCL-SCL(analog pin 5)
SDA-SDA(analog pin 4)
ADD-NC or GND

Code pasted below
used library from GIT : https://github.com/claws/BH1750
#include <BH1750.h>
#include <Wire.h>

BH1750 lightMeter;

void setup(){
    Serial.begin(9600);
    lightMeter.begin();
    Serial.println("Running...");
}

void loop() {
    uint16_t lux = lightMeter.readLightLevel();
    Serial.print("Light: ");
    Serial.print(lux);
    Serial.println(" lx");
    delay(1000);
}

What happens if you disconnect the module? Do you still get 54612lx?

lux/2? check the default configuration (lightMeter.begin(???)).

use this lib = https://github.com/Erriez/ErriezBH1750
its very good to use

There may be a regulator and logic shifter on the board you are using but according to the data sheet the device is a 3V device with 1.8V logic and I2C levels.  So this is the first thing you need to check.
Have you got 4.7K resistors pulling the SDA and SCL lines to Vcc?
Can you change your code to turn the device off and then take a reading?
There is nothing wrong with your code, your wiring looks OK, so that implies that there is something wrong with the device or the Arduino.  Change the device (and code) for another I2C device and see if that works fine.  If it does then it looks like there might be a problem with the BH1750.
Hope that helps.

Looking at the BH1750.cpp and BH1750.h and I think i've noticed some errors:

Change #include "Wire.h" to #include <Wire.h> in the header file, trivial perhaps but still...
In the method BH1750::readLightLevel in the .cpp, comment out Wire.beginTransmission(BH1750_I2CADDR); and Wire.endTransmission();; they aren't needed for a Read and may be responsible for the wrong value you're getting.
You can also try replacing _delay_ms(10); with delay(10), just in case
You may also try commenting out level = level/1.2; just to see if this division has any adverse effects.

Save the files after making the changes.

I had to connect my SCL and SDA pins to dedicated 20th and 21st pins on Arduino MEGA 2560.

Please check that the OP is using an Arduino UNO as tagged on the question.

I bought some "GY-302" modules on ebay, it's a breakout board with the BH1750 sensor on it. I tried one of them and it didn't respond at all, like you I saw 54612 (which is just 65535/1.2). I tried another of these modules and it worked. So, on the one that didn't work, the sensor chip was not well aligned and centered, and the soldering looked ugly on one side, so I used my soldering iron to attempt to reflow and re-align/center it. If you attempt to do that too, clean your soldering tip and do not add any solder! Now the soldering looks even uglier (under microscope..), but the sensor is working well! I don't have any pro equipment, not even a small tip for my crappy soldering iron, so I guess I am lucky that it worked.

i didnt solder my light sensor and it had the same error, as it was just resting on the pins, try pushing it up so the sensor makes contacts with the male headers or just solder them :D


text:
Pro Micro and LilyPad USB
Is there a difference between Pro Micro 8MHz 3.3V and LilyPad USB bootloaders?
Both are based on 32U4 running at 8 MHz.

I'm curious as to what issues you're having with them exactly...

I am not sure which one to pick for my application.

Pick whichever one has the form factor that is most appropriate, then replace the firmware with any you like.

Thank you. I learned form Sparkfun that they modified these bootloaders reset. Their document which explains this change is available from this link: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/32U4Note.pdf Where can I get a version of these bootloaders without these changes.  Thanks

http://arduino.stackexchange.com/questions/16731/how-to-change-the-usb-name-of-atmel-32u4/16736#16736


text:
Arduino with seven segment
Can anyone help me regarding the output of this program?
What is the function of Num_Write?
Here is the code below:
int num_array[10][7] = { { 1,1,1,1,1,1,0 }, // 0
{ 0,1,1,0,0,0,0 }, // 1
{ 1,1,0,1,1,0,1 }, // 2
{ 1,1,1,1,0,0,1 }, // 3
{ 0,1,1,0,0,1,1 }, // 4
{ 1,0,1,1,0,1,1 }, // 5
{ 1,0,1,1,1,1,1 }, // 6
{ 1,1,1,0,0,0,0 }, // 7
{ 1,1,1,1,1,1,1 }, // 8
{ 1,1,1,0,0,1,1 }}; // 9

void Num_Write(int);

void setup() {
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
}

void loop() {
  for (int counter = 10; counter > 0; --counter) {
    delay(1000);
    Num_Write(counter-1);
  }
  delay(3000);
}

void Num_Write(int number) {
  int pin= 2;
  for (int j=0; j < 7; j++) {
    digitalWrite(pin, num_array[number][j]);
    pin++;
  }
}

The 2 dimensional array is holding the HIGH and LOW signal for each number to display in 7-segment. function "loop" is running through the first dimension to get the number from array, the function "Num_Write" actually is then setting the display segments from the second dimansion of the array. So all is just to display numbers 0 - 9 in a 7-segment display element

Urgh - obviously written by someone that really doesn't have a clue...  140 bytes of RAM to store what could be in 10 bytes of flash...

@FuaZe Const binary patterns is exactly what I use for this kind of thing.

Num_Write will map the output pins to display a number on the 7-segment display.
Please note that the schematic below is not the best, nor the proper way to connect a 7 segment display. It's intended to show the connection for illustrating purposes, not for actual wiring. Each segment lead should have it's own resistor. Also, depending on if you have a Common Anode or Common Cathode 7 segment, wiring will differ.

When the number 0 is being displayed (check in the num_array) all segments are lit, except for the last segment (segment G).
void Num_Write(int number) {                 //Write a number to the 7-segment display.
  int pin= 2;                                //Take the starting (output) pin.
  for (int j=0; j < 7; j++) {                //Loop through all the segments of the given number.
    digitalWrite(pin, num_array[number][j]); //Write the output pin according to the pattern in the "num_array" for the given number.
    pin++;                                   //Go to the next pin.
  }
}

So by looping through the pins, and looping through the array (while setting the pins) we can display a number on the 7 segment display.
Extra:
The output will be somewhat like this, but then reversed (9 to 0) and withouth the A, B, C, D, E and F.

I know you probably didn't draw the schematic there, but you want to watch that resistor usage - a single resistor on the COM pin is very bad - you should mention that in your answer, or find a better schematic.

@Majenko, it does work though? ;D
But yeah, I should add that indeed. It could draw too much power when you light up all segments at the same time? Or basically have different light intensities if you have more or less segments on.

The latter - plus the segments may light up at different intensities. In a worst case scenario you may even get a cascade failure and destroy your LED display.  You need one resistor per segment to set the current through that individual segment.

Yup, also added that there is a difference in common anode and common cathode wiring.

Forgive my newbieness: what's a cascade failure?

@bot3663369 I didn't really know either. Though: https://en.wikipedia.org/wiki/Cascading_failure will be helpfull. I believe he means that if the resistor fails, all the segments won't light either. If you have a resistor for every segment, only the segment connected to the failing resistor won't light up. Or that if one LED fails it might make the others fail somehow.

I think single resistor configuration has its merits too. (1) The power draw will be the same as long as one or more of the segments are lit. This means less power as more segments are lit, but even with 1/7 or 1/8 of the brightness, the difference can still be very subtle depending on the selected resistor value. (2) The parts count is significantly less as the number of digits increase. For example, a 4 digit will require 4 resistors instead of 28/32 resistors. (3) As for the cascading failure: the resistor has to be replaced regardless of how many segments has failed.