text:
Not sure if my Arduino Uno is damaged
When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:
avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

when I go to Tools > ports I can't find the USB port.
The Arduino still working and green ligh is on, so what is the problem exactly?

Does the Uno show up under  -> "About this Mac" -> "More info" -> "System Report"->"Hardware"->"USB"?

You should really search on Arduino Inappropriate ioctl possibly with mac that would give you some results worth reading.
http://arduino.stackexchange.com/questions/13299/inappropriate-ioctl-for-device or https://forum.arduino.cc/index.php?topic=292284.0 and  http://askubuntu.com/questions/646254/arduino-serial-port-com1-problem are all people with the same error message. Try what worked for them.

Probably never mind, since the Arduino isn't even recognized by the PC, try to fix that first. If you try another Arduino, you would be able to tell if the problem is on the PC or on the Arduino.

Actually, you might still want to check out those links. Try running your IDE as administrator (or what it is at mac).

Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.
Try rebooting your Mac.
If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.

I have tried with 2 Mac laptops, same thing happened. an electronics guy told me that the IC is burnt, is this right?

I would check that you have the correct driver before i would make that assumtion.

@AfnanHumdan and I would check it again, because the "the IC is burnt" is the common way to say "I don't have the time to look at it, so just change it". Moreover you didn't say if the board ever worked. Then try using another pc (not a mac) just to double check. If it doesn't work, maybe flashing again the firmware on the atmega16u2 (the usb-serial interface IC) can solve the problem..

The Arduino only requests 100mA from the USB port. If you draw more than that it may decide to cut you off. 100mA is somewhat conservative (they could have set it to ask for 500mA) but it does allow it to work on an unpowered hub without the hub shutting it off - as long as you stay within that 100mA budget. Many systems ignore that limit though and provide many amps of power, but the Mac may be more sensitive.

@Majenko the Arduino request 100mah and could ask for 500 mah. I beg you to explain this. The usb 2.0 standard says a port should be able to deliver 500mah, whether the arduino draws that from the port or not is irrelevant unless exceeding 500mah where the controller might disconnect your device.

You are thinking purely electrical. USB also contains a protocol. That protocol as a portion in it whereby the device tells the host "I will require this much power". If that request exceeds what the port can provide it should be disconnected (unpowered hubs can only provide 100mA per port). If the device draws more than it has told the host it will be using then the host is at liberty to disconnect the device to protect itself.

I just read up on this, and you are correct according to the  standard. I however are using hubs, always and have no problems drawing up to close 3 A before being cut off from those, with only power pins connected.

I was also facing this type of issue. But it has resolved itself now. I go to Tool >> Select Port after Select USB modem its work fine.

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review

I can't agree this isn't an answer. It clearly spells out what to do to resolve the issue. If that doesn't solve the problem that is another issue. To whoever has been flagging this, answers are not to be flagged merely because they are wrong.

@NickGammon, the question is a Mac specific problem, where no ports are listed in IDE. how does this 'late' and 'me-to' answer answer the question? ('my' previous comment was generated by SE)

@Juraj On the Mac you get Tools -> Ports, as mentioned in the question. Bad answers don't have to be flagged for moderator attention. Just leave a comment stating why it won't work in your opinion and optionally vote it down.

@NickGammon, SE system asked me if this is a low quality late answer that should be deleted. I didn't flag it directly

Yes, but you agreed, right? You can skip answers that don't seem low quality. It's just an algorithm.

@NickGammon, yes I agreed.  the SE system added the answer to review because it is late and short and I reviewed it and I think, the answer doesn't answer the question. because if the list is empty you can select nothing. but you are the admin and you can delete the flag and let it be. there was an other late answer in the review list and it was ok. and then some answers I skipped because I was not sure


text:
Communication serial port with matlab
I am trying to communicate with a serial port trought matlab. This is my code:
delete (instrfindall)
clear all
close all
clc;

s=serial('COM4');
set(s,'BaudRate',4800);
set(s,'DataBits',8);
set(s, 'Parity','none');
set(s,'StopBits',1);
set(s, 'FlowControl','none');
set(s,'Terminator','CR');
set(s,'TimeOut',5000);

fopen(s)
%Move the probe radial
fprintf(s,'%s','RADIAL=100');

out=fgets(s);

fclose (s)
delete (s)
clear (s)

But i cannot make the serial port to answer me.
Can you help me? Is this code right?
Best regards,

The baud rate seems a bit low. Have you tried higher rates, ex: 38400?

source: Stack Exchange

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

sort: votes


text:
Arduino sketch won't run until I open up GUI in processing
I am trying to make a human detection robot using D6T omron thermal sensor. However, I am facing some problem here. My Arduino Uno didn't run the sketches until I open up my GUI in processing. The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board. The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.
I am trying to move my robot away from my PC. Therefore, it is a must for me to provide my board an external power supply but it just does not work. I am confused here. Fyi, it will be interfacing with my PC thru Xbee in the near future.
Ps: this is my final year project. Your effort will be much appreciated and credits will goes to you. Thanks guys!
Attached below is my code (Arduino sketch):
#define E_right 10
#define E_left 11

int RightMotorForward = 9; // Pin 10 has Left Motor connected on Arduino boards.
int RightMotorReverse = 8; // Pin 9 has Left Motor connected on Arduino boards.

int LeftMotorForward = 12; // Pin 12 has Right Motor connected on Arduino boards.
int LeftMotorReverse = 13; // Pin 13 has Right Motor connected on Arduino boards.

float top_sum, bottom_sum, left_sum, right_sum, center_row_sum;

#include <Wire.h>
#include <WireExt.h>

#define D6T_addr 0x0A
#define D6T_cmd 0x4C

int rbuf[35];
float tdata[16];
float t_PTAT;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  Serial.flush();
  pinMode(E_right, OUTPUT);
  pinMode(E_left, OUTPUT);
  pinMode(LeftMotorForward, OUTPUT);  // initialize the  pin as an output.
  pinMode(RightMotorForward, OUTPUT);  // initialize the  pin as an output.
  pinMode(LeftMotorReverse, OUTPUT);  // initialize the  pin as an output.
  pinMode(RightMotorReverse, OUTPUT);  // initialize the  pin as an output.
}
//-----------------------------------------------------------------------------

// The following Loop is to make the Robot move towards heat source.
void loop()
{
int i;

  if (Serial.available() > 0) {
    int inByte = Serial.read();
    if (inByte == 0x0001) {

      Wire.beginTransmission(D6T_addr);
      Wire.write(D6T_cmd);
      Wire.endTransmission();

      if (WireExt.beginReception(D6T_addr) >= 0) {
        i = 0;
        for (i = 0; i < 35; i++) {
          rbuf[i] = WireExt.get_byte();
        }
        WireExt.endReception();

        t_PTAT = (rbuf[0]+(rbuf[1]<<8))*0.1;
        for (i = 0; i < 16; i++) {
          tdata[i]=(rbuf[(i*2+2)]+(rbuf[(i*2+3)]<<8))*0.1;
        }

      }
    }
  }

top_sum= tdata[0] + tdata[1] + tdata[2] + tdata[3];
bottom_sum= tdata[12] + tdata[13] + tdata[14] + tdata[15];
right_sum= tdata[0]+ tdata[4] + tdata[8] + tdata[12];
left_sum= tdata[3] + tdata[7] + tdata[11] + tdata[15];
center_row_sum= tdata[1] + tdata[2] + tdata[5] + tdata[6] + tdata[9] + tdata[10] + tdata[13] + tdata[14];

if ((left_sum>center_sum)&& (center_sum>right_sum))
{
   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
   digitalWrite(LeftMotorForward, LOW);   // turn the Left Motor OFF
                  // wait for  0.5 seconds
   delay(500);
   //turn left
}

else if ((right_sum>center_sum)&&(center_sum>left_sum))
{
   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, LOW);   // turn the Right Motor OFF
   digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
   // wait for  0.5 seconds
   delay(500);
   //turn right
}
else if ((center_row_sum>right_sum)&&(center_row_sum>left_sum))
{

   analogWrite(E_right, 230);
   analogWrite(E_left, 205);

   digitalWrite(RightMotorForward, HIGH);   // turn the Right Motor ON
   digitalWrite(LeftMotorForward, HIGH);   // turn the Left Motor ON
   delay(500); //forward

}

}

Attached below is my code in processing:
import processing.serial.*;

float[] tdata = new float[17];
float tptat; // PTAT
String portName;
//int serialport = 0;

String buf;
float colourGreen; //change green in relation to temperature

int lbTemp = 25; //lowest relative temperature
int hbTemp = 35; //highest relative temperature
Serial myPort;  // Create object from Serial class

void setup() {
  size(640,640);
  //println(Serial.list());
  //portName = Serial.list()[serialport];
  myPort = new Serial(this, "COM7", 9600);
  myPort.clear();

}
void draw() {
  myPort.write(0x01);
  delay(100);
  while (myPort.available() > 0) {
    delay(300);
    buf = myPort.readString();
    myPort.clear();
    tdata = float(split(buf, ','));
    for (int i = 0; i <16; i++) {
      colourGreen = map(tdata[i],lbTemp,hbTemp,255,0);
fill (255,colourGreen,0);

      if (i == 0)
    { rect(480,0,160,160);}
      else if (i == 1)
    { rect(320,0,160,160);}
      else if (i == 2)
    { rect(160,0,160,160);}
      else if (i == 3)
    { rect(0,0,160,160);}
      else if (i == 4)
    { rect(480,160,160,160);}
      else if (i == 5)
    { rect(320,160,160,160);}
      else if (i == 6)
    { rect(160,160,160,160);}
      else if (i == 7)
    { rect(0,160,160,160);}
      else if (i == 8)
    { rect(480,320,160,160);}
      else if (i == 9)
    { rect(320,320,160,160);}
      else if (i == 10)
    { rect(160,320,160,160);}
      else if (i == 11)
    { rect(0,320,160,160);}
      else if (i == 12)
    { rect(480,480,160,160);}
      else if (i == 13)
    { rect(320,480,160,160);}
      else if (i == 14)
    { rect(160,480,160,160);}
      else
    { rect(0,480,160,160); }

    if (tdata[i]<5) {fill(255);} else {fill(0);}
      if (i ==0)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),560, 80);}
      else if (i == 1)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),400, 80);
      }
      else if (i == 2)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 80);
      }
      else if (i == 3)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]),80, 80);
      }
      else if (i == 4)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 240);
      }
      else if (i == 5)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 240);
      }
      else if (i == 6)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 240);
      }
      else if (i == 7)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 240);
      }
      else if (i == 8)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 400);
      }
      else if (i == 9)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 400);
      }
      else if (i == 10)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 400);
      }
      else if (i == 11)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 400);
      }
      else if (i == 12)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 560, 560);
      }
      else if (i == 13)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 400, 560);
      }
      else if (i == 14)
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 240, 560);
      }
      else
      {
      textAlign(CENTER, CENTER);
      textSize(20);
      text(str(tdata[i]), 80, 560);
      }
    }
    delay(800);
  }
}

My Arduino Uno didn't run the sketches until I open up my GUI in processing.

How do you know?

The tx/rx pin did not light up when I remove my USB serial cable from my PC and put in an external power supply to my arduino uno board.

That is because the TX/RX LEDs are linked to the USB interface chip. With no USB connection there can be no lights.

The tx/rx pin will only light up when I open my GUI in processing and everything works just fine.

That is because there is USB communication.
Your sketch is running fine. However your sketch looks to be wrong.  Major portions of it (i.e., the portion that does any detection at all) relies on serial data coming in.  How can you have it working, in that case, if you disconnect the serial interface so that no data ever comes in?

OHHHH! I see. Thank you so much for pointing out the mistakes. Do you hv any suggestion on how to improve my sketch? Sorry because I am new to these. Thanks a lot Majenko!

You don't appear to actually be doing anything with serial in your sketch. Just delete all references to it.

Okayyy! I will try it out and update you later. Thanks again Majenko! =D

It works! Thanks for pointing out my silly mistakes! Credits goes to you, Majenko~ Thanks!!

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


text:
Two voltage sources on the same circuit
I am looking to power a Trinket Pro 5V microcontroller using a 9V voltage source. I have logic running on this controller to gather the data from an accelerometer (powered off of the 5V pin on the controller) and output it to three strands of 21 RGB LEDs (https://www.adafruit.com/products/1655).
RGB LEDs cannot exceed a power source of 5V and after passing through the Trinket voltage regulator the 5V pin on the Trinket just does not have enough power for all three strands.
Please, advise on the appropriate hardware for this case. What is the maximum voltage that RGB LEDs can handle and how does the schematic look on the protoboard.
Thank you for your expertise.

Use a second 5V power source for the LEDs. And connect the grounds.

@Majenko, thank you, do you mean connect the microcontroller ground pin to 9V voltage source gnd pin to the 5V source gnd pin?

The MCU and 9V will already be connected. Just the 5V and MCU and/or 5V and 9V grounds need to be connected. It's exactly the same as powering a motor, or a relay, or other things from external power supplies.

First of all: 9V means that you are using a 9V "transistor" battery (like this), right?
If so it won't last very long: I suggest you to use a different approach (e.g. four AA batteries in series).
As for your question, I couldn't find the power consumption for these leds. Try to measure it yourself, setting the max brightness and white color. I think that, anyway, the max current for each LED should be 60mA (20mA for each color). This means that each strand absorbs 1.2A (quite a lot!).
This power requires you to use at least a switching regulator. I always used some small modules I found on ebay (they have a LM2596 IC, so just search LM2596 on ebay to find them). They are rated for 3A, so you should put at least two of them (1.2 * 3 strands = 3.6A > 3A).
The connections are quite straightforward: the board has four pins: IN+, IN-, OUT+ and OUT-. IN+ of all the modules go to the positive terminal of the battery, IN- and OUT- of all the modules go to the common ground node (negative terminal of trinket, battery and leds), OUT+ is the 5V regulated output. Oh, by the way, they are adjustable modules, so BEFORE ATTACHING THE LEDS use a multimeter to set the correct voltage (if you attach the leds without regulating the voltage you can destroy them).
Since you will have a lot of current left on the second module, you can power the trinket from there (so you will not waste a lot of power).
One last thought: 9V batteries usually have a capacity of around 600mAh; if you use one of them with the switching modules and drain 4A from the 5V your battery will last 0.6Ah / 4A * 9/5 = 0.27h = 16 minutes; if you switch to 4 AA batteries (around 2000mAh) it will last 2Ah / 4A * 6/5 = 0.6h = 36 minutes. More than double (calculations made rounding up the power drained by 21 leds set at max brightness and white color)

@frarigu87 could you recommend an optimal power source for the project?

@K.Nadkina It depends on 1) the leds usage, 2) the desired duration 3) the required size of the battery 4) the money you want to spend. Usually the best weight (or size) over energy ratio is with the lithium batteries (LiPo or LiIon). A 7.4V (2 cells, also called 2S) 5200mAh I found on ebay costs about 30€, is 165x60x35 mm and, at full brightness white, will last about 2 hours. The drawback is that you need an appropriate charger for these (you can also find small modules, but be sure they are for 2S batteries too). I suggest you to avoid 1S (3.7V) batteries, because you will need a step up

According to the link you supply you might either receive the WS2812 or the SK6812, datasheet on Ws2812 claims you can supply up to 7V , but this is still less than 9V , the SK6812 is lacking in max voltage but says 5v typical.
If you still want to use the 9V supply you will need a extra voltage regulator.
A little math: each pixel can max draw 60mA, if you have 21 of them we multiply and get 1260mA, thats 1.26 Amps but thats max values we might divide by two and still be relative safe. Let's not.  So we need a 1.26A source from 9V to 5V then we can calculate the power we need to dissipate. (9-5) x 1.26 = 5.04W of heat. Ok you need a regulator that can dissipate that kind of heat.
A 7805 regulator will not do,  you need a switching buck converter.
As to driving this on battery power I don't think alkaline will be able to deliver 1.3A (adding for the MCU) without loosing voltage to inner resistance, some rechargeable might. Lipo can deliver but at a different voltage that will need a new calculation of potential waste using linear regulation, or a buck regulator.  In my opinion the charging of lipos require special attention and are not my preference, but might be option here.

The question doesn't give any indication that only half the LEDs are likely to be on, or only at half power. Arbitrarily halving the current draw seems a little dangerous to me.

I second @MarkSmith; moreover as I wrote in my answer I think that they are 3 strands of 21 leds, not 21 total. Moreover, please, be precise. Currents are expressed in milliamperes (symbol: mA, not mah

@Mark Smith you are absolutely right. I'll correct my answer

@HansNeve, do you think using a 3.7V Lithium Polymer Battery @ 2000mAh would be enough and eliminate the need for a regulator? Would it power the Trinket and one LED Strand? Could another battery of that sort power the other 2 LED strands?

@K.Nadkina You could use one lipo for each strain to lessen the load yes, but be aware that there might not be cirquitry to stop theese lipos from beeing completely drained, which is a bad thing. and you will have to disconnect them to charge them.

@HansNeve Incorrect again: the LEDS should be powered at 5V, so 3.7V is out of specs. Read the provided datasheets...

@frarugi87 will using 3.7V at 2000mAh per strand not work at all? or just last less time than that of a 5V?

@K.Nadkina it will work fine.

@K.Nadkina Of course, USING A SWITCHING STEP UP CONVERTER, a 3.7V 2000mAh will last half of a 7.4V 2000mAh (using a switching step down converter). Usually I tend to prefer to lower the voltage instead of increasing it because of the less stress the components have to bear (5V 4A means 7.4V 2.7A or 3.7V 5.4A). Moreover the step up converter has a higher input ripple. And for my experience they are a bit more unstable than the step down ones. This said, a 3.7V 2000mAh at 4A will last about 20 minutes, but it will work


text:
Powering from 3V coin cell to VCC, using I/O pin as supply GND
I'm thinking of creating a "small" electronic dice.
(I will solder the button a little different though xD)

But there are some concerns on my design:
Powering from a coin-cell
It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?
Can I use a I/O as (input/supply) GND?
You can actually use outputs as positive voltage, and you can sink currents.
But does that mean I can connect the negative side of the coin-cell to an output, and sink it?
This way it should power my arduino's VCC pin through the "digital GND"
Using the reset button
I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?
(I probably won't use it though, it's placed inconveniently for this project, but I am wondering.)
A crude drawing below:
The fun thing is, polarity of the LED's/segments doesn't matter, since I can change which side is high or low? :)
Also, I've only drawn half the LED's/segments. And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.
(btw, battery GND pin should be pin 4, not pin 2)

Can I use a I/O as (input/supply) GND?

You can use an I/O pin as a supply for another (low power) device, but
you should power the Arduino itself from its Vcc and GND pins.

I could use the reset button, but would it still give me "random
  enough" numbers?

You will likely see the very same sequence every time you reset it.
There are ways around this:

You can seed the random number generator (RNG) at startup with an
analogRead() from an unconnected pin, but it's not clear how much
entropy you can expect from this.
You can save the RNG's entropy into the .noinit memory section, this
way it will not be wiped up during the program startup.

I would recommend, however, that you use a normal I/O pin to trigger the
dice, if only for one reason: the time when the user presses the button
(that you read with micros()) is a very good entropy source for
seeding the RNG.
For example, whenever the user presses the button you could:
srandom(random() ^ ((uint32_t) analogRead(0) << 22) ^ micros());

This way you combine the entropy from the button press with the entropy
from the analog pin (if any), with whatever entropy may already by in
the RNG.
Edit: More on entropy gathering.
As you seemingly already know, random() is a pseudo-random number
generator intended to produce a sequence of numbers that look random.
Unless you have some other source of randomness in your program, every
time you restart the Arduino you will get the very same sequence of
numbers. Getting true randomness (also called “entropy”) on an Arduino
is not so easy. Here are some ideas you may want to explore.
Read from an unconnected analog input
This trick seems to be pretty popular. It can even be found in the
Arduino documentation on
randomSeed():

use randomSeed() to initialize the random number generator with a
  fairly random input, such as analogRead() on an unconnected pin.

In my experience, this seems to be a very poor entropy source. I wrote a
test program that prints out the output of analogRead(0) and it seems
to cycle through the same few values in an almost predictable way.
I estimate this gives around one or two bits of entropy per call. On the
plus side, each call takes just over 100 µs.
Read from an analog noise source
There is a lot of literature on building analog noise sources. Such
sources are used inside crypto-grade random number generators, but the
circuits are likely to be more complex than you would like. There seems,
however, to be a very simple alternative. In a comment to this
post, CharlieHanson wrote:

Connecting the analogue input to the collector of a run-of-the-mill
  transistor, with the emitter grounded and base open helps to make a
  noisy input.

I have not tested this idea, but it is certainly worth exploring.
Time user input
If the user is required to press a button to throw the dice, the timing
of the button press is probably the best entropy source you can have.
With a 8 MHz clock, the micros() function has a resolution of
8 µs (64 clock cycles). Assuming the user is unable to control his
timing better than 0.1 seconds, then you have more than
13 bits of entropy per button press.
If, instead of micros(), you use timer 1 running at the full CPU
speed, then you would have 16 bits of entropy per button press. And
you would not need random() at all, as you could just output
1+TCNT1%6. That would be like throwing a dart at a carnival wheel
spinning at 80 million RPM (8 MHz / 6)!
Measure clock drift
The drift of a clock relative to another clock can be used as an
entropy
source.
The ATmega chip in your Arduino has two independent clocks: the internal
“calibrated” 8 MHz RC oscillator, and the 128 kHz oscillator
used by the watchdog timer. Both are low-accuracy clocks subject to
somewhat unpredictable drift, which is a good thing for this
application. You can gather entropy from this by configuring the
watchdog timer as a periodic interrupt source, and using timer 1 at full
speed to time the interrupt arrival times:
#include <avr/wdt.h>
#include <util/atomic.h>

// Configure Timer 1 for counting CPU cycles and the watchdog as an
// interrupt source firing (roughly) once a second. Call once in
// setup().
void configure_timers()
{
    // Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS10);  // prescaler = 1

    // Watchdog. This is a timed sequence.
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        WDTCSR = _BV(WDCE)  // enable changing the prescaler
               | _BV(WDE);  // ditto
        WDTCSR = _BV(WDIF)  // clear interrupt flag
               | _BV(WDIE)  // enable interrupts
               | WDTO_1S;   // timeout ~ 1 second
    }
}

volatile uint16_t wdt_time;
volatile bool wdt_fired;

// Watchdog interrupt service routine.
ISR(WDT_vect)
{
    wdt_time = TCNT1;
    wdt_fired = true;
}

// Add entropy to the RNG from the timing of the last WDT interrupt.
// Call periodically in loop().
void get_wdt_entropy()
{
    if (!wdt_fired) return;  // No WDT event since last time.
    uint16_t wdt_time_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        wdt_time_copy = wdt_time;
        wdt_fired = false;
    }
    srandom(random() ^ wdt_time_copy);
}

I have tested this idea by plotting the time differences between
successive interrupts. On an Arduino Uno clocked at 16 MHz, I see
short-time fluctuations with an amplitude of about 300. That should
provide around 8 bits of entropy per second.
Save the entropy pool across reboots
Once you have spent some effort to gather entropy from the environment,
it would be a pity to lose it all at power down. It is common practice
to save the entropy pool to disk when a computer shuts down, and restore
it at boot time. This avoids the problem of the RNG always starting in
the same predictable state. On the Arduino, you have no disk, but you
can use the EEPROM instead. The problem is you cannot know in advance
when the user is going to switch the device off. Then, ideally, you
would save the entropy every time the user requests a new dice value.
The new problem is that the EEPROM is only guaranteed to work reliably
for 100,000 write/erase cycles. This may not be a serious problem
(100,000 is plenty of throws), but it can nonetheless be mitigated by
using a wear-leveling scheme, where you distribute the writes across the
whole EEPROM instead of always overwriting the same bytes.
Wear-leveling can add significant complexity to your program, but it
turns out there is, in this particular case, a wear-leveling scheme that
is trivial to implement: just write at a random location! At startup,
you do not know what was the last location written to, but you do not
need to: you read and mix the whole contents of the EEPROM:
#include <avr/eeprom.h>

// Save the entropy to EEPROM. Call this every time the user requests a
// new value.
void save_entropy()
{
    uint32_t *address = (uint32_t *)(random() & E2END & ~3);
    eeprom_write_dword(address, random());
}

// Restore the entropy from the EEPROM. Call once in setup().
void restore_entropy()
{
    uint32_t seed = 0;
    for (uint32_t *address = 0; address < (uint32_t *) E2END; address++)
        seed ^= eeprom_read_dword(address);
    srandom(seed);
}

Combine the entropy sources with the XOR operator
As you probably already noticed, the bitwise xor operator (^) is used
every time one wants to combine entropy sources. The main reason is
that, if a and b are independent random variables, then a^b is at
least as random as the most random of a and b. Which means that
XORing a “good” random variable with a “bad” one is harmless. This is
somewhat formalized as the piling-up
lemma.
As an example, doing randomSeed(analogRead(0)) at program startup is
fine, but doing it repeatedly during program execution is a terrible
idea: most of the time this will put the RNG in one of a very few
states. If instead you
srandom(random() ^ analogRead(0));

then you are combining the current randomness of the RNG with the output
of analogRead(), and putting this back into the RNG. And this is
harmless even if analogRead() is quite predictable.
A side note on randomSeed(): Arduino releases prior to 1.6.5 had a
bug that would truncate to 16 bits the entropy provided with
randomSeed(). On those releases it is better to use the avr-libc
srandom()
function.
The bug has since been
fixed.

It's a 5V arduino Pro mini, but it should be able to run (per datasheet) on 2.7V to 5.5V, can I just put the 3V of the coin-cell battery on VCC. (I'm aware I'll have to use the internal 8Mhz clock on this voltage though). I won't need the regulator, since the coin-cell will never exceed 5V?

That is correct.

You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

Definitely not. That is a sure-fire way to kill the Arduino.
Also you have a Catch-22 situation. To make the pin conduct to ground you have to set it to output and switch it LOW. How can you do that if the chip is powered off? You need to power the chip on in order to power the chip on. It just can't work.

I could use the reset button, but would it still give me "random enough" numbers? Since the seed is reset every time?

You will only get random numbers if you seed the PRNG with a random number. If you can get a source of entropy (noise on an analog pin for instance) then yes, that could work.

And I know it's better to use a resistor on every pin, but I don't want to make it any more bulky.

It's not "better" - it's REQUIRED.  With just one resistor and one segment on that segment will get 8x the current compared to having all 8 segments on. You then either get very dim segments with lots on, or smoke from segments when not many are on.

Hmm, and what if I loop through all segments rapidly, having only one on at the time? Then one resistor should do? Since it makes it much easier to wire. Or I should indeed accept the difference and very dim with all on?

If you only have one segment on at a time then yes you can get away with one resistor.

Yup, that's a nice "hack". Equal brightness, efficient power usage. The trick for randomness is also a good one. If using milis and resetting device, it wouldn't be smart, since milis will the almost always be the same? Is it good to reseed once in a while?

It can increase your randomness, yes. Especially if you reseed at random times ;)

Hmm, yeah when using time as a "random variable" you should avoid seeding at specific times :) I could also try running it and collecting the data, test different methods, should be interesting.

Yes you should be fine with the voltage from a coin cell - though don't expect it to last long!
No you can't use an I/O as ground - they are set to input by default, and even if they weren't, if wouldn't be guaranteed to work, and even if it did happen to work*, it would be horrible.  I don't quite understand why you want to do it this way - why not just connect the cell's -ve to the GND pin, right next to the VCC?
If you seed your random number generator suitably (e.g. from an unconnected analogue input) you ought to be OK since that will suitably random - you'll be reseeding it each time with a different seed.
*Stranger things have happend! The very fist ARM chip worked without power, running from parasitic currents from the inputs, as they discovered by mistake when they tested it with the power supply disconnected.

The reason was that when just inserting the coincell holder, the other pin could only land on an IO pin. Or I would need some wiring. It should only show the digit for a short time when pressed on the button. But what battery is most energy per size?

I should look up the battery voltages by myself, sorry. Might even use USB power bank, but doesn't really look small. And might put it in proper board indeed.

Ah, that's a coin cell holder in the photo! I thought it was something you'd rested it on to take the picture! :-)  Bear in mind that you're probably going to want an off switch, unless you want to take the battery out, so maybe you can wire that in neatly somehow.

Yeah, when I look at the picture again, it actually looks awfull. I'm ging to use a protoboard as backplate and probably 2 digits (for other games). An on/off switch is indeed better. And maybe even 2xAA

You can actually use outputs as positive voltage, and you can sink currents. But does that mean I can connect the negative side of the coin-cell to an output, and sink it? This way it should power my arduino's VCC pin through the "digital GND"

It would not be a good idea to use a input pin as they can only sink a maximum of 40mA per pin.
Also, incase any power surges are experienced and it is connected to Vcc if that 5v is exceeded then it could damage your board. It might be a better solution to use the RAW pin even if it does ultimately use more power.

I agree on not using a digital pin as GND. But, the RAW pin needs a higher voltage? And a power surge from a battery is some what unlikely?

Not from a battery as such however since the design is exposed and open to surrounding sources of static charge it could affect the boards operation

Good point, though any static charge on the 5V/GND pins may cause failure? But it indeed is more likely to happen (like when touching the battery if it's connected). But the RAW pin has ESD protection?

I think a simple (and aesthetically pleasing) solution would be a case for the whole design. This would mean it could use the 3.3v VCC pin which would use less power compared to the RAW pin.

True, but I don't have a laser-cutter or 3D printer ;) I might design a case and let it print by one of those online 3D print services.


text:
How to use unregulated VIN voltage?
I have recently bought an Arduino Mega, and I am powering it with a USB charging port, 5V at 1A. I need to use the 1A with a transistor, since the Arduino itself can only supply a maximum of 20mA through one pin.
So I was wondering, is there any way to access this unregulated power source? Would the VIN pin serve this purpose, or is there no way to access the 1A current without pulling apart the USB cable?

The VIN port is connected to the barrel jack. It must only be used if you are powering the board through that jack.
To access the USB power just use the 5V pin - it is directly connected to the USB.
However, the USB, although the socket it is plugged into can supply more, is limited to 500mA. This is because of a 500mA auto-resetting polyfuse on the USB power input (the large gold and dark green rectangle next to the USB socket - mine has either XE05 or 503X on it depending on which way up you hold it).

Okay, thank you for clarifying. I guess I'll need to power it another way, so I can access the power source... or sacrifice a USB cable!

The VIN port is connected to the barrel jack. - via a diode. Thus Vin will be around 0.7V less than what you supply at the barrel jack.


text:
Max current through an Arduino Mega?
How much current can I put through the pins of an Arduino Mega at the same time?
The situation: I am building a 7x7x7 LED cube, and my plan was to multiplex in 7 layers of 49 pins, lighting each layer, one at a time. This would mean each pin on the Arduino Mega would only have to supply max. 1 LED at a time.
However, if all 49 LEDs in one layer were on, it would presumably draw 49*20mA (from the LED specs sheet), which is 980mA. This seems like quite a lot of current to put through an ATMega chip, so I was wondering if I could do it, either continuing like this, or using transistors to control the lighting of each layer, or what?
Any help or advice is appreciated!
EDIT: Using ATMega2560, not ATMega328 or alternate.

What does the ATMega datasheet say?  The maximum output current on microcontrollers I've used is around 20 mA, so your 980 mA is totally out of range - you'll need transistors to handl that much current.

@PeterBennett Yeah, the datasheet says the 20mA is per pin, and for an Arduino Uno. For an Arduino Mega, per pin is 40mA. The 980mA figure quoted is in total, over 49 pins.

Possible duplicate of Real maximum current for ATmega328?

The ATmega 2560 (assuming that's the chip on your Arduino Mega) has an absolute limit of 40mA on each pin, and 200mA in total for all pins. So yes, you will not be able to drive that load directly from the Arduino.

With external circuitry however, anything is possible. If it were me, I'd use some TPIC6B595 IC's to drain current and BC635 NPN's to source it.
The 595's can sink up to 150mA each (so up to 8 LEDs at 18.75mA each, use a 270Ω resistor in series with each LED if you're running everything from 5V.) You would need 7 595's for 49 LEDs (49 / 8 rounded up.)
You can daisy chain the serial in/outs on them so you just need to shift out 8 bytes from the Arduino (either using SPI or the software equivalent, shiftOut or whatever it's called, on any digital pin.)
TPIC6B595N Datasheet
To source current, BC635's are rated up to 1A with a typical current gain (hFE) of 100. Collector pin goes to 5V, Emitter pin goes to all the LED anodes on a layer, Base pin connects in series to a 510Ω or 470Ω resistor and an Arduino digital pin. You would need 7 635's, one for each layer. They turn 10mA from a digital pin into 1A from the power supply.
BC635 Datasheet
Speaking of power supplies, you will not be able to power the whole thing from the Arduino 5V pin (especially if powered from USB.) You will need an additional 5V power supply. If you want simplicity you could use a L7805 voltage regulator and stick a heatsink on it.
L7805 Datasheet
All of these are popular components which can be obtained from eBay for next to nothing.
If you have more questions specific to Arduino, they might be better suited to the Arduino Stack Exchange.
Arduino Stack Exchange Link

I should mention that by multiplexing each LED will only receive 1/7th of the current over time. That is to say, if you were putting 18.75mA through each LED they would only get the equivalent of 18.75mA / 7 (2.68mA.)

So what if I went over the max recommended current for the LEDs? I asked for 180 ohm resistors and I got given 150 ohm instead at Maplin's, and didn't check before I was out. The blue LEDs have a voltage drop of 3.3V which gives 3.3/0.150 = 22mA, which is over the recommended 20. But since I am multiplexing, this means I'd have an equivalent of 22/7 ≈  3.1mA?

Ummm I think that should be (5V - 3.3V) / 150Ω = 11mA so you're fine in either case.

You're on the right track here. In the datasheet for the ATmega1280 I find this box:

What you want to look at is DC Current Vcc and GND Pins  ....  200.0 mA
This is the total limit of all the current going through the chip (because everything must come through Vcc), and it is the absolute maximum. Don't go near it. You need to boost this with some transistors.

It's listed in the Electrical Characteristics of the specific MCU used in the Arduino you have.
For the Mega2560, its remarkably similar to the 328 in the Uno.
Absolute Max, 40mA per pin, 200mA VCC or GND current. 20mA per pin recommended max. A huge note, various ports have individual limits:

3: Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state
  conditions (non-transient), the following must be observed:
  ATmega1281/2561:
  1.)The sum of all IOL, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
  2.)The sum of all IOL, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
  3.)The sum of all IOL, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
  4.)The sum of all IOL, for ports F0-F7 should not exceed 100mA.
  ATmega640/1280/2560:
  1.)The sum of all IOL, for ports J0-J7, A0-A7, G2 should not exceed 200mA.
  2.)The sum of all IOL, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
  3.)The sum of all IOL, for ports G3-G4, B0-B7, H0-B7 should not exceed 200mA.
  4.)The sum of all IOL, for ports E0-E7, G5 should not exceed 100mA.
  5.)The sum of all IOL, for ports F0-F7, K0-K7 should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition.
4: Although each I/O port can source more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
  ATmega1281/2561:
  1)The sum of all IOH, for ports A0-A7, G2, C4-C7 should not exceed 100mA.
  2)The sum of all IOH, for ports C0-C3, G0-G1, D0-D7 should not exceed 100mA.
  3)The sum of all IOH, for ports G3-G5, B0-B7, E0-E7 should not exceed 100mA.
  4)The sum of all IOH, for ports F0-F7 should not exceed 100mA.   ATmega640/1280/2560:
  1)The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed 200mA.
  2)The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
  3)The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
  4)The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
  5)The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.


text:
Reading 2 numbers from serial
I try to send pairs of numbers over the serial port from a linux pc to the arduino. By now I did so always by piecing together the ASCII chars from the serial line and using Serial.read(). Now I need this same thing to run at 100-200Hz, and it turns out, that the Arduino does not receive all the data (even at 1Hz).
As turned out, my problem was in another portion of the code and all below code works perfectly as is!
How do I make sure, that every char (or better even byte without ASCII encoding) is received? I am aware, that each connection has errors, but this is a systematical error! I guess, that the bytes are lost during the processing within the main loop, or because of other callbacks I use (got some ISR running). I am not looking for error detection, but rather a concise way of reading the serial line, without loosing 70% of the data validity.
If important: the pairs i need to send are unsigned, 1 byte and another one with 2 bytes. The values are in the range of [0;7] and [1000;2000]. Thanks for any advice. Disclaimer, I read a lot, including this, but most questions go into detail about the packaging format, whereas I am concerned about the reading method.
Code I use at the moment:
// read numbers from the char representation!
// on the serial connection
// each DIGIT is sent separately

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
uint8_t channel; // holding the number of the channel to modify
uint16_t signal; // ppm signal length in us (1000-2000)

void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
  if (stringComplete) {
    channel = uint8_t(inputString[0])-48;
    signal = 0;
    for (uint8_t n=1; n<5; n++) {
      signal = (signal*10) + uint8_t(inputString[n])-48;
    }
    Serial.print(F("ch: ")); Serial.print(channel);
    Serial.print(F(" signal: ")); Serial.print(signal);
    Serial.print(F("\n"));
    //PROCESS Data
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    // if the incoming character is a
    // newline (10) or carriage return (13)
    // set a flag for a complete transmission
    if (inChar == 10 | inChar == 13) {
      stringComplete = true;
    }
  }
}

Another version I tried, without strings is:
// channel and pulse-length
uint16_t numbers[2] = {0, 0}; // channel,value
uint8_t buf[5];

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

void loop() {
  if (serial_input(numbers,buf)) {
    numbers[0] = buf[0]-48;
    numbers[1] = (buf[1]-48)*10+(buf[2]-48);
    Serial.print(F("channel: ")); Serial.println(numbers[0]);
    Serial.print(F(" signal: ")); Serial.println(numbers[1]);
    // Do Stuff
  }
}

uint8_t serial_input(uint16_t* num, uint8_t* buf) {
  uint8_t newData = 0;
  uint8_t k = 0;
  num[0] = 0; num[1] = 0;
  while(Serial.available()) {
    delayMicroseconds(2100);
    char ser = Serial.read();
    if (isDigit(ser)) {
      buf[k] = uint8_t(ser);
      k++;
      newData = 1;
    } else {break;}
  }
  return newData;
}

Another try inspired by an answer here, where I send "3 1500\n" over the serial line:
void serialEvent() {
  if (!newdata) {
    channel = Serial.parseInt();
    signal = Serial.parseInt();
    newdata = true;
  }
}

Turns out all of those methods work (more or less elegantly), but having a "delay" within an ISR isn't such a good idea - even intermediately...

there is a great function:
https://www.arduino.cc/en/Serial/ParseInt
I have tested the following script up 2kHz incoming, but it should go even faster.
Do something like this
int number = 0;
int number2 = 0;
bool get_data = false;
void setup() {
  Serial.begin(115200);
  inputString.reserve(200);

  pinMode(9,OUTPUT); // fixed pin 9 for PPM output
}

void loop() {
    if(get_data == true){
      Serial.print(number);
      Serial.print(number2);
      get_data = false;
    }
}
 void SerialEvent()
   if(!get_data){
     number = Serial.parseInt();
     number2 = Serial.parseInt();
     get_data = true;
   }
}

115200 baud at 200Hz means you should be able to transfer in excess of 50 characters between each "trigger". That is more than enough time to send the data even as ASCII encoded text.
serialEvent() is no better than manually looking at things like serialAvailable() in your loop since that is all it does anyway. It just runs after each iteration of your loop.
One problem that you have is that you're appending each character to a String object. This is very inefficient and should be avoided. Instead you should really use a character array:
// Input text in the form "123 456\n"
char instring[20]; // Room for 19 characters plus terminating null
int spos = 0; // Location in the array
int val1 = 0;
int val2 = 0;

void loop() {
    if (Serial.available()) {
        char *bita, *bitb;
        int c = Serial.read();
        switch (c) {
            case '\r': break; // ignore
            case '\n':
                 spos = 0;
                 bita = strtok(instring, " ");
                 bitb = strtok(NULL, " ");
                 if (bita && bitb) {
                     val1 = atoi(bita);
                     val2 = atoi(bitb);
                 }
                 // You now have two new values in val1 and val2
                 break;
            default:
                if (spos < 18) {
                    instring[spos++] = c;
                    instring[spos] = 0;
                }
        }
    }
}


text:
Arduino LCD changing contrast only makes black boxes less readable i.e. less in contrast
I have seen similar issues posted here but none match my problem exactly.
I have a starter kit and a 16x2 LCD screen that only shows black boxes in the top row using the following code:
#include <LiquidCrystal.h>

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

void setup() {
  lcd.begin(16, 2);
  lcd.print("hello, world!");
}

void loop() {

}

All tutorials use a potentiometer to change the contrast but I don't have one so I decided to use chain several resistors. When doing so, the contrast indeed changes, but it changes as a whole. The black boxes become less readable i.e. less in contrast (more vague) but stay completely black.
Just to make sure, I have a cable from the + tray (with 5v) to the VDD port and - tray (with GND) to the VSS port. The K port is on the - tray as well and the A is with a 220 ohm resistor on the + tray.
I have tried no, 3k, 4k, 3220, 10k and 100k ohm on the v0 port to change the contrast.
What could be wrong? Any help is appreciated.
Edit photo:

Black boxes mean the screen isn't being initialized. Check your wiring.

@Majenko I checked it at least 2 times. Either a cable is faulty, I forgot code or my LCD is broken. Can't think of another reason at this point.

Maybe you could show us your wiring and we can check it for you?

@Majenko photo or provide an overview in my question? Following all cables might be a bit messy I fear.

Photo. It's hard to see what you have done from test alone.

@Majenko take a look. I hope it's clear enough

That is almost impossible to follow. Don't you have some more varied colours of wires? Or separate them out a bit so they can be followed manually?

@Majenko I feared so. I do not have that many colors unfortunately. It's the setup shown in this video minus the potentiometer (I used 3 chained 1k resistors): https://youtu.be/Mr9FQKcrGpA?t=3m45s

You have your polarities round the wrong way. VDD and A (for 'anode') should be positive/5V; VSS and K (for 'kathode') are Ground. As you have a backlight, I suspect you have at least A and K the right way round, but you have Vss/Vdd switched.

@CharlieHanson Sorry my bad, A was actually in the + tray and the K in the - tray. Mixed them up in the text. VSS is in the - tray as well like in the text and VDD in the +.

Great, now all you have to do is re-read my comment and find the other mistake you are still making.

@CharlieHanson, K and VSS in the - tray which is connected to ground, VDD and A in the + tray. What am I missing?

Nothing from that comment, but the text in the question is still incorrect. The quality of the photo is so bad that it's very tough to know if it's a typo or actual incorrect wiring. Always check, check, then check again.

Please post the photo in the question, not a link off-site. There is an icon for adding photos to questions.


text:
ATtiny85 and INPUT_PULLUP
I have read some conflicting sources about what pins have internal pullup resistors available for the Attiny85 microcontroller. Can all I/O pins work with INPUT_PULLUP, or just some of them? And if so, which ones?
Thanks!

Check the datasheet, probably just search for "internal" or "pullup"  I believe there are little more pins/ports as portB, so they should all have internal pull ups.


text:
Has anybody seen/created a gps guided vehicle with arduino?
I thought the idea of Amazon Prime air drone delivery was a pretty cool one when it first came out and I started to question whether something like that (an autonomous gps guided vehicle) could possibly be created with the Arduino microcontroller(s). Any thoughts?

Is this your other question just worded slightly differently? If so, it would be better to ask one question, not two almost identical ones.

@NickGammon uh oh, well as you can see im new here and I have no clue what caused me to submit it twice

You might really want to check out LIDAR applications. While extremely expensive, it's a superb way of checking your surroundings. (https://www.youtube.com/watch?v=nDkW_XuXQEM)

GPS is not, by itself, enough to make an Amazon Prime-like delivery drone.  GPS only provides a very rough position (thanks to the US Military imposing a large margin of error on non-military users, or so the urban legend goes (it's actually a difference in transmission systems that makes the difference)). It's good enough for getting you to your destination and working out roughly where you are, but getting to a specific pinpoint location just can't be done.
So you need other sensors as well. Things that can examine the environment and work out where you are in relation to other things. Especially people. Object avoidance is the critical component of any autonomous drone, and unless you can come up with a completely safe and foolproof system the FAA will be down on you like a ton of rectangular building blocks.

Yes, someone (not me) has: https://www.youtube.com/watch?v=3-r2Jk0uA6U
I doubt it would work very well with non-flying vehicles - in the air, a 3 meter margin of error is fine, on the ground it's the difference between the sidewalk and the middle of the road.


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

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


text:
How do I reduce this down to a smaller, more permanent prototype?
I've prototyped a little light/sunrise alarm clock w/ an Arduino Uno and a breadboard. How do I go about figuring out what components I'd need to reduce this down in to a more semi-permanent prototype?
Obviously I don't need everything the Uno has to offer and I'd like to slim this down into a custom box I build.
But what sort of microcontroller(s) would I need to size this down? How else can I simplify it?
To be clear, I'm not trying to turn this in to any sort of finished/super-polished product. Just wanting to get out of the breadboard and in to some soldering of something a bit more set in stone.

The resistor at the top does nothing - it's legs are connected together.

In addition to AMADANON's answer, I would like to point out that if you are going as far as making a PCB (which I highly recommend), you would do well to move away from Fritzing and use a more capable schematic/layout software. I recommend Kicad, but Eagle, DesignSpark, and gEDA are other free options.

@uint128_t You can actually make decent PCB's with Fritzing... Compared with Eagle, I think Fritzing is way more easier to use. You could compare it like "Arduino IDE and Eclipse IDE". For a starter, I would highly recommend Arduino IDE. Same applies to Fritzing. He's never going to use very advanced features, so shouldn't be bothered with it. I can't see why such an (easy) board can't/shouldn't be done in Fritzing.

@Shpigford you should really check your wiring at the RGB Led's
Also, I'm not sure if your buzzer could be switched with PWM (or is active itself), you might just use the pin 9.

You could use a pro-mini instead of an UNO. Or just the bare ATMega chip kike others suggested. You could use proto-board instead of breadboard. You probably need to add resistors to those leds.

I think your LEDs are probably seriously wrong, according to the above design. I think the above design will immediately burn out your power supply and/or your LEDs, since 3 of the 4 LEDs are connected directly across the power. They will light up blue, but consume way too much power. The top one has a non-functional LED, and could be powered to light up green, which draw too much power through the Arduino and burn it out.

@Paul and AMADANON: They are NeoPixel through-hole LEDs: https://www.adafruit.com/products/1734 I've got them wired up how Adafruit suggests (at least that's my understanding from their photos). ¯_(ツ)_/¯

@AMADANONInc. FYI, regarding the resistor, Adafruit suggests adding that: https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices It's for the Arduino from the data out to the data in on the first LED.

Aha, yeah it wasn't 100% clear, they do really look like RGB led's. I'm more used to the chip-like neopixels.

To what size do you want to reduce it? It's in those cases better (and cost effective) to not use breakout boards. But to solder the chip directly. There is a RTC with built-in crystal in an 8 PDIP package somewhere, that greatly reduces the size (and accuracy). But I believe you're better off soldering it to a protoboard :) a PCB will be overkill for a one-off project, especially when using breakouts etc. How should it be powered?

@Paul Just enough to fit in a ~8x8x8 box. And I'll power it via a wall adapter of some sort. It's just going to sit on my nightstand and wake me up every morning. :)

And it's probably less about "size" and more about not tying up my Uno so I can use it for other projects.

How would you configure it? And wouldn't it be nice if it can display time? (: But I might re-look into this question tomorrow, since I always wanted to make an arduino alarm clock :)

Let us continue this discussion in chat.

@Shpigford The easiest thing to do, since the circuit is really simple apart from the arduino, in my opinion is to wire the breadboard stuff on a perfboard; with a bit of planning it can become really small. Then add an arduino pro mini, which is exactly the same as the arduino uno, but much smaller and cheaper (it just lacks the usb to serial converter, but you are not using it. This is the cheapest and easiest to make solution, in my opinion

At a bare minimum, you need a power supply, and an AtMega or AtTiny chip.
The AtMega and AtTiny's have an internal clock, 1mhz. It's not terribly accurate for timekeeping purposes (1% error, I think, as opposed to 20ppm = 0.02% for the external clock), but I see you have an RTC, so a 1% drift is probably fine (I can't see your code, so I don't know if the internal time is used for anything). Remember that you will need to adjust your code for the different clock rate, anything that uses anything time-related will run at 1/16th speed (delay, serial comms, etc). You will need to set the fuses to use the internal clock.
If your power source isn't 5v, then you need a transformer.
What type of AtTiny or AtMega you use depends on your code, and how many pins you use. I see 5 pins, they are all used as digital I think? You might get away with one of the 14-pin AtTinys. I suspect your code is probably pretty small. You can probably get away with nearly any AtTiny. To select an AtTiny, go to http://www.atmel.com/products/microcontrollers/avr/tinyavr.aspx
Nick Gammon (who will probably be providing his own answer as I type) has an excellent site on how to put the parts together, at http://www.gammon.com.au/breadboard
This site mentions programming the bootloader. On a low-memory chip, you do not need a bootloader, you can upload your program using SPI (same way as you upload the bootloader in Nick's example). Alternatively, you can use a programmer like the USBASP, which makes the whole process a lot easier. When you build your final board, I strongly suggest putting a 6-pin ICSP header (same as the 2x3 pins on the end of your Arduino board) on, to make reprogramming easier. You plug the USBASP into the 6-pin header, and click File->Upload using programmer.
ADDITIONAL:
If you want your project "really nice", you can design and etch your own PCB. If "good enough is good enough" (which for me it always is), I suggest you use stripboard (also known by it's brandname, veroboard).
In either case, spend some time thinking about your exact layout. Use a computer layout tool, and spend some time working out the best layout. I generally spend at least 5 times as much time on the layout, as I do on building the board - if a project is twice as big, I will spend twice as much time soldering, but at least 4 times as long laying it out.

Nick Gammon (who will probably be providing his own answer as I type) - I won't need to after such a comprehensive answer. :) However the page of mine Amadanon linked to certainly has some tips for you.

Several steps are required:

Define what you want to achieve in a clear and explicit manner, eg start documenting your project by writing down your decisions and design goals, for example on a project wiki somewhere. This could be the time where you explore the internet to gather several inspirational sources & modules you want to reuse.
Check that your schematic is correct, eg that first prototype works reliably. Obviously, going from prototype to a "more permanent prototype" should include checking everything works as expected (getting validation from here would be an option).
Prepare a hardware design, eg routing on your prefered CAD software. Many options exist: Fritzing, Eagle, Kicad, ... You may need help/tutorials to do this properly
Manufacture the pcb, or get your board manufactured. Several options are available (see below)
Assemble & test; depending on results, go back to step 1, 2, 3 ;)

To check that your schematic is correct, well, you can post it somewhere. As a starter: your initial post has some errors.

resistors required for LED
red (+) seems to be on GND, not +5v (!!)
using a pulldown for the button where an internal pullup is sufficient is a waste of ressource

Answer above has errors, too (as stated). So make sure your schematic & prototype work before trying to get it more permanent.
To manufacture the PCB, several options:

Veroboard & through hole components. Not small, but cheap, easy & reliable.
DIY: toner transfer method (numerous examples & howto online) :
requires a bit more time/skills, but if you plan to do several
boards/experiments, can be worth it. Can be rather cheap. Cannot
yield high precision pcb.
Note: other DIY PCB manufacturing techniques exist.
boardhouse contract manufacturing: yields perfect results (if your
design files are OK...), can't be quick & cheap (but can be either,
relatively)

Didn't even know about pullups for those buttons. Just tweaked it to do that instead. Fantastic!

I did an awful try at making a nice breadboard for it.
BUT.
I think you're better off using some perfboard, small solderable wires and an Arduino Nano.

This because the Arduino Nano has an FTDI chip, crystal and power regulator and is barely bigger than an 328 DIP package.
You could easily mount the pieces of perfboard inside/on your enclosure.
Aim to add the snooze button on top with the settings buttons on the sides.
The buzzer could be in the back or other side. The display (if any) should be in the front. Your "Neopixels" are no different than WS2812B "led's".

Ah. that capacitor is just plain wrong, but I hope you get the idea :) Also, you'll have to make each "module"  individually, I haven't dived too far in the MAX7219 but it can be adressed using SPI (only ~3 lines). An can actually update 8 (7segment) displays (4 in this picture).


text:
Sparkfun Si4703 FM not getting to loop
I recently purcahsed an si4703, from sparkfun
https://www.sparkfun.com/products/11083
I got it soldered to some headers and now I am not getting anything to work on it, my wire diagram is as follows

( I know the FM module pictured is different but its ultimately wired up the same I think)
And I am just trying to run the out of box example code modified to my Arduino Mega board
#include <SparkFunSi4703.h>
#include <Wire.h>

int resetPin = 35;
int SDIO = A15;
int SCLK = A14;

Si4703_Breakout radio(resetPin, SDIO, SCLK);
int channel;
int volume;
char rdsBuffer[10];

void setup()
{
  Serial.begin(9600);
  Serial.println("\n\nSi4703_Breakout Test Sketch");
  Serial.println("===========================");
  Serial.println("a b     Favourite stations");
  Serial.println("+ -     Volume (max 15)");
  Serial.println("u d     Seek up / down");
  Serial.println("r       Listen for RDS Data (15 sec timeout)");
  Serial.println("Send me a command letter.");

  radio.powerOn();
  radio.setVolume(0);
}

void loop()
{
  Serial.println("looping");
  if (Serial.available())
  {
    char ch = Serial.read();
    if (ch == 'u')
    {
      channel = radio.seekUp();
      displayInfo();
    }
    else if (ch == 'd')
    {
      channel = radio.seekDown();
      displayInfo();
    }
    else if (ch == '+')
    {
      volume ++;
      if (volume == 16) volume = 15;
      radio.setVolume(volume);
      displayInfo();
    }
    else if (ch == '-')
    {
      volume --;
      if (volume < 0) volume = 0;
      radio.setVolume(volume);
      displayInfo();
    }
    else if (ch == 'a')
    {
      channel = 930; // Rock FM
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'b')
    {
      channel = 1067; // BBC R4
      radio.setChannel(channel);
      displayInfo();
    }
    else if (ch == 'r')
    {
      Serial.println("RDS listening");
      radio.readRDS(rdsBuffer, 15000);
      Serial.print("RDS heard:");
      Serial.println(rdsBuffer);
    }
  }
}

void displayInfo()
{
   Serial.print("Channel:"); Serial.print(channel);
   Serial.print(" Volume:"); Serial.println(volume);
}

However I do not think it is ever getting to the actual loop, it seems to get stuck on the code radio.powerOn() and then does nothing after that, what can I do to make this work?

Welcome to Arduino StackExchange! But could you please add an actual picture of your wiring instead of that image?

According to your hookup image, you have connected I2c pins to A14 and A15, I2c on Mega is on pins 20 and 21 , clearly marked SDA and SCL.
Also note that this module can ba powered by 5V but is only 3.3V tolerant on the input pins, you should use a level converter.

Thank you so much, It worked, why on an UNO board in the hookup guide does it say to use Analog ports A4 and A5, is it because the Mega offers something the UNO does not?  Just would like to know the reasoning as to why it works, thanks

The AtMega328p and the AtMega2560 are wery different in many ways and the pinout and what hardware features are available on which pin is also different, while they are made to be as similar looking as possible this might often lead to your little snafu.


text:
Controlling Arduino through Internet and Bluetooth
I have an Arduino sketch that controls an LED through the Internet, and another through Bluetooth. The thing is I want to combine both sketches so that I can control my Arduino LED by Bluetooth as well as through the Internet. Is it possible to do that?

If I were you, I would separate the "hardware" from the "software". This is quite an interesting "pattern". It's used by almost every Operating System, to assure compatibility with devices all around the world.
But how?
Layers
The "OSI-model" typically describes a few layers. But to me, the most interesting part is the difference between "Host layer" and "Media layer".
Media Layer
The media layer(s) typically handle the transportation of your bits, addressing and data collision. In "the internet" you can 'simply' change from copper to glasfiber without it being noticeable in your end application (apart from being faster).
Host layer
The same for the host layers, whatever PC or network adapter you have, your program will run fine (if this abstraction/integration is done well).
Applying this
So how do we apply this? In a basic, small application.

We want our Host to not care too much about which Media(layer) it is using.
The Arduino has to be able to be configured or detect which media layer it is using.
Something like this is neccesary (this is not actual code, more pseudo code):
String messageBuffer = "";

void Setup(){
   setupWifi(pin1,pin2);
   setupBluetooth(pin3,pin4);
}

void Loop(){
   messageBuffer = getWifiMessage();
   handleMessage(messageBuffer);
   messageBuffer = getBluetoothMessage();
   handleMessage(messageBuffer);
}

If you set up this correctly, you'll only have to write the buffer handling code once. Which is very useful!
Handling buffers along with all the logic/effects it will cause, should be solid. You (probably) don't want different behaviour when you use bluetooth as when you use WiFi. Imagine your web-browser only working when you use copper, but not when you use glasfiber :)
Protocol
Your message should be exactly the same for WiFi and bluetooth. This way you won't have to deal with two different protocols and it will be easier to implement this at the other (control) side.
A good protocol/message can be this:
"@12#13,255,255,0;"

I use the @ as an start indication. This is very usefull for receiving, since you know where to start (obviously?).
You'll have to make rules for what will follow (maybe a set amount of characters, in my example, between @ and # it will indicate an "address". When you send it to multiple devices, you only want (in my example) device 12 to react. This often is handled by the bluetooth or wifi already, but it can be good to have some sort of unique header. So that random messages (which might look alike) won't be seen as one of your messages.
An message ID is useful, you kinda want to have different types of messages, for either "LED brightness" or "debug request" or "set output".
Each message could have an x amount of parameters, it's often better to separate these. It's important that you specify the maximal amount of parameters and what behavior they will cause.
Some protocols use a set length, but an end delimiter ";" is often the best way to let the other device know your message is completely received.

Some notes

Try to aim for existing protocols, it will be cool if your device is compatible and creating yet another protocol isn't particularly useful.
Mind that possible transmitted text does not include your start/end delimiters. You could use the message length or exclusions/inclusions in this case.
Be wary that the protocol adds overhead. But usually being able to "read" a message will make it much more easier to program a handler or generally work with it.
Check if the message is fully received and does not have errors. If you have an error, be sure your system can handle it and will respond with a message telling so. In no way your system should lock down on error or not provide a reaction (which makes debugging a pain).

The server
From whatever device you're sending your stuff, it should have bluetooth and/or WiFi. Bluetooth is fairly easy and should get you started quite fast.
If you're using WiFi, you should check if your device can make a TCP/IP connection. TCP/IP is basically a "shell" around your message, to shoot it over the internet ;D it comes with some neat addressing and error checking built in (but you can't be 100% sure there will be no error between your receiver and arduino).
But why?
Not only is it useful to learn how to do this, having to write the handler and protocol specification for both the Wifi and bluetooth (and possible usb, rf, ethernet etc).
Apart from that, in embedded systems, you want to be sure that something works, using different handlers for different physical layers will create vague specific errors and might rip up your program logic. Also, if your protocol/application is used/reviewed by more people, you'll be more certain that it works well.

What if I don't what to use the wifi or Ethernet shield.. ??? I will use directly from USB port.

so that I can control my adruino led by Bluetooth as well as through Internet. Is it possible to do that?. How you mean? Will you use your PC as the "internet receiver" and send it to the Arduino through serial?

It's not trivial to use Wifi or Ethernet without any form of (certified) receiver. The ESP8266 is a cheap 3$ Wi-Fi solution, but you could indeed use your PC as a master.

Yes ..I'm  doing my project.. I didn't bought the Ethernet/wifi shield so I want to show a demo only how we can control from Internet..

Can It be done or not...Bluetooth as well as Internet without wifi shield to control led?

Judging from your reaction, you don't want to use a WiFi/Bluetooth/Ethernet shield
Arduino has no built-in Bluetooth or Ethernet.
The question is shifting a little towards software, but okay.
1. Using your PC as Ethernet/Bluetooth receiver
You can (and I believe you want to) use your PC as the receiver.

Talking in network terms, your phone has to become a "client" and your PC will become a "server".
I would advise using Processing on your PC as a "Server".
Within processing you can easily set up a connection to your Arduino.
And even use your PC's bluetooth or you might just set up a "bluetooth COM port" which makes your Bluetooth device look like a serial device like the Arduino.
There is a little catch though. Processing can easily set up a TCP/IP connection. On your phone this might be a little less trivial. Your browser generally uses HTTP(s) to connect.
So you should either implement HTTP in Processing or make/use an app that supports TCP/IP message sending.

Okay..I want to use Bluetooth which I can control using an Android app. And also the same led which I controled using Android I even want to control through Internet i.e. serial communication

You use MIT App Inventor (http://appinventor.mit.edu/explore/ or alternatively http://www.appinventor.org/), create your own app and after that you can access all the results of Arduino on your smartphone.


text:
Open WiFi Configuration Automatically
Is it possible to have an Arduino Uno + WiFi 101 recognize when the USB cable has been connected and prompt a user to enter a network name and password?
Can this be stored on the Arduino itself or does it need to be something run locally on the user's PC?

Prompt the user where? The serial monitor? What do you want to be stored on the Arduino?

Good questions. I'd like a window with a few text fields to open. The user will input the network name and network password and press a submit button. The submission will amend the sketch and replace the old name/pass with the new. The file that opens the window would be stored on the Arduino (or is that unwise/not possible?).  A clean-ish ui would be better than the terminal but the terminal would work I suppose.  A user should not have to download and install the IDE.  Think parents and non-tech friends

To render a UI, you need a PC program. It would handle presenting an interface as well as communicating the user's input to the Arduino over UART. I would recommend writing your own program as it would give you a lot of freedom in the UI design. Processing and Python are good options. To avoid using the IDE, you'll need a USB-TTL adapter cable. If you use the default USB connection, you need the drivers which only ship with the installer AFAIK. To detect the COM port, you can either have the user check the Device Manager or make your program auto-detect it, though this isnt very reliable. This link shows some Python code on detecting the Arduino's port or at least, displaying a list of open ports and allowing the user to choose. You can set the baud rate and other stuff permanently in your code; the COM port is the only variable. Also all handshaking b/w the Arduino and PC can be done without the knowledge of the user.
That said, there are already existing programs (for most common OSes) that can provide minimal functionality. If you dont need a fancy GUI, then putty (on Windows) can serve to read input from a user and pass it on to the listening Arduino. You can use putty's default baud rate (9600) in your Arduino sketch so that the user doesnt have to set this. Again, the COM port must be known. Device Manager is the only real option.
With this second approach, you could make a user enter some string (or even a char) in putty to prompt the Arduino to ask for the SSID and password. Once the Arduino is powered, it does nothing but wait for that input string and once it receives it, it sends something like: Enter SSID: , the user complies (and presses the Return key to terminate) and this is repeated for the password. The Arduino sketch would look like this:
#define MAX_LEN 20  //max length of name or password

char PROMPT[] = "ready\r"  //the initial string input from a user
char SSID[MAX_LEN];  // buffers for the ssid and pwd
char PWD[MAX_LEN];

init_done = 0;  // this var is set when an ssid and pwd have been received

void setup(){
  Serial.begin(9600);
  //anything else
}

void loop(){
  if (!init_done)
    continue;
  //  your other code
}

void get_data(){
  Serial.print("Enter Network SSID: \r\n");
  while (Serial.available() == 0);  // wait for input

  // no timeouts used here; wait till user presses return key
  int i = 0;
  char c;
  while (i < MAX_LEN - 1){  // read chars till the buffer is almost full
    c = Serial.read();
    if (c == '\r') // means end of input
      break;
    SSID[i++] = c;
    while (Serial.available() == 0);  // wait for next char
  }
  SSID[i] = 0;  // null terminate
  while (Serial.read() != -1);  // flush serial buffer

  Serial.print("Enter password: \r\n");  //same as before
  while (Serial.available() == 0);

  i = 0;
  while (i < MAX_LEN - 1){
    c = Serial.read();
    if (c == '\r') // end of input
      break;
    PWD[i++] = c;
    while (Serial.available());
  }
  PWD[i] = 0;
  while (Serial.read() != -1);

  //Serial.print("Done.");
  init_done = 1;
}

void serialEvent(){
  if (!init_done){
    while (Serial.peek() != PROMPT[0]) // read off any garbage
      Serial.read();
    int i = 0;
    while (1){
      if (Serial.peek() == PROMPT[i++]) // compare received chars to PROMPT
        Serial.read();
      else
        return

      if (i == sizeof(PROMPT)){ // read enough chars
        while (Serial.read() != -1);  // flush the buffer
        get_data();  // get ssid and so on
      }
    }
  }


text:
Take the program from the arduino board
How to remove the program from arduino board which is already there in it.?And I need that program in my arduino IDE how to take it please help me?

You remove an existing sketch by uploading a new sketch.

That's a somewhat advanced question. And you shouldn't be "stealing" code for no reason. But you can have a look at this: https://ucexperiment.wordpress.com/2015/01/04/dump-and-disassemble-avr-%C2%B5c-flash-memory/

You can retrieve the program currently in your Arduino with the
avrdude tool. This tool comes with the Arduino installation. The way
to call it is somewhat OS-dependent. On Ubuntu, for an Arduino Uno, I
type:
avrdude -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:r:prog.hex:i

This creates the file prog.hex with your program in Intel
HEX format. You can save this
file if you want to re-install it on the Arduino later. You can also
turn this file into an assembly listing with avr-objdump:
avr-objdump -m avr -Dz prog.hex > prog.lst

You may be able to make some sense of this listing if

you are well versed in AVR assembly language
you have lots of spare time

As others have said, you cannot expect to get the original C++ source
back.

You can't. The program in the Arduino IDE is compiled to machine code (bits and bytes basically) and that's what is uploaded to the Arduino.

It's a bit like baking a cake. Or brewing cider. Once you have baked your cake can you get the eggs, flour and sugar back again? Can you make apples from cider? No. And it's the same with compiling. Once you have compiled your source code you can't turn it back into source code again.


text:
How to convert array of chars to array of ints?
I have a rather newbie question but I can't figure it out.
Lets say I have this char array:
char array[] = "10,11,12,1,0,1,0";

How can I convert it to an array of int like this?
int arrayINT[] = {10,11,12,1,0,1,0};

Are you sure those arrays contain what you want them to? In the first case, are you looking for an array which contains the values 10, 11, 12, 1, 0, 1 and 0?  (That's not what you have -- you have a string containing an ASCII 1, an ASCII 0, an ASCII comma, and so on.) And the second one I'm almost certain isn't what you want - it's an array of pointers to very short strings (if the compiler even allows it).

yes i know, i'm building http server and this is a part of a string that i recieve from my web page

OK. Do you want it to end up as int arrayINT[] = { 10, 11, 12, 1, 0, 1, 0 } ?

Yes, it seems that Majenko's answer below is working properly :)

I'll edit your question then, so it asks what you want.

Yes of course :)

If you have a C string containing ASCII numbers with a common delimiter (comma in this case) you can use the strtok() function to split it into individual strings.  Then you can use atoi() to convert those individual strings into integers:
char array[] = "10,11,12,1,0,1,0";
int intArray[7]; // or more if you want some extra room?

int ipos = 0;
// Get the first token from the string
char *tok = strtok(array, ",");
// Keep going until we run out of tokens
while (tok) {
    // Don't overflow your target array
    if (ipos < 7) {
        // Convert to integer and store it
        intArray[ipos++] = atoi(tok);
    }
    // Get the next token from the string - note the use of NULL
    // instead of the string in this case - that tells it to carry
    // on from where it left off.
    tok = strtok(NULL, ",");
}

Note that strtok() is a destructive function. It will decimate your existing string with NULL characters as it slices it up.

Amazing, this is working. I knew about strtok() and atoi() but couldn't get them working properly. Thanks very much!!

A major improvement would be counting the commas in the string and allocating an array of the approriate size. On the other hand, why not convert the nth value at runtime?


text:
Measuring LPO (Low-Pulse Occupancy)
I'm using an Arduino clone (Seeeduino Lotus) together with a Shinyei PPD42NS sensor to measure air quality. The sensor reports its measurement as Low-Pulse occupancy. What would be the best way how to collect the value with Arduino? Currently I'm simply looping for some predefined duration using pulseIn:
unsigned long starttime;
register unsigned long sample_time; // ms
register unsigned long lowpulseoccupancy = 0; // us

// Wait for the signal to return to HIGH
pulseIn(DUSTPIN, LOW);
// Now start measuring
starttime = millis();
while ((sample_time = (millis() - starttime)) < DUST_SAMPLE_TIME_MS) {
    lowpulseoccupancy += pulseIn(DUSTPIN, LOW);
}

ratio_pct = lowpulseoccupancy / (sample_time * 10.0);

Is there a better way? In particular, this tight loop prevents Arduino from doing anything else for 30s (or a similar period).
I was thinking about using interrupts, either triggering on CHANGE, or (if that's possible) having two functions, one triggering on RISING and another on FALLING. Are there any caveats when doing so?

Seeed studio has some example code for gas sensors using LPO. 30s is way longer than necessary though. Interrupt could also work. The only downside is you can't use those interrupt pin for anything else. There is no way to have two kinds of interrupts on a single pin.

@Gerben For completeness (and not to pick nits), you could OR a couple of devices' interrupt lines (through a gate if necessary) to a single interrupt line. On an interrupt, the ISR could poll the devices which would need to be able to cooperate in some minimum way, or the interrupt lines could be latched and the latches presented on other, non-interrupt pins that the ISR could poll.

Some help: https://github.com/selfbuilt/ppd42ns-example-code/blob/master/particle_meter/particle_meter.ino

You can trigger on CHANGE, and check in your handler which case it is:
   attachInterrupt(digitalPinToInterrupt(my_pin), my_handler, CHANGE);
    (...)
    void my_handler(void) {
      if(LOW==digitalRead(my_pin)) {
        //do_falling();
      }
      else {
        //do_rising();
      }
    }

Another option would be to use a timer to poll your input, and implement a logic on top of this.

How long does it take between the change and the invocation of the handler? In particular I'm concerned if I could miss some pulses due to the delay.

authors: Pʌʀvɘsʜ ĸʌʀtoos


text:
How to combine Leonardo with Ultrasonic sensor?
I am working on an Arduino project that replaces the computer mouse. I want to do this in combination with an ultrasonic sensor. I found some nice examples on youtube, but they didn't post the code. And an example on this website. But I don't get it completely. I don't have much Arduino skills, but do have some. How can you attach for example echoPinScroll to a board?
I hope someone can give me advice on how to use this ultrasonic to control my mouse!
#include <Mouse.h>

int echoPinCursor=2;
int trigPinCursor=3;

int echoPinBtn=4;
int trigPinBtn=5;
int echoPinScroll=6;
int trigPinScroll=7;
int x;
int y;
long duracionCursor, distanciaCursor;
void setup() {
 Serial.begin(9600);
 pinMode(trigPinCursor, OUTPUT);
 pinMode(echoPinCursor, INPUT);
 pinMode(trigPinBtn, OUTPUT);
 pinMode(echoPinBtn, INPUT);
 pinMode(trigPinScroll, OUTPUT);
 pinMode(echoPinScroll, INPUT);

}

void loop() {

//mover el cursor
int direccionx=moverx();
int direcciony=movery();

Mouse.move(direccionx, direcciony,0);
delay(2);

}

int moverx(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 1  || distanciaCursor <= 11){
   x--;
 }
if (distanciaCursor >= 12 || distanciaCursor <= 24){
   x++;
  }
 return x;
}

int movery(){
distanciaCursor=obtener_distanciaCursor();
if (distanciaCursor >= 25 || distanciaCursor <= 37){
   y--;
   }
if (distanciaCursor >= 38 || distanciaCursor <= 50){
   y++;
  }
return y;
}

long obtener_distanciaCursor(void)
{
digitalWrite(trigPinCursor, LOW);
delayMicroseconds(2);

digitalWrite(trigPinCursor, HIGH);
delayMicroseconds(10);

digitalWrite(trigPinCursor, LOW);
duracionCursor = pulseIn(echoPinCursor, HIGH);

distanciaCursor = duracionCursor/58.2;
return(distanciaCursor);

}

Was this the example, as it is the only link with echoPinScroll that I can find: I want to move the mouse pointer with an Arduino and ultrasonic sensor

What is your hardware setup?
From your code, it looks like you're not using the pins trigPinBtn, echoPinBtn, trigPinScroll, echoPinScroll. Weird. I can't figure out:

which ultrasound module you're using
what do you expect, eg which movement(s) in front of which ultrasound sensor shall generate which mouse action(s)

I would recommand having an iterative approach:

Play with your ultrasound sensor(s), eg understand properly how to wire them to the arduino, how to interface them (software/lib), what kind of values you can get from them, etc... This will depend on the HW module you have chosen (if any yet).
Read the documentation that comes with the mouse lib of the Leonardo and play with it independently/with existing, working examples.

That is divide and conquer: understand each bit before trying to assemble them.
THEN, and only then, you will have a better understanding of the different part of your project. You will then be able to formulate an overview of your project goals, and how you can do it. That is, start documenting your project before it is done: doing so will force help you to have a clear idea of what it is that you're trying to achieve... and thus how to achieve it.
But yeah, the overall project might look something like this:
// Ultrasound distance sensor #1, hooked to the arduino with xxx and yyy; generates movement along the x axis
// Ultrasound distance sensor #2, hooked to the arduino with zzz and ttt ; generates movement along the y axis
// Something for the wheel? The buttons?

//global values & objects
setup()
//initialize hardware& libs

loop()
//get raw ultrasound distances
//translate these into x and y movements
//do something about buttons & wheel?
//update mouse values