text:
Can I connect a voltage, higher that the 1.1V bandgap voltage, to an ADC pin
Can I (attempt to) measure a voltage that is higher that the ADCs Vref, without damaging my IC?
I'm trying to measure the battery voltage using a resistive divider, and using the internal 1.1V bandgap voltage. I selected the resistors so the voltage would be around 1V when fully charged.
My project can however also be power by a wall-adapter, which exceeds the batteries voltage, resulting in a voltage higher than 1.1V at the ADC.
In the datasheet the table of ADC Characteristics seems to indicate that the maximum input voltage is Vref. Though I'm not sure if that's the maximum voltage is can convert, or if that's the maximum voltage that's allowed.
Elsewhere in the datasheet it says: Single ended channels that exceed VREF will result in codes close to 0x3FF, which seems to indicate it isn't a problem to exceed Vref (as long as it's below Vcc).
The part I'm using is an ATtiny13A, but the relevant sections of the datasheet seem identical to the ATMega328.

Yes, you can go above VRef.

Voltage on any Pin except RESET
with respect to Ground ................................-0.5V to VCC+0.5

And as the ADC reference says anything above VREF will give you the maximum value (it will saturate).
So powered from 5V you can apply anything from -0.5V to +5.5V safely. That's basically the supply voltage plus one diode drop for the ESD protection diodes within the pin.
The ADC is just comparing two voltages. The VREF isn't used to power anything.


text:
What background do I need to have before starting Arduino?
Like: basics of electrical circuits, etc..
In order to go far in Arduino and electronics.

I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.
The end result is that he is the one showing me new stuff.
In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.
Good luck

It might help alot to have some basic knowledge about the law of Ohm etc. It may be that these tutorial books of Arduino will explain these thingss since I've never bought such a book.
When you've finished the book you might consider to continue learning from other example projects for Arduino on the internet and reading lots of datasheets. Try to open some applications and rebluid small parts of it with your Arduino.
Oh, and not to forget. Read the datasheet of the Arduino before experimenting your self so you won't blow it up. (How many volts can an Arduino recieve, how many amps etc)

You need a basic understanding of programming because you will need to program in C++.
You need basic computer literacy, but I bet you've got that if you are on this website.
You need some understanding of electronics, such as a High-School level textbook. You need to understand resistors, diodes, voltages, current etc. Otherwise you'll get very frustrated.

While knowing all this helps, this is not actually true. It is possible to, as they say, learn.

You need to learn some absolute basics about electronics so you don't fry your arduino. (Don't exceed the current limits on the i/o pins. How to use Ohm's Law to calculate current. How to tie inputs to ground with a resistor. How to tie inputs to +5 through a resistor.  How to estimate the total current load of your entire circuit to make sure it doesn't overload the +5 regulated power from the Arduino. Basic precautions against static electricity.)
Beyond that, it makes a great learning tool, and you should be able to learn as you go. Build the sample projects that are on the Arduino website.
You might want to buy a book on logic circuits. I read "The CMOS Cookbook" years ago, and it gave me a good strong grounding.
You'll also want to learn programming, since you need to use C or C++. Again, though, you can use the Arduino as a learning tool. Looking at the sketches from the website and modifying them will help you learn.

source: Stack Exchange

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

sort: votes


text:
How can I send serial over RF?
I've got the following:
#include <SoftwareSerial.h>

const int rx = -1;
const int tx = 4;

SoftwareSerial mySerial(rx, tx);

void setup()
{
  mySerial.begin(2400);
  pinMode(tx, OUTPUT);
}

void loop()
{
  if(mySerial.available())
  {
    String data = "Hello World";

    for(int k = 0; k < data.length(); k++ )
    {
      mySerial.write(0xAA);
      mySerial.write(data[k]);
    }

    mySerial.write(0xA9);
  }

  delay(1000);
}

Which I'm trying to send to to a RF transmitter module. It all compiles just fine, but am I forgetting something? And does pin 4 = physical pin 3?

You haven't told us what doesn't work! And how you are testing it? What is on the receiving end. PS arduin-pin-4 is indeed on attiny-pin-3, i.e. in most cores.

In your loop function you have:
if(mySerial.available())
{
  String data = "Hello World";

  for(int k = 0; k < data.length(); k++ )
  {
    mySerial.write(0xAA);
    mySerial.write(data[k]);
  }

  mySerial.write(0xA9);
}

The available() function returns the number of bytes available in the receive buffer. You say your module is a transmitter, so there will never be any data to receive (I can see the module doesn't even have a tx pin). Hence you will never transmit any data.
That said it's not a good idea to send data plain over wireless. It might work to some extent, but you'll likely get much more lost data. Look at the virtual wire library or google "manchester coding" if you wan't to roll your own.

First off, are you trying to send to the 433MHz transmitter? This will not work.
If you mean you are using the 433MHz transmitter to send data to a receiver, the VirtualWire.h library work.
If you are using another transmitter please add more info on the transmitter used in this project.
HumanHarddrive on youtube got a tutorial on the DX transmitter and receiver.
Tutorial

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


text:
Read temperature (DS18B20) with the ATTiny85
I'm trying to read the temperature of a DS18B20 with my ATTiny85 - but I'm getting rubbish data :D
I should have gotten ~22 degrees, but I'm getting 129! I followed this tutorial i found here, but maybe there is something funky with the ATTiny85?

Do you have a 4K7 Ohm pullup resistor between the DQ and 5v pins of the DS18B20?

Hi Omer! I'm using a 4k7 between DQ and 5v source. Does it need to be the 5v pin of the ds18b20? It's on my breadboard so just attached it to the power rail on the side, and not the same as the 5v pin for the sensor

it needs to be between the ds18b20's 5v and DQ.

Try to connect the VDD-pin of the sensor to +5V instead. This makes sampling easier.

I just rewired to my UNO and it works like a charm. I add a blinking led to the attiny, so I know its doing something :P it's running on 8mhz, does it matter?

I would suggest it has to be the clock speed or memory. Whilst you can program the ATTiny85 with the Arduino IDE, it will take up quite a lot of its flash memory. There is a thread on the Arduino form here which might help pinpointing the issue.
One solution is to write it in AVR-C but I don't know if there is an easy way (or a library) for the 1-wire. I think you'll have to do it with the 1-Wire library alone as the DallasTemperature library is too much for the 8Kb of memory you have to play with.
Please feedback any breakthroughs you make as this is a nice project, the ATTiny is an awesome little chip...

The code in the link that Jason94 attached to his question works perfectly with ATtiny85, I used it many times. No need to re-implement OneWire in pure AVR-C :)

Apologies for my assumptions. Just to clarify @Omer, you can run the ATtiny85 with both the 1wire and DallasTemperature libraries (and of course, the sketch provided in the original post)? It might be time I got the breadboard out again ;)

Yes. leaves almost no room for other code. Don't forget to make sure the ld.exe is fixed, to enable 8kb sketches (otherwise it will allow only 4kb) - https://github.com/TCWORLD/ATTinyCore/tree/master/PCREL%20Patch%20for%20GCC

Thanks for all the replies! I've found dozends of project where the ATTiny does one or the other, but not both... so maybe there are memory issues. Have some ATTiny84, but they have the same spec but more pins so would not do me any good... sad

@Jason94 was this issue solved?


text:
Understanding the ESP8266
I've received my ESP8266-01 and playing with it I discovered that with a baudrate of 74880 I can get the boot modes and `hy version, etc:
 ets Jan  8 2013,rst cause:1, boot mode:(3,0)
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 249
rf[112] : 00
rf[113] : 00
rf[114] : 01

SDK ver: 1.5.4.1(39cb9a32) compiled @ Jul  1 2016 20:04:35
phy ver: 972, pp ver: 10.1

With this baudrate I'm not able to check the AT commands. Then, when I switch to a baudrate of 115200 I am able to communicate with the ESP:
Ai-Thinker Technology Co. Ltd.
ready
AT
OK
AT+CWL
ERROR
AT+CWJAP?
No AP
OK
AT+CWLAP?
ERROR
AT+CWLAP
+CWLAP:(4,"bbox2-7f0d",-88,"00:1 ",1,-46,0)
+CWLAP:(0,"PROXIMUS_FON",-94,"06: ec:6b",1,-47,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-88,"0a: :ec:6b",1,-44,0)
+CWLAP:(3,"WiFi-2.4-BB3D-ext",-51,"00: 9a:38",1,-12,0)
+CWLAP:(3,"NGUYEN",-79,"e0:b ",11,-2,0)
+CWLAP:(0,"PROXIMUS_FON",-81,"42:6 ",11,0,0)
+CWLAP:(5,"PROXIMUS_AUTO_FON",-79,"42 ",11,0,0)
+CWLAP:(4,"WiFi-2.4-6858",-75,"4 e",11,1,0)
+CWLAP:(0,"PROXIMUS_FON",-89," ",11,-6,0)
OK

How is that possible that it has two different baudrates?
Thanks in advance,

How is that possible that it has two different baudrates?

Very simple. Exactly the same as the Arduino.
If you put:
Serial.begin(9600);

in your program then your sketch runs with the serial port at 9600 baud. However, just before then, the bootloader runs at 115200 baud for a few seconds listening for instructions from the PC.
There's no magic there.
You can even do it yourself:
Serial.begin(9600);
Serial.println("Hello at 9600 baud");
Serial.flush();
Serial.end();
Serial.begin(115200);
Serial.println("Hello at 115200 baud");
Serial.flush();
Serial.end();

The baud rate isn't fixed. It's whatever the firmware that is running at that precise moment deems it to be - whether that is the bootloader, the AT firmware, or your own custom sketch.


text:
When the Arduino is in reset mode are the digital pins high impedance?
I have an Arduino (Arduino A) hooked up to an external FRAM chip and I want to be able to pull the Arduino A's reset pin to ground to keep it in a constant reset state. Then I want to hook up another Arduino (Arduino B) up to the same lines going from Arduino A to the external FRAM chip and pull data off of the FRAM chip.
I am worried that when I hook Arduino B to the lines running between the FRAM and Arduino A that it will damage Arduino A. If the digital pins are in a high impedance state while I do this though, then it should be fine. I can't find the necessary documentation to figure this out though.
All Arduinos involved are Uno Rev 3s.
Any help would be appreciated, thanks!

I'd suggest adding some resistors between the arduino outputs, and the FRAM IC. So that in the case that Arduino A is not reset (broken connection e.g.) you don't get any shorts (i.e. one arduino outputs a HIGH, while the other outputs a LOW).

From the ATMEGAxx8 datasheet...

11.1 Resetting the AVR
... The I/O ports of the AVR are immediately reset to their initial state
when a reset source goes active. This does not require any clock
source to be running.

(bold added)
Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of 0, corresponding to high impedance input.
...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the RESET pin goes low.
Caveats:

The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).

Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.

The MISO pin can inadvertently become an output while RESET is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI & SCK lines. This process is described in App Note AVR910.

Thank you for explaining the whole reasoning path from datasheet to initial values of the registers. That helps a bunch!

But note that holding a AVR in reset also means that it will be listening for programming signals on some of its pins.

My reading of this is that there is you must hold the RESET pin low during power up to enter serial downloading mode. - no, when I am programming using ICSP, you can enter ICSP programming from any reset, not just power-on reset.

Above commentors are correct! Despite what the data sheet says, the MISO line does become an output if RESET is asserted and then the programming enable command is sent! Answer updated to reflect. Great catch for a very obscure corner case.


text:
Why does the Pro Mini 5 v and 3.3 v version have different clock frequencies?
It looks like the 5 volt version used the 16MHz external crystal while the 3.3V one uses the 8MHz crystal. I need to use 3.3v as my operating voltage.
Can I just remove the linear regulator and bring in 3.3V. I still have to select the 5V 16MHz version in the Arduino IDE, right?
https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

Don't make it work at 5V @16MHz, since it is out of the safe operating area

The ATMega328p is not rated to operate at 16 MHz on a 3.3v supply.
In practice it may sometimes work, but cannot be considered reliable.
The data sheet will show the actual clock rate vs. voltage tradeoffs, so there might be an intermediate value that is workable for you.
The Arduino toolchain needs to know the CPU clock frequency for the serial baud rates, timing delay code, and any time-based use of the timer peripherals to come out right.
There is a special case where if the configured clock rate and the actual clock rate differ by a factor of two, you may be able to cover that by selecting a similarly wrong baud rate - however, the baud rate in the bootloader was set in comparison to the expected clock frequency when it was compiled before flashing, and the baud rate expected of the bootloader is set in the boards file, so less readily changed than it is in something like the serial monitor.

And if I wanted to use the same arduino board, can I simply replace the crystal with an 8MHz one and bypass the linear regulator with my own 3.3V supply? I know it seems like a lot of work... lol but i have spare parts around.

Some components on the board may be expecting 5v (LEDs immediately springs to mind); you may also need to change the fuse settings - http://www.engbedded.com/fusecalc/ - in fact, if clock accuracy isn't terribly important, then you can change the fuse to use the internal 8mhz clock, save yourself some soldering.

PS - setting fuses is advanced black magic - it's easy to brick your Arduino that way (as I did) if you get it wrong.

Changing the fuses isn't necessary when changing the crystal. What you do need to change is the bootloader to the 8MHz version.

If the brown out detector is already either disabled or set at 2.7v or below that may be the case (seems to be in the boards.txt).  If it is set at 4.3v there would be a problem.  Also if the "3.3v" is really two AA cells that will drain to a lower voltage in operation, the chip might be fine but the 2.7v BOD will shorten the usable life.


text:
Why does "!=LOW" != "HIGH"?
I'm learning about accessing ports directly on the ATMEGA 328 using an Arduino Uno. The program sets up pin 13 as an output and pin 2 as an input. I then enable the pull up resistor on pin 2.
I read Pin 2 and set the LED high or low depending on if pin 2 is high or low.
Why is it that I cannot seem to use == HIGH in my if statement instead of != LOW?
void setup() {
  MCUCR &= ~(1 << 4); //disables pull-up disable (redundant as default is off)
  DDRB |= (1 << 5); //sets pin 13 (B5 on ATMEGA 328) as output
  DDRD &= ~(1 << 2); //sets pin 2 (D2 on ATMEGA 328) as input (redundant as default is input)
  PORTD |= (1 << 2); //since it's an input sets pull-up resistor ON
  PORTB &= ~(1 << 5); //sets pin 13 (B5 on ATMEGA 328) as LOW

}

void loop() {
  if ((PIND & (1 << 2)) != LOW) PORTB |= (1 << 5); //sets pin 13 (B5 on ATMEGA 328) as HIGH
  else PORTB &= ~(1 << 5); //sets pin 13 (B5 on ATMEGA 328) as LOW
   delay(100);

}

Because
((PIND & (1 << 2)) != LOW)

means exactly
(PIND & 4) != 0

and that is true if PIND is 4, 5, 6, 7, 12, 13, ... (any number having 4 in it binary), so it yelds
4 != 0

Which is definitively not equal
4 == 1

BTW: in C any integer != 0 is true and 0 is false, so you can as well write:
if (PIND & (1 << 2)) PORTB |= (1 << 5); //sets pin 13 (B5 on ATMEGA 328) as HIGH

if ((PIND & (1 << 2)) != LOW) PORTB |= (1 << 5); //sets pin 13 (B5 on ATMEGA 328) as HIGH
  else PORTB &= ~(1 << 5); //sets pin 13 (B5 on ATMEGA 328) as LOW

PIND & (1<<2) will return a value of either (1<<2) if PD.2 is high, or 0 if PD.2 is low.
So it basically says that if PD2 is high, set PB5; otherwise, clear PB5.enter code here

Thanks, Danny. Yeah I should have known... dork move on my part.


text:
Arduino stacking wifi and gsm shield
I'm fairly new to this and I need some help before I buy anything...
If I understand correctly I can buy an arduino, couple of shields and just stack them one onto another if they are compatible...
I'll be doing some work with an arduino and I would need both WiFi and GSM shields but I'm not sure if they're compatible... On the arduino.cc I saw that they both use pin 7 (GSM as modem reset and WiFi as "handshake")
Is there any way I can use both of the shields even though they use the same pin?
Thanks

You can still use both of them although you'll need to buy another piece to make it work.
This is called the Go-Between Shield and it basically lets you re-route a pin to a different one.  You will need to change the pin number in your code to the one you re-assign that signal to but it will still work.
The signals you listed that go on that pin are very incompatible, as in if you try to do it, you'll have problems.  Every time your Wifi shield will try to connect to something, your GSM shield will reset.

If you will be using Wi-Fi, instead of buying a Wi-Fi shield and a GSM shield, simply buy an Arduino Yún (which will substitute the Arduino and WiFi shield) and connect the GSM shield to it.
From How to use the Arduino GSM shield with Arduino Leonardo, Arduino Yun, and Arduino Mega, it shows you how to connect the Arduino Yún with a GSM shield and to use them without any problem with the help of jumper.

A classic Arduino is indeed a bad fit for either WiFi or GSM, and a terribly bad fit for both at once.  But while the Yun is a step in a better direction there are now much more cost effective solutions of similar concept available as well.


text:
Problem loading sketch to Leonardo
Today I got Arduino Leonardo to replace my Uno. I've tried running one of sketches I use on the Uno, but with no luck. When I start the upload, RX LED on the Leonardo flashes few times, and after several seconds, L LED pulsates and I get this message:
avrdude: ser_open(): can't open device "\\.\COM9": The system cannot find the file specified.

avrdude: ser_send(): write error: sorry no info avail

I've checked in Device Manager, where it says that Arduino Leonardo is on COM3, and COM3 is also set in Arduino IDE.
However, when I change COM port to 9 in Device Manager and also in Arduino IDE and then try to upload the sketch, things start to roll out like above, but this time IDE freezes for 5-10 mins on "Uploading..." part, and finally unfreezes with this message:
Found programmer: Id = "B¨J"; type =
    Software Version =
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

Several more infos:
- OS: Win7 64-bit
- Arduino IDE: 1.0.5-r2
- Other serial devices: Only Bluetooth that I've manually assigned to COM200, to avoid possible conflicts.

Try deleting all the com ports in the device manager, uninstall Arduino IDE and download and install the latest version

You've selected leonardo in the boards menu correct?

Per imjosh's suggestion, I've installed IDE version 1.5.7 BETA and that solved my problem.
Thanks!

I had my Olimexino 32u4 connected to Axagon USB 3.0 hub and had problems not only to flash but also to find a board. Then plugged it directly to USB 2.0 port on my laptop and it worked. If you have problems with board communicating with PC try to change USB port it is connected to and also try different USB cables.

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


text:
Power supply voltage confusion
I just ran into this article: Arduino: What adapter?.
It says that the external power supply should be 9-12V. That really surprises me, since my Arduino Uno can also be powered via USB, which is 5V.
Later he talks about a 9V pin. But I can only see a 5V and 3.3V pin on mine. Is he talking about a different version of Arduino?
Judging from the picture, his Arduino looks slightly different from my Arduino Uno R3, but I can't tell which version is on the picture.

The board has a voltage regulator which converts 9-12V to the 5V that the chip uses.
Why does it need 9V if the board works at 5V? Well, it doesn't need 9 exactly, but it needs something greater than 5. The reason for this is that the regulator has whats called a dropout voltage.
Looking at the schematic of the Uno we see it uses a NCP1117, which has a dropout of 1.2V. So the minimum voltage you can give it to get 5V is 6.2.
The 9V pin is the Vin pin which is at the same level as the input voltage (before converting).

@MadsSkjern updated my answer with that explanation

A voltage regulator creates a lower stable voltage by burning away the extra volts (turning them into heat). A voltage regulator always has to burn away some voltage to work. So if you only provide 5V to VIN, the voltage regulator will only output e.g. 3.8V (also not very stable).

The power protection circuitry drops a few tenths of volts as well, pushing the minimum to around 6.6V or so.

And the third part of your question: It is possible to bypass the voltage regulator and feed REGULATED 5 volts directly to the 5V pin.
That's how the Arduino is powered using USB. The USB power is already regulated 5V, and is fed directly to the 5V pin.
Beware of doing this yourself however. You better be certain the 5V you're feeding in is a clean, filtered and regulated 5V. If it's not you run the risk of destroying your Arduino (and possibly anything connected to it's 5V lines.)


text:
PIR sensor issues
The code works but there was a problem on the output. When the PIR detect the presence of motion the output (pin 12) would not give an instant HIGH state on the output, it has more than 10 sec delay to provide a HIGH state on PIN 12. HOw can I lessen the time that once the PIR sensors detected motion it would give a HIGH state to the output (pin 12)? please help me regarding this problem! Thanks
 void setup()
{
    //Serial.begin(9600);
}

void loop()
{
    pinMode(13,OUTPUT);//output 1
    pinMode(12,OUTPUT);//output 2
    int pirOuts=11;pinMode(pirOuts,INPUT); /*PIR sensor 1*/
    int pirOut = 10;pinMode(pirOut,INPUT); /*PIR sensor 2*/

    if (digitalRead(pirOut) || digitalRead(pirOuts) == HIGH){
        digitalWrite(12,HIGH);
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else if (digitalRead(pirOut)||digitalRead(pirOuts)==LOW){
        digitalWrite(12,LOW);
        tone(13,50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else
    {}
}

"digitalRead(pirOut) || digitalRead(pirOuts) == HIGH" is actually "digitalRead(pirOut) == HIGH || digitalRead(pirOuts) == HIGH" and "digitalRead(pirOut) || digitalRead(pirOuts)==LOW" is actually "digitalRead(pirOut)==HIGH || digitalRead(pirOuts)==LOW". Also pinMode(), if fixed, are often done once in the setup().

Check to make sure your PIR sensor reads high when triggered. Most of them will trigger high, but I've seen a few that will trigger low. Also, some PIR sensors have potentiometers to control delay. Some delay the trigger, some delay the reset between triggers.
The delay may not be coming from the Arduino, but from the sensor itself.
Note, the first if statement is formatted incorrectly:
if (digitalRead(pirOut) || digitalRead(pirOuts) == HIGH)

should probably be:
if (digitalRead(pirOut) == HIGH || digitalRead(pirOuts) == HIGH)

It works the way you coded it because you're doing a logical OR of the two input values (which will be 0 or 1) then comparing the result to HIGH. As I said it will work, but probably not best practice.
Also, in your code, I don't understand why you're using else if instead of just else.
else if (digitalRead(pirOut)||digitalRead(pirOuts)==LOW){

Basically, your first if statement has to be false (so both pirOut and pirOuts must both be low) so your if statement as written will always be true.
If your intent was to execute that code when either pirOut or pirOuts goes LOW, then it should be a separate if statement, not an else if.


text:
RGBs, photoresistors, and delays
I am having a little trouble with a program of mine. My circuit consists of (mainly) an arduino UNO, two RGB LEDs, and a photoresistor. My current code(programmed in c#) operates the hardware as so: When the lights in the room are on, the two LEDs alternate blue/off once per second in a loop. When the lights are off, or the photoresistor is not sensing any light, both LEDs turn on, and stay on, red.
My code:
int prPin = A0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(prPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
  int prVal = analogRead(prPin);
  Serial.write(prVal);
    if(prVal>450)
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,LOW);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);
      delay(1000);
      digitalWrite(5,LOW);
      digitalWrite(6,HIGH);
      digitalWrite(7,HIGH);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,HIGH);
      delay(1000);
    }
    else
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,LOW);
      delay(10);
    }
}

The problem I am having is when the lights turn off, the LEDs will not operate according to the "else" statement/loop until it finishes going through the "if" statement/loop.
Any suggestions or answers are appreciated. I'm an open book, so I'll take anything you guys give me.

Stop delaying. Use a state machine.

How to do multiple things at once. Also State machines.

Instead of the two delays of one second, have the program check if the current time is an even or odd number of seconds.
int prPin = A0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(prPin,INPUT);
  Serial.begin(9600);
}

void loop()
{
    int prVal = analogRead(prPin);
    Serial.write(prVal);
    if(prVal>450)
    {
      if( (millis()/1000)%2 == 0 ) // check if even or odd number of seconds have passes since the program started
      {
        digitalWrite(5,HIGH);
        digitalWrite(6,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,LOW);
        digitalWrite(9,HIGH);
        digitalWrite(10,HIGH);
      }
      else
      {
        digitalWrite(5,LOW);
        digitalWrite(6,HIGH);
        digitalWrite(7,HIGH);
        digitalWrite(8,HIGH);
        digitalWrite(9,HIGH);
        digitalWrite(10,HIGH);
      }
    }
    else
    {
      digitalWrite(5,HIGH);
      digitalWrite(6,HIGH);
      digitalWrite(7,LOW);
      digitalWrite(8,HIGH);
      digitalWrite(9,HIGH);
      digitalWrite(10,LOW);
      delay(10);
    }
}


text:
Programming a motor with an RGB
Please see the comments section if confused.
I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V.
I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.
void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
////  pinMode(2,OUTPUT); //IB2
////  pinMode(3,OUTPUT); //IA2
//  pinMode(4,OUTPUT); //RGB
//  pinMode(5,OUTPUT); //RGB
//  pinMode(6,OUTPUT); //RGB
//  pinMode(A0,INPUT); //lMotor
////  pinMode(A1,INPUT); //rMotor
//  Serial.begin(9600);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);

//  int lMotor = analogRead(A0);
//  Serial.write(lMotor);
////  int lMotor = analogRead(A1);
////  Serial.write(lMotor);
//
//  if (lMotor>10)
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,HIGH);
//    digitalWrite(6,LOW);
//  }
//  else
//  {
//    digitalWrite(4,HIGH);
//    digitalWrite(5,LOW);
//    digitalWrite(6,HIGH);
//  }
}

And here's this:
void setup ()
{
  pinMode(0,OUTPUT);
  pinMode(1,OUTPUT);
}

void loop ()
{
  digitalWrite(0,HIGH);
  delay(1000);
  digitalWrite(0,LOW);
  delay(1000);
}

What do I need to do? Should I use a "while" loop? If so, how?
Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right.
Any help is appreciated, even if it doesn't answer all of my questions.
Thank you.

You'll have to investigate what "component video" signals should look like. It is too simple to assume you can just drive a pin high and expect the screen to color accordingly.

@jippie I am not changing anything on screen, I am turning an RGB LED on. (Everything is connected to the arduino via a breadboard.)

You haven't actually told us what's not working. Is the motor not turning? At the top you say you have the motor connected to pins 0 and 1 and 5 V and ground! How? What's the relay doing? Can you hear the relay clicking? We'll need a schematic or a photo of a sketch. Note that the Arduino pins can't provide enough current to drive a typical little DC motor.

@transistor The motor turns with the simple code (the second one in my post); my problem is basically I don't know what to do to make the RGB turn on and change colors based on the current state of the motor (on or off). Everything works properly until I add something to the code (because someone, or some site, suggested that's what I should do); by "not working properly" I mean the entire circuit does nothing. Absolutely nothing.

If my response below doesn't answer the question can you edit the question to clearly show the code that works and the code that doesn't and explain what works - e.g., the motor works but the LEDs don't.

I forgot to say, the way you've set up the first code example you turn the motor on for a second, then turn in off for a second and then updated the LEDs. The LEDs are only updated when the motor is off so they'll never change.

Try this:
void setup ()
{
  pinMode(0,OUTPUT); //IB1
  pinMode(1,OUTPUT); //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT); //RGB red
  pinMode(5,OUTPUT); //RGB green
  pinMode(6,OUTPUT); //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  digitalWrite(0,motorOn);
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
  delay(1000);             // wait
  motorOn = !motorOn;      // toggle the status of the motor.
}

The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:
void setup ()
{
  pinMode(0,OUTPUT);   //IB1
  pinMode(1,OUTPUT);   //IA1
//  pinMode(2,OUTPUT); //IB2
//  pinMode(3,OUTPUT); //IA2
  pinMode(4,OUTPUT);   //RGB red
  pinMode(5,OUTPUT);   //RGB green
  pinMode(6,OUTPUT);   //RGB blue
  boolean motorOn = false;
}

void loop ()
{
  motorOn = false;
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(1000);             // wait
  motorOn = true;          // toggle the status of the motor.
  digitalWrite(0,motorOn);
  updateLEDs();            // update the LED status
  delay(750);              // wait a different time
}

void updateLEDs(){
  // This routine updates the LEDs based on status of motorOn.
  if(motorOn) {
    digitalWrite(4,HIGH);  // red on
    digitalWrite(5,LOW);   // green off
    digitalWrite(6,LOW);   // blue off
  }
    digitalWrite(4,LOW);   // red off
    digitalWrite(5,HIGH);  // green on
    digitalWrite(6,LOW);   // blue off
  }
}


text:
Does Nano not get sufficient power via USB?
I have an Uno, and I can play all I want with it, just using a USB cable.
Then I got two Nano clones, and they both show the same behavior:
When I connect it to the USB cable (which leads to my PC) it blinks a few times, then seemingly does nothing. I am also not able to connect to it via the Arduino IDE.
If I then connect an external power source to Vin and Gnd, it wakes up and blinks forever, and I am able to connect to it.
Is this just because I got a cheap clone? Or is this really the accepted / expected behavior?

Should work. Place a say 100 Ohm resistor across USB power leads (about 50 mA load). What Voltage? Remove R :-) | What is USB input voltage to Nano loaded? What brand is clone?

I have a few clones but have not seen this behaviour so I guess it could be one of three things (in order of most likely to least):

They have a fault related to taking power from the USB connector.
The USB lead is not able to supply enough power ie. it is cheap and extremely thin and cannot carry much current. Have you already tried other cables?
Your USB port cannot supply enough power. Given that the spec says 500mA from a USB 2 port, this seems unlikely unless the port is faulty. Have you tried other ports / another PC?

What is the reference of the board that you used ?

@MAC: Are you asking me? If so, sorry, but I don't understand the question.

@Crispy: Using another port made no difference. But using a different USB cable did. Crazy :) Thanks!

To answer your title question, My Nanos run at significantly less than the 500 mA you can draw from a normal USB port, so unless you have a cable problem it should be getting enough, yes.
One thing I have learned about cables is that your mileage may vary.  For the Pi, it is nice enough to show me a lightning bolt on-screen when it isn't getting enough, and swapping the cable fixes it 99.9% of the time.
Arduinos simply display odd behavior like this one.
I always suspect power supply first.
So first, try changing cables.  Then if that doesn't help try changing Arduinos and see if the problem follows the Arduino.
Good luck!


text:
What does it mean in I2C, "NACK received"?
I am reading about I2C. On this site:
http://playground.arduino.cc/Main/WireLibraryDetailedReference#endTransmission
It says that endTransmission() can return one of the following status codes:

0: Successful send.
1: Send buffer too large for the twi buffer. This should not happen, as the TWI buffer length set in twi.h is equivalent to the send buffer length set in Wire.h.
2: Address was sent and a NACK received. This is an issue, and the master should send a STOP condition.
3: Data was sent and a NACK received. This means the slave has no more to send. The master can send a STOP condition, or a repeated START.
4: Another twi error took place (eg, the master lost bus arbitration).

If I attach nothing to my Arduino (or with pull-up resistors to both SDA/SCL), I always get status 2. But how can a NACK (or anything) be received when there is nothing to communicate with? Does it mean something else?
Here is my example code
#include "Wire.h"
void setup() {
  Serial.begin(9600);
  Wire.begin();
}
void loop()  {
  Wire.beginTransmission(42);
  Wire.write(0);
  byte status = Wire.endTransmission();
  Serial.println(status); // always prints 2
}

A NACK is signaled by an acknowledgement slot in which SDA remains high while SCL cycles under control of the master.
Since high is the un-driven state of the pulled-up bus, in the absence of a peripheral at the selected address to positively acknowledge by pulling it down, a NACK condition will passively result.

Could you please elaborate more? You mean that peripheral is not connected? How about was able to get data for a while, then it stopped working and keep return 0x02?

Anything that means a peripheral fails to respond can cause this - no peripheral, broken traces or wires, wrong address, noise making the address look wrong, weak pullups distorting the data, absurdly strong pullups distorting the signalling, bad power, buggy software or silicon design in the peripheral, even mismatching support of extensions like clock stretching.


text:
What is this temperature sensor module? (LM358, 103)
I got this sensor some time ago because I wanted to play with measuring the temperature. I don't remember how I got it or if it has a name.
I've Googled around, and obviously is has the following

LM358 op amp
"103" thermistor

When googling for help I mostly find stuff about how to use the LM358 which is way above my skill level.
What is this and how do use it? :)

Hard to tell without a schematic. I assume the LM358 is being used as a unity-gain non-inverting buffer. The "103" means "10KΩ" (1, 0, 3x0). Without knowing what the thermistor's exact parameters are you can't make accurate measurements with it.

"103" is standard resistor (and other component) numbering - the first two digits specify a value and the third is a power-of-ten multiplier:
1 0 3 = 10 * 10^3 = 10K

4 7 2 = 47 * 10^2 = 4.7K

For devices that are typically measured in thousandths, millionths or smaller (like a capacitor) then the third digit is a minus power-of-ten:
1 0 6 = 10 * 10^-6 = 1u

That black disc labelled '103' is a thermistor - a temperature-controlled resistor. It is most likely NTC, or negative-temperature coeffiecient, thus the resistance decreases as the temperature increases. This is contrary to typical physics where an increase in the temperature of a generic conductive material results in an increase in its electrical resistance.
The LM358 is included to buffer the thermistor from the Arduino/microcontroller. In simple terms, this means that the effective resistance of the analogue input pin does not have to be taken into consideration when converting the voltage measured to into a value for the temperature.
Without a better picture of both sides of the board, or better yet a circuit diagram, it is not possible to determine what the voltage on pin S will be for a given temperature. However, it seems that the thermistor is in series with another 10K resistor (R3, marked '103' of course) such that an increase in temperature results in an increase in voltage. At roughly 20 degrees Celsius (it depends on the manufacturer and their specifications) the resistance of the thermistor will be 10K, thus the voltage at S will be Vcc/2. Calculating the voltage for different temperatures requires you to know the temperature coefficient, which can be found from the datasheet or by measuring the resistance at various known temperatures and plugging those values into an equation.

I am working on it, and I will return later and (I expect) approve your answer :)

You are totally wrong about  “For devices that are typically measured in thousandths, millionths or smaller (like a capacitor) then the third digit is a minus power-of-ten”.  Cap numbers are in picofarads, ie in multiples of 10^-12 Farads.  A 106 cap is 10·10^6 pF, or 10 million pF, or 10 μF. See elecraft.com/Apps/caps.htm.  Inductor text gives microhenries.  Eg, a 102 inductor is 1000 μH, or 1 mH.  See eg how-to.wikia.com

@jwpat7 what was I thinking?? Thanks, Brain. I'll edit when I can, thank you.

Connect VCC to +5V, GND to GND, then S to A0.
Do an analogRead() of A0 and then convert that to temperature using the Steinhart-Hart equation, inserting the three values A B and C which you don't know because you have no documentation for the thermistor.

Back-calculating the B-parameter is achievable with an ohmeter and a bowl of ice water. That should be more than enough to give a reasonable accuracy; sometimes manufacturers only state the Beta, rather than the A-B-C values.


text:
actual use of noTone() in arduino
What is the use of noTone() function as the duration for which the note must be played can be specified using the third argument of note() function.

So that you can terminate the output prematurely, e.g. during an interrupt.


text:
How to append float value of into a string ?
I have a float variable lng = 33.785469 and lat = 78.126548. Now can I convert them to String and append in a String variable "my_location" as "your location is \nlng = 33.785469 \nlat = 78.126548". I was trying to do this with
    char charVal[5];               //temporarily holds data from vals
    String stringVal = "";     //data on buff is copied to this string

    dtostrf(lng , 4, 2, charVal);  //4 is mininum width, 2 is precision; float value is copied onto buff
    //convert chararray to string
    for(int i=0;i<sizeof(charVal);i++)
    {
    stringVal+=charVal[i];
    }
    GPS_string = GPS_string + "Car location: \nlat:" + stringVal;
    stringVal = "";

and it given me an error :
error: cannot convert 'String' to 'double' for argument '1' to 'char* dtostrf(double, signed char, unsigned char,

This has been answered in the previous question but I can repeat it here:
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

An alternative is to use dtostrf() as in your snippet:
void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  const int BUF_MAX = 64;
  char buf[BUF_MAX];
  const int VAL_MAX = 16;
  char val[VAL_MAX];
  strcpy_P(buf, (const char*) F("your location is \nlat:"));
  dtostrf(latitude, 8, 6, val);
  strcat(buf, val);
  strcat_P(buf, (const char*) F("\nlong:"));
  dtostrf(longitude, 8, 6, val);
  strcat(buf, val);
  ...
}

Cheers!


text:
append a String on ArduinoJson Object value
I've a json string request coming from server and I convert it into json object
  StaticJsonBuffer<500> jsonStaticBuffer;
  JsonObject& root = jsonStaticBuffer.parseObject(String(msg));
  String reqId;
  String reqData;
  root["requestid"].printTo(reqId);
  root["data"].printTo(reqData);

I need to populate another char json string initiated at the beginning
const char response[] = "{\"response\": {\"requestid\":, \"data\":}}";

such that I need to write requestid into the response::requestid and data into response::data + ACK/NAK . here is how i've tried;
  DynamicJsonBuffer jsonDynResponse;
  JsonObject& jsonResponse = jsonDynResponse.parseObject(response);
  String out;
  if (ACK) {
      jsonResponse["response"]["requestid"] = root["requestid"];
      jsonResponse["response"]["data"] = root["data"] + " ACK"; //THIS DOESN'T WORKS
      jsonResponse.printTo(out);
  } else {
      jsonResponse["response"]["requestid"] = reqId;
      jsonResponse["response"]["data"] = reqData + " NAK";
      jsonResponse.printTo(out);
  }

I know this will definitely not work root["data"] + " ACK" because we can't combine const char with String. But this reqData + " NAK"; resulted in "\"data\" NAK"". How can I concate root["data"] into another String ?
Thank you in advance :)

String(root["data"]) + " ACK"?

Tried that already, I get exit status 1 call of overloaded 'String(ArduinoJson::Internals::JsonObjectSubscript<const char*>)' is ambiguous

perhaps you need to create a String variable, do things with it, and then jsonResponse["response"]["data"] = whateverYourStringVariableIsCalled;

The things that I want to do with the string is append ACK/NAK on whatever is in root["data"]. Which I am not able to do.

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


text:
Assign and control Digital pin from String
Here is modified version of Blink example
#define D8  13

String p = "D8";

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(D8, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  byte pin[2];
  p.getBytes(pin, sizeof(pin));

  digitalWrite(D8, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(D8, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

D8 defined above is a byte of length 2. So LED turns on/off if I mention D8 on digitalWrite(D8, HIGH). Similarly I am getting the same byte D8 from String p = "D8", and converting it into byte of length 2, but assigning pin to digitalWrite(pin, HIGH/LOW) doesn't works. Has anyone tried something similar before ? any help would be appreciated :)

digitalWrite(pin, value) is expecting an unsigned 8 bit integer for the pin parameter ......... it is actually unclear what you are trying to do ....... also,  doesn't works does not describe what actually happens .... if you got an error, then why did you not say anything about it?

C and C++ programs get compiled in multiple passes through various programs/steps. One of the first is the C Preprocessor, which handles the #define preprocessor directive.
It's basically a big find/replace function. After the preprocessor is done, anywhere you had D8 outside of a string literal, would have the value 13. It's not a variable or a string -- it's simply the number 13.
But the String p, which has content "D8" doesn't get replaced by the #define directive because it's part of a string, and the preprocessor doesn't modify strings in that way.
Also, p converted to a byte array of length 2 does not have anything like 13 as the value. It has 0x44 and 0x38 (or, in decimal, 68 (ASCII 'D') and 56 (ASCII '8')). Disregarding that digitalWrite() and pinMode() do not accept byte arrays, only bytes, you are passing in a byte that doesn't represent pin 13.
If you want to assign the pin via a string, then you would need to use programming to examine the string and pick the right byte value, and each possible value would have to be explicitly enumerated and checked for.


text:
ACS712 Not working correctly with Arduino
So I have the basic setup ready with one relay that is controlling a 200W bulb. The Phase of this bulb is passed through a current sensor acs712. While running a simple analog read example sketch, I get output 511 from ADC, which is as expected. Then I subtracted this 511 from my measurement and observed the results while turning on/off the bulb.
int sensorValue;

void setup()
{
  Serial.begin(9600);  // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println((511-sensorValue), DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

Here is the output graph;

While the bulb is off, the current remains 0, but when I turn on the bulb, the voltage fluctuates over positive and negative side. Why is the sensor showing this behavior ?, I am not using any additional capacitor for noise reduction. Do I need to ? but I guess this is not noise. Is it ?

You are seeing that because that is what the current is doing. It's called AC - Alternating Current. It's what the mains current is.
To work with AC you have to rapidly sample over a short period to get the maximum and minimum values. Subtract one from the other and that gives you the peak-to-peak current. You can then use that to calculate the RMS current which is what you are (most likely) interested in.

http://whatis.techtarget.com/definition/root-mean-square-RMS

oh now I got that... Thank you so much :),
got the code from
http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-arduino-ac-current-tutorial/
and its working now

I'm not sure if that is the case here. Since it's AC the current would also be negative half the time, and we are not seeing this here. The acs712 seems to be made for AC, though I couldn't understand enough of the datasheet to say anything useful.

@Gerben It is negative, but around a 2.5V DC offset. That's the 511 reading  Anum mentions.

Ahhh. Silly me. (-:


text:
Any disadvantages on using Particle Photon over an Arduino?
It seems to me like Photon is 'winning' on the price front and ease of programming and of course the cheap wifi connection.
I realize the cloud portion (even the local cloud server) could be considered a disadvantage, but what about things like ability to drive dc/stepper motors or some exotic sensor? Perhaps not enough analog and/or digital pins? etc..
One disadvantage I can think of is the lack of resources whereas the Arduino has a ton of references online with working with all kinds of motors and sensors.

It's horses for courses. The Photon fulfils a different need to the Arduino. Use the device that best fits what you want to achieve.

Arduino has never been inexpensive; once you are willing to consider alternatives there are many having more capability, and some selling for less than half of the price of the photon.  For a one-off, effort is a substantial consideration, while for a project you will use in volume, how the price decreases as you start buying in volume matters a lot - Arduino almost wins there, as you can use the inexpensive bare chips on a custom design, while with photon you may have trouble cutting out the "particle" middlemen.

Photon advantages:
The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.
A photon  about 1/4 the size of an Arduino UNO
Photon is much cheaper than arduinos
Arduino UNO advantages:
Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt
Arduino has many resources while Photons don't since Photons are fairly new
Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)
UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital
UNOs have female pins, so no breadboards are necessary for small, simple projects.
Photons have male pins, and they need to be plugged into a breadboard or soldered.
Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!

"Photons need to be connected to wifi and the cloud to run code". This isn't completely correct. Photons need internet for code to be uploaded to it, but other than that, they can run without internet (if your code doesn't require internet, but in that case you can just use an Arduino).

Thanks for pointing that out. I will edit my answer. I would also like to say that it IS possible to flash code to an Photon without wifi, but it is a highly complicated process.

Your new edit also includes some more information of USB flashing a Photon, which indeed is really complicated. Good addition.


text:
how much current does Arduino Nano draw when only using 8 digital pins?
I want to connect an Arduino Nano to an Intel Minnowboard Max (it's like a Raspberry Pi). I know Arduino can draw up to 500 mA current through the USB connection. Since I already need the USB to communicate the Arduino with the Minnowboard, it would be nice to not power the Arduino separately as well. However, I wouldn't want the current the Arduino draws from the Minnowboard to overheat Minnowboard's 2.5A 12V power supply.
I only have 8 buttons connected to the digital pins of the Arduino Nano. Nano sends the state of the buttons to the Minnowboard via USB (serial). How much current is Arduino drawing in this case?

I would guess around 50 mA, to power the processor and the USB converter. I notice that this question suggests more like 20 mA.
To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.


text:
Wrong calculation UNO
I've a joystick and a servo connected to my UNO, but for some reason my calculations keep on being wrong? I'm trying to calculate how the rotation should be of my servo (Tower Pro 9g, max value of 180 I think) with my Joystick (Keyes_SJoys, max value of 1023 on any axis) and example would be:
y = 500;
servo.write(y * 180 / 1023); // should equal to 87.97, but in reality it's 24?
#include <Servo.h>

Servo servo;
int d2 = 2;
int a0 = 0;

void setup() {
  Serial.begin(9600);
  servo.attach(d2);
}

void loop() {
  int y = analogRead(a0);
  Serial.print("y: "); Serial.println(y);

  servo.write(y * 180 / 1023);
  Serial.println(y * 180 / 1023);

  delay(100);
}

PS. It's a Robotale UNO; I don't know if that makes any difference or not, but.

What you are experiencing is a common pitfall.
You are probably expecting floating point calculations, but what you are writing are only integer ones.
Try with:  y * 180. / 1023.   (notice the dots).
This will work only with constants.
To make it work with anything, use a cast:  y * 180 / (float) 1023
Happy hacking.

Awesome, this worked, thanks! (Just had to cast evertyhing)

Please select the answer as correct, if it helped.

One cast should be sufficient.

Oh, yea... But for some reason casting didn't work on 1023, but it did on 180. Weird.

The reason you're getting completely the wrong value (not just losing the decimal portion) is because of a problem called integer overflow.
Because the Arduino is an 8-bit device the default integer size is double that.  That means that an integer value can store 16 bits, and when signed that's -32768 to 32767.
Any calculations, unless you specify otherwise, have to fit into that range.  If you take your calculation step by step you will see how it works:
500 * 180 = 90,000

Represented in Hexadecimal (for ease of demonstration) 90,000 is 0x15F90.  That is 17 bits (4 bits per digit, the left hand is just one bit since it's only the value 1), and 17 is more than the maximum 16 allowed.  So we have to "overflow" that value and discard the lefthand-most digit to keep it at 16 bits.  So we end up with 0x5F90.
0x5F90 in decimal is 24464.  Now we divide that by 1023 and we get:
24464 / 1023 = 23.914

Because it's integers we have no decimal portion of it, so that just ends up as the 23 that you are seeing.
Solutions?  Change the data type.
As @IgorStoppa has pointed out you can use floating point values which gives you big values and the decimal portion.  As long as one value in your sum is floating point all the values will be. This is known as promotion.  There's numerous ways you can force floating values:

Represent your literals as a floating point value - that means adding a decimal place. You could have (as Igor shows) things like 1023., but I find that a little obscure.  It's better to explicitly show a decimal value since it's obvious what it is then, such as y * 180.0 / 1023.0.
Use a floating point literal suffix.  You can add certain letters after a number to describe what that number is.  f is for floating point: y * 180f / 1023f.

Floating point is quite heavy weight though and can cause your program to get bigger than you'd like.  If you're not interested in the decimal portion you can instead use long variables.  The best way to do that is with the long literal suffix L:  y * 180L / 1023L
Promotion means that all the variables are promoted to the size of the biggest variable (not greatest value, the variable with the largest storage space).  Long and Float are both 32 bits in size, so using either of those will force the other values to both be promoted to equivalent types.


text:
Beginner here. Which arduino revision should i buy?
I have no idea what difference is there between the revisions and how it affects me. I have a pdf and this pic was in there:

My questions

which arduino revision is this?
Does it matter which revision i    buy?

That looks like an early-version Uno, rather than an Uno R3 as shown below. (Image is from dxcdn.com and is one of the first few images in a google images for Uno R3 search.)

For a beginner, replacing a DIP ATMEGA328P may be a chip too far.  I suggest that rather than looking for an Uno with a replacable chip, get any Uno you like.
Also note that for beginning projects, it makes sense to use the same kind of Arduino – an Uno, a Mega, a Pro Mini, a Nano, etc. – as the guide you are following uses, so that you won't have to adapt any pin numbers and wiring pictures.  As you gain experience, it should become easy to adapt designs to different boards.

It looks very much like the R2 that I have here.

That looks like an UNO R2, the type with DIP micro controller (you can extract it and replace it with another one, in case of problems).
The R3 version is probably the best choice to get started.
You might want one that has a connector where this one has only the 3x2 empty pads on the top left (close to the vertical writing AREF).
Have a look on ebay/aliexpress/amazon. You can find it for as little as $5-$6. Just search for UNOR3, if you elect to buy this type.

Looks more like an R2 to me.

Whoops, true, it's R2, I'll fix it. But I still think the removable AVR is better than the SMD one.


text:
What happens if I connect an external power supply, plus to GND and minus to VIN?
So far, I have connected plus to VIN and minus to GND, but I am curious what would happen if I do it the other way around. And I am not going to try in case I break someting.
So, what will happen?

Magic smokes will apear. If you have such a question, then DO NOT TRY THIS! Yes, you will definately burn your device

Well, good I did not try then :)

FYI: If connecting through a power supply plug (eg on the Uno), no problem. http://arduino.stackexchange.com/a/896/3267

So we are talking about specific device?

I am talking generally. But the Uno has a power plug (besides the VIN pin). And as described in the answer I linked to, the power plug has protection against reverse polarity. I thought that was worth mentioning.

So FYI: generally about polarity: https://www.youtube.com/watch?v=D-RZ5RTAdSg and if we are talking about Arduino UNO: yes it has polarity protection diode.

As you say, D1 adds protection for the PWRIN pin but it does not protect from eg reverse polarity on Vin - which was and so far is what the question was specifically about. Whether a shield will see PWRIN I don't know.  If it does then how it deals with reverse polarity may adversely affect the Arduino.

Some systems have protection against people connecting things in reverse.
Some don't.
On unprotected systems you MAY destroy the powered system and/or you MAY destroy the power supply - both these depend on happenstance, system design and luck.
Possibly worse - you may damage the target system in an inobvious way so that it subsequently behaves incorrectly or damages other equipment.
Systems which are designed to be protected may not be protected in all cases. eg if you have a "shield" connected that accesses the Vin pin outside the protection diode the reverse polarity voltage may damage the shield AND current may travel via the shield circuitry back into the Arduino via other connections.

Advice on You tube may just sometimes very very occasionally be wrong. Or more often.
If this "Reference Schematic"  is correct (as you'd hope it was) then Vin is connected to the "inside" of protection diode D1 - so D1 does not protect against reversed polarity. See lines and boxes in red.
Larger version of diagram here
D1 does protect against reversed polarity on "PWRIN".
How PWRIN relates to shield feeding I know not.

And D1 refers to a diode on the diagram? (not to the pin D1)

@MadsSkjern - D1 - yes, diode D1 as per text. In RED box at upper right here. I looked at a UNO. The power supply jack circuitry is used only by that board and not by attached shields so diode-D1 does protect them against reversed power supply. BUT reverse voltage on VIN line is NOT protected against. .


text:
What are the 5V and VIN pins for?
I believe I can supply the Arduino with power in three different ways:

Use USB. The design trusts the 5V to be regulated, and does not regulate it in any way.
Use a regulated power source, trusted to be 5V, and connect it to GND and 5V.
Connect an unregulated power source, eg a battery, to GND and VIN. This should be above 6.2V (since the dropout voltage is 1.2V) and preferably between 9V and 12V. There is a built-in regulator that will supply the Arduino with exactly 5V.

But can I use any of those pins to power other components. E.g. if the Arduino is powered with USB, can I use the 5V pin to power a diode? I thought I could, but the voltage is 4.70V, while the USB is 5.07V. The VIN is 4.26V btw.
Are the 5V and VIN only for powering the Arduino?

It's an Arduino Nano, so no barrel jack.

where and when were you getting those voltages? It could be a drop from measuring with and without other current flowing from USB (if you measured initially without the arduino). There should be a small drop as the USB input power does go across a fuse (F1 on schematic) and a mosfet (T1) before reaching the 5v pin.

I put the Nano in a breadboard. And I measure the voltages with a multimeter, which I put in the breadboard right next to the pins from the Arduino. I understand that there can be a voltage drop when there is a load, ie when there is a current. But there is no other load in my setup, than what is inside the Arduino itself.

I measure the 5.07V, by putting the multimeter on the points where the USB connector is soldered to the Arduino.

There is Feeding power to Arduino: the ultimate guide

No. You can draw power from the 5v and VIN pins on the arduino. VIN is the completely unaltered input power before the regulator (it will be useless if regulated 5v is supplied directly). Outputting power is what the 5v pin is intended to be used for, not as a power input.
From the arduino website:

5V. This pin outputs a regulated 5V from the regulator on the
  board. The board can be supplied with power either from the DC power
  jack (7 - 12V), the USB connector (5V), or the VIN pin of the board
  (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the
  regulator, and can damage your board. We don't advise it.

Yet, provided that you do not exceed 5.5 volts on the +5v pin, you can absolutely use it to supply the arduino.  You bear the responsibility of ensuring that you do not exceed 6v though.

I am still wondering how the USB power fits into this. Does the USB power bypass the regulator? I think it must otherwise there is too much of a voltage drop. So is powering the Arduino through the +5V pin the same as powering by USB? And does powering it through the +5V pin still also give the +3.3V?

you can input power into an arduino, up to 20 volt, via vin pin.

They can also be used to draw power from the barrel jack (Vin) or from USB or the on-board regulator (5V). The schematic of the board shows all exact power paths.

Ok, but then why does the 5V and VIN pins have lower voltages then? And wouldn't that be a problem for many applications? I imagine that if I used a LCD display rated at 5V, it could (potentially) be a problem that it only gets 4.70 or 4.26V?

Btw: I am not an electrical engineer, and I am not able to understand the schematics. Maybe one day :)

It gets a lower voltage because the traces on the board have non-zero resistance, which results in a voltage drop. Check the datasheets of all components to see what voltage range they can accept, but 4.70V should be fine for 99% of all 5V electronics.

5V pin can be used to power up shields like Bluetooth, RFID, ultrasonic sensors etc..
vin pin is used to power up the Arduino. For example, when using shields such as L298 motor shield which is providing 5V output while operating from 12V.

The MBR0520 Schotky Power Rectifier (Surface Mount
Schottky Power Rectifier) is connected in the Series path of 5v pin present on Nano which can handle maximum of 12V reverse voltage and according to datasheet 20v typical valur thus we can power ON arduino NANO using 5v pin also provided you supply proper 5v through any type of DC-DC Converter to it.
https://www.onsemi.com/pub/Collateral/MBR0520LT1-D.PDF
http://malylubo.sk/wp-content/uploads/2013/01/Arduino_Nano_Schematic-1024x676.png


text:
control a jack/cylinder to open/close a window
I want to open the window to let the cat enter or go out, but the mecanism of the window may me think that the best way should be to use a jack/cylinder (I don't know what term is more appropriate in english for that) to open and close the door.
I will use rfid or another wireless think to know it the cat is in the place and then open the wondow but I want to close the window and let the wndow close event if there is little bit of wind, so I need domething robust.
Do you know a good hardware with (this would be the best) piece of code that can help me for that?
Thanks in advance

Something like this http://www.window-openers.com/ks3040_electric_window_opener.html maybe

Check out this instructable - for opening a window for a cat :)
The guy used a servo, Towerpro MG995 with 10 kg torque for opening/closing the window, and a 10cm distance sensor for sensing the cat (he used Pololu Carrier with Sharp GP2Y0D810Z0F Digital Distance Sensor, but I believe that any proximity sensor will do).
This is a pictrure of the mechanism, seems quite robust:

I think it's safe to say that this would fall under "fair use".

so @IgnacioVazquez-Abrams you woundn't recommand it? too cheap?

@clement: See the revisions of the answer.

and what about a Actuator? @Ignacio ?

Servo is a type of actuator.


text:
little pump isn't working
I'm trying to use a little pump with my arduino nano:
void setup ()
{
  pinMode(waterPump, OUTPUT);
}
...
  while (val < valueWater)
  {
    Serial.println ("in while"); // testing purpose
    digitalWrite(waterPump, HIGH);
    delay(1000); // 1 second
    digitalWrite(waterPump, LOW);
    val = analogRead(sondeEau);
  }

When I try this one, pump isn't working. When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?
I tried to plug pump directly on 5V on arduino, pump works well...
This is the pump I bought: http://www.dx.com/p/hsyy01-water-pump-motor-w-hose-white-silver-236808
Thanks in advance to help me!

You can't plug a motor directly into the arduino, you need an appropriate driver circuit, or for simplicity, a "motor shield".  Further, you should not try to a run the motor off of USB power or through the Arduino's voltage regulator.

You plugged this directly into your Arduino? You might as well have dropped your Arduino in the water you are pumping...
The Arduino can only supply 40mA per pin. However, you pump requires 800 mA!!! Often, when overloading a pin, the Arduino chip is fried. Even worse, a typical USB port can only supply 500 mA, so you could have fried your computer if using USB.
You'll need a motor driver. Like mentioned in the comments, the Arduino motor shield is a great place to start. If you don't to spend all that money, you have a few options:

A relay is an easy way that works with almost all voltages and any reasonable amount of current.
If you want something a little more professional, a transistor, like a MOSFET would be the way to go. They're fairly cheap, but you have to know which to pick (that's hard to do in practice).
You can also get a half H-bridge which I think would work well for your situation.

When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?

The motor is likely taking up all the current.
tl;dr: get an external power source and get a proper motor driver.

Pretty much any logic level power mosfet will do, driven through a 120 ohm resistor. Plus a flyback diode across the motor. I think that's the cheapest and lowest component count solution.

I would not qualify a relay to "wok with any reasonable amount of current". Using a relay typically implies using a transistor (not a high-current) AND a diode to protect against emf currents.

@jfpoilpret I meant that a relay shield/break out board might be better than a transistor (as far as ease of use for some users).

I used a relay I had and an other power source for the motor. Thanks for your infos, very appreciate!

As Chris says, you should never plug a high current device like a motor directly into a pin on your Arduino. That motor is rated at 800 mA, which is more than you can draw from the entire 5V supply on the Arduino!
The digital pins are rated for 40 mA max, if I remember correctly. You tried to draw 20 times that much. There is a decent chance that you burned out the driver for that digital pin. I would try hooking an LED through a 220 ohm resistor and to ground and see if it still lights up when you send it a HIGH logic signal.
For a simple DC motor you should be able to use a high current transistor and an external power supply to drive it.
Edit:  If I were doing this I would use a logic-level MOSFET to drive the pump directly, plus a flyback diode. To use a relay, you will still need a transistor to power the relay coil, AND a flyback diode. Your circuit might look like this:

(Note that I made no attempt to pick the RIGHT kind of diode and transistor. Ignore the part numbers shown in the schematic. I just used the defaults.)

All is ok, all pin works. I finally used a relay and 5V 2A input source, it works well.

Did you put a flyback diode on the relay? (VERY important!) And are you driving the relay with a transistor? A relay's coil will almost certainly draw more than the 40 mA max from an Arduino digital output pin.


text:
Sine Wave Inverter
I am working on building a pure sine wave inverter using an Arduino Uno to output two PWM signals for the top and bottom half of the wave. Currently I am outputting pre-calculated values with an interrupt as PWM. This seems to be working but I was wondering if anyone had any feedback on my design, and whether there is a better way to go about doing this. I will also need to incorporate feedback into this to vary the max PWM duty cycle, and I am worried the ATMEGA will not be able to keep up do this fast enough.
Please let me know if you want any more details, thanks in advance!
Olls
The spreadsheet I'm using to calculate the values.
#include "TimerOne.h"

int duty_cycle;
int x = 0;

// sin_table is made up of sin(0-400) values multiplied by PWM_PERIOD
// https://docs.google.com/spreadsheets/d/1iyveHnOxIzqg907T6pu4znsJE-6tg40juMihDvU8Tbg/edit?usp=sharing
uint8_t _sin[] = { // Calculated for 50Hz at 200 pulses per half wave.
    0,0,0,1,1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,7,7,8,8,8,9,9,9,10,10,10,11,11,12,12,12,13,13,13,14,14,14,15,15,15,15,16,16,16,17,17,17,17,18,18,18,19,19,19,19,19,20,20,20,20,21,21,21,21,21,22,22,22,22,22,22,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,23,23,23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,20,20,20,20,19,19,19,19,19,18,18,18,17,17,17,17,16,16,16,15,15,15,15,14,14,14,13,13,13,12,12,12,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,5,5,5,4,4,3,3,3,2,2,1,1,1,0,0,0,0,0,1,1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,7,7,8,8,8,9,9,9,10,10,10,11,11,12,12,12,13,13,13,14,14,14,15,15,15,15,16,16,16,17,17,17,17,18,18,18,19,19,19,19,19,20,20,20,20,21,21,21,21,21,22,22,22,22,22,22,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,23,23,23,23,23,23,23,22,22,22,22,22,22,21,21,21,21,21,20,20,20,20,19,19,19,19,19,18,18,18,17,17,17,17,16,16,16,15,15,15,15,14,14,14,13,13,13,12,12,12,11,11,10,10,10,9,9,9,8,8,8,7,7,6,6,6,5,5,5,4,4,3,3,3,2,2,1,1,1,0,0,0
};

void setup() {
    // Pin mode, and set low.
    DDRD = DDRD | B00011000;
    PORTD = B00000000;

    Timer1.initialize(47);
    Timer1.attachInterrupt(pwm);
}

void pwm() {
    if (PIND & B00000100) { // Inhibit switch

        // Lower half or upper half of wave, start PWM pulse
        if (x > 200) {
            PORTD = B00010000;
        } else {
            PORTD = B00001000;
        }

        duty_cycle = _sin[x];
        if (duty_cycle > 3) {
            delayMicroseconds(duty_cycle);
        }

        PORTD = B00000000;

        x++;
        if (x > 400) {
            x = 0;
        }
    }
}

void loop() {}

Why not use one timer to do the PWM on the pins, and a second (slower) timer to change the duty cycle to match the sine wave. That way you also don't need to change the code to have a different frequency. You'd probably also need to add a RC filter to the output pins, and maybe a voltage follower to get a consistent output, no matter how much current you are drawing.

I did get it working. The schematic isn't mine to share unfortunately, but it consisted of some transistors to shift the PWM up to 20v, which then went into an inverter circuit (not made by me, quite complex) which merged the two PWM signals together into a AC signal. Then there was a transformer and RC filter to smooth out and amplify the PWM. Sorry I can't be more help, but it was a while ago, and I didn't make all of it.

http://arduino.stackexchange.com/questions/23842/three-phase-sine-wave-inverter-using-arduino points to an article with some circuitry.

Comment by olls converted to an answer:
I did get it working. The schematic isn't mine to share unfortunately, but it consisted of some transistors to shift the PWM up to 20v, which then went into an inverter circuit (not made by me, quite complex) which merged the two PWM signals together into a AC signal. Then there was a transformer and RC filter to smooth out and amplify the PWM. Sorry I can't be more help, but it was a while ago, and I didn't make all of it.


text:
A knob that can be turned by hand, have the position read, and turned by software to another position?
I'd like to be able to change variables on the Arduino by adjusting a set of knobs.  When I get to a desirable setting I'd like to be able to save those settings on the Arduino... and then I'd like to be able to load those settings back, and have the knobs turn themselves back to the correct positions.  Specifically I'm thinking of using this with a synthesizer.
I understand how to do all of this, except, I don't know if there are knobs that allow this type of behavior.

I think one of my amplifiers had something like that. Google "motorized potentiometer". There seem to be a few on eBay, amongst other places.

You might also consider using KY-040 rotary-encoders, with no cal marks on the knobs.  When you reload settings, just change all the current-position counts to match the reloaded values.  I can add this as an answer with a little more detail if you like.

Thanks Nick.  Looks like theres one here: http://www.mouser.com/ProductDetail/ALPS/RK16812MG099/?qs=uOLQ569YubvkId4TDNOKXQ%3D%3D

If you attach a knob to the Analog Feedback Micro Servo, either directly or via gears, then you can use the pot output to measure the current position and use the normal servo control protocol to turn it under software control.

Not a knob, but depending on your application, would a motorized slider like this be applicable?
You would read it just as you would a potentiality, and you have a motor that you can use to drive it to a specific position when you make a change in your software.
As for knobs, I have seen very few if any motorized knobs. What I would recommend here would be a continuous rotation encoder so that the position of the knob actually doesn't matter.

Alternatively, just add an LED/LCD display on top of each knob (or have a larger LCD showing info for all the knobs) to show the value.
Then you can have the knobs implemented with an optical rotary encoder.
Each knob is unmarked and doesn't need to be reset.
This solution doesn't put any mechanical part under strain.

If you can't get a motorised potentiometer could you use a rotary encoder, a motor, a shaft and some cogs.  Press the shaft and rotate manually then release and it disengages the manual cog and moves back to the motor cog.


text:
How is LED powered when PIN 2 is disconnected?
Using the Arduino tutorial "Button", I have noticed that if I totally disconnect Pin2 from the circuit, the LED comes on dimly.
I am trying to understand HOW this happens.  Is it simply due to being a floating ground?

The pinMode(buttonPin, INPUT); line tells the board to set the buttonPin in high impedance mode.
When you disconnect the wire the state of that pin becomes unknown; usually it oscillates.
Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".
The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as pinMode(buttonPin, INPUT_PULLUP); and invert the logic (i.e. buttonState = !digitalRead(buttonPin);). This way it will never oscillate again.

Sounds good!  Any idea why the tutorials all assume PULLDOWN and ask for resistors rather than coding for PULLUP?

That's because our mind thinks in a "positive" way. Button is pressed means, for the programmer's mind, a HIGH value. Since the atmega only has pullups, if you want to use it you have to connect the button towards ground, so the button pressed status is signaled by a LOW value. You just have to invert the logic, but... Personally I prefer to put buttons towards ground :P And, by the way, since you are learning I suggest you to experiment with debouncing ;)

Yep, de-bouncing was the next question and I've got that one mastered now.  I guess we all have the same questions getting started. :-)

Of course ;) That's why forums are a great way of learning if used properly. There is always someone who has already faced your problem ;)


text:
reversing a micro motor by reversing two pins - one Source and one sink?
can I use this configuration of two pins to run a micro motor ,so I be able to change the polarity of the current (by the code itself-one time out pin1-high out pin2 - low , while next time one low two high!) every time I would like ?(and by changing the polarity OF THE CURRENT to the motor it will revers it) !
Thank's !

For interest - how micro is "micro" and what is the motor used and application? If you need more power an H bridge driver can be built for tens of cents (and some ICs are low cost)

**Required:**

Drive micro-motor directly from two processor pins.

 - Pin 1 high / Pin 2 low for one direction.
 - Pin 1 low / Pin 2 high for other direction.**

This is not a very good idea if it can be avoided but yes, you can operate a motor that way,  providing that the motor current is low enough to meet the pin current ratings. It would have to be a very small motor to achieve this.
Take careful note of the current versus voltage drive capabilities of the processor concerned. While a pin may be shown as being able to source or sing 5 or 10 or 20 mA, this is accompanied by a voltage rise for a sink and voltage drop for a source, so at higher currents lower voltages will be available.
A danger is that motor noise may affect the processor.
Placing a small capacitor across the motor will help, and driving the motor through a small resistor from each pin will also help keep noise away from the processor. But depending on the motor used this may not be enough.
The series resistors will drop some voltage and so are limited in maximum allowable size.
The parallel capacitor will slow the direction transition - the larger the capacitor the slower the change.
Using drivers or "buffers" which are higher current rated would allow a larger motor to be driven and would help isolate the processor from the motor noise.
Ask further if any idea here sounds useful.

Added: Had a discussion with Gerben (below).
I'd avoided mentioning "catch diodes" but this is an add on that can help.
From each pin add a small Schottky diode* from pin to Vcc and pin to ground so that all 4 diodes are reverse biased.
(ie Cathode goes to Vcc = line on diode on upper diodes.
Anode goes to ground on "lower" diodes. )
These diodes are usually non conducting. If motor operation or switching causes spikes that rise above Vcc or below ground these diodes will conduct (slightly) before  the internal protection diodes do. This is not ideal but can help.
As Gerben notes, when reversing the motor, driving BOTH pins to ground until the motor has stopped and then applying reversing polarity can help. Also driving both high will do the same. There are pros and cons with either method.

eg BAT54 surface mount,   BAT48 through hole, 1N581x  or similar.

You also need to add some clamping diodes to eliminate flyback, which is the sudden voltage spike seen across an inductive load when its supply voltage is suddenly reduced or removed. I did this on my project where I was driving the tiny lavet stepper motor inside an analog clock. I added diode to clamp the voltage to VCC. Clamping to ground  was done by setting both pins to LOW before any further movement.

A problem with using diodes is that the motor polarity reverses. I considered suggesting Schottky diodes to gnd and VCC from each pin but decided to offer the cct as seen and see if the OP shows interest. It can then be refined. You can add an H bridge driver with jellybean transistors for very little $ indeed but providing detail on this initially is just liable to confuse.

thank you very much guys !                                                                                you are fantastic  !!!


text:
What is Arduino?
Actually I don't know about Arduino, but seeing my fellow classmates, I want to start learning it. Could anybody tell what actually Arduino is about?

Google Arduino or got to arduino.cc

What is Arduino?
Arduino video tutorials
Official boards
Wikipedia - Arduino
Arduino forum

A popular Arduino - The Arduino Uno:

In case I get accused of writing a "link-only" answer ...
The Arduino is a hobbyist prototyping platform, where users can develop projects for microprocessors. Typically the boards have one or two processors on them, can connect to a PC/Mac/Linux by a USB interface, be programmed in C++, and operate external devices (eg. motors, lights, MIDI, LCD screens, LEDs) and take readings (eg. temperature, time, location, voltage).
Different boards have different capabilities, such as the number of I/O ports, the amount of memory, and the size of the program that can be uploaded.
You can connect them to the major operating systems:

Linux
Macintosh
Windows

The hardware and software are open-source, making development for them easy.

Image attribution: Sparkfun Electronics


text:
Why does this button have a connection to ground?
I am testing this basic button example  from the Arduino tutorial page.
This circuit lets power flow to pin 2 when the button is pressed. When the button is not pressed, the power goes through the resistor to ground, but my question is: why would you even need the connection to ground?
Can't you have power flow from 5V to pin2 or just have NO connection at all when the button is not pressed?

Don't think in terms of where the 'power flows' (current), think in terms of voltages. It will make more complicated circuits easier to understand.

That resistor is called a pull-down resistor. It's there to make sure pin 2 read low when the button isn't pressed. If you don't put it there pin 2 is left 'floating', and it could erroneously read a high value. Google it for more info.
If you want to simplify you circuit you could instead use a pull-up resistor, and connect the button to ground instead of 5v. The ATMega chip on the arduino has these pull-up resistors build into the chip itself, so you don't need to add one to the breadboard. Just not that the input values will be reversed. So pin2 will read LOW when the button is pressed, and HIGH when not. To activate the internal pull-up use pinMode(2, INPUT_PULLUP)

In simple words, to avoid undefined state. This type of resistor arrangement is known as Pull Down Resistor. (Pull-Up also exists)


text:
Neopixel code not working on Adafruit Feather board
I have connected a single neopixel to my Adafruit Feather board, running Arduino software.
The power pin is connected to 3V on the Feather. The data-in pin is connected to pin 15 on the Feather.
As soon as power is connected, the light shows blue. But uploading any program has no effect whatsoever. The Neopixel won't respond to anything.
How can I use a Neopixel on the Adafruit Feather?
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif

#define PIN 15
#define NUMPIXELS 1

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

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

void loop() {
  Serial.println("RED");
  pixels.setPixelColor(PIN, pixels.Color(255, 0, 0));
  pixels.show();
  delay(1000);
  Serial.println("GREEN");
  pixels.setPixelColor(PIN, pixels.Color(0, 255, 0));
  pixels.show();
  delay(1000);
}

The neopixel and the Feather board

I think, 3V is not enough for the Neopixels. Can you try providing them with 5V?

Hm, that might be it. I assumed 3V would be good since the Circuit Express Playground uses 3V and has 10 neopixels! But maybe these bigger ones need more power ??? https://www.adafruit.com/product/1734

Adafruit states, that the 3.7V from a LiPo battery is just enough for a few Neopixels

Pin 15 is the serial RX pin which connects to the USB port so you should not use it.  From the Feather pinouts page about pins 15,16 : "These are connected through to the CP2104 USB-to-Serial converter so they should not be connected to or used unless you're super sure you want to because you will also be getting the USB traffic on these!"
So try another pin and it should work.


text:
Detect when RFID card is absent
I am trying to build a mobile device that turns itself on when removed from its usual location. I am attempting to do this with an Adafruit PN532 RFID reader and a MiFare card. Using the sample code I can detect when the card is present
success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
Serial.println("Scanning");
if (success){
  Serial.println("FOUND");
}

However, when I try to detect the absence of the card using the following code it will tell me "Present" over and over (since its in the Loop) while the RFID card is present but when it is removed it stops printing "Present" but never prints "Card Gone"
success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
    Serial.println("Present");
    if (!success){
      Serial.println("Card Gone");
    }

Is this a function of how Im using ! or is there something else at play here? I have found very few suggestions regarding detecting the absence of an RFID card and none of them seem to provide any useful answer. Most suggest some other hardware methodology as the solution. That is not the type of answer Im interested in for the moment. I would simply like to figure out why my code is incorrect.

Post the whole function, at least, not this snippet. There is no context.

First, your code isn't structured properly. It should be:
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

if (success)
  Serial.println("Present");
else
  Serial.println("Card Gone");

From what I could find in the library, the reason you aren't getting either the 'Card Gone' or 'Present' message when there is no card is because nfc.readPassiveTargetID() is a blocking function. It will wait forever until a tag is detected, at which point it returns to the caller. When you bring a card within the reader's range, the function returns quickly and loop() runs smoothly, giving you the 'Present' message over and over again. When you remove the card however, on the next call of nfc.readPassiveTargetID(), the function tries to locate a card but finds none and then it keeps trying and does not return. So loop() never gets past that point, until you bring a card within range again.
To detect the presence or absence of something, an observer must observe for some pre-determined period of time before making a decision. So, I suggest you get the latest version of this library which gives you the option of adding a milliseconds timeout argument to nfc.readPassiveTargetID(). That way, you can specify how long you want the function to try detecting a card before concluding there is no card and returning.
Alternatively, you could use your existing function as is but in setup() you need to set the maximum number of re-tries before the nfc.readPassiveTargetID() returns. This is done with setPassiveActivationRetries(). Any argument from 0x00 to 0xFE indicates a finite number of tries, while 0xFF is to wait forever:
nfc.setPassiveActivationRetries(0x9A); // for example
nfc.SAMConfig();  // this comes next

Good luck.

thank you for the great explanation and thoughts on approaches to address the issue. One question before I try this. From your explanation, it seems the "if (success)" line is redundant?

@techkilljoy In your code, it is redundant because the function only ever returns if it finds a card. However, if you make these changes, it will become possible for the function to return 0 after trying a few times and finding no card. A card detected would result in a return value of 1 though

You can edit the .cpp file and add a timeout. I did this to remove the blocking scan. Search for TIMEOUT in the Adafruit_PN532 source code.


text:
Arduino ESP8266 (arduino-esp8266) documentation for core_esp8266_waveform.h
Intro
I have found by chance the following header file in Arduino core library for ESP8266:
core_esp8266_waveform.h
That defines interesting functions like startWaveform that should allow for playing (maybe?) an arbitrary waveform using pwm.
I would like to know more about this library that seems interesting.
What I have tried
I have looked for documentation but I have found only these:
https://arduino-esp8266.readthedocs.io/en/3.1.1/
https://arduino-esp8266.readthedocs.io/en/latest/
These are documentation of the Arduino ESP8266 platform but there is no trace of the waveform library.
Source files are in the following path:
[framework-arduinoespressif8266 home path]/cores/esp8266
And interesting files are:
core_esp8266_waveform.h
core_esp8266_waveform_phase.cpp
Final question
Beyond trial and error and self studying what the source does (that I will do as a last resort), is there some documentation I was not able to find?

there is not much trial and error to be done ... there are only two functions to try ... one starts the waveform and the other stops the waveform

not sure what exactly you are interested in those functions as there are more abstracted function of tone() and noTone() that achieved the same. It actually the functions used in tone() and noTone() implementation, you can find out more it usage from https://github.com/esp8266/Arduino/blob/master/cores/esp8266/Tone.cpp.

@hcheung
Beyond what can be inferred from the method signature and (maybe) random examples found here and there I would like to build a base knowledge of how these functions are implemented in order to decide if to use some of them or implement on my own.
I'm going to use these devices as waveform generators for a musical project.
If it's not documented then I have to reverse-engineer the code  ...
I find your answer useful.

Please look at Arduino tone() documentation for more details, it might provide the API that you need.

You can try the startWaveform library: https://github.com/esp8266/Arduino/blob/master/cores/esp8266/core_esp8266_waveform.h


text:
How do I address internal led in Arduino framework raspberry pi pico W?
I am trying to use the internal led of a Rapsberry pi pico w
The exact point of the question is the "w" version of the raspberry pi; internal led is not pin 25 but I was unable to figure it out.
I tried several addresses up to 32767 with no result:
#include <Arduino.h>

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

void try_led(uint led_n)
{
  pinMode(led_n, OUTPUT);
  digitalWrite(led_n, 1);
  delay(200);
  digitalWrite(led_n, 0);
  delay(200);
}

void loop()
{
  for (uint led = 0; led < 32767; led++)
  {
    Serial.println(led);
    try_led(led);
  }
}

Is internal led supported?
How can I address it?

did you try to use the macro LED_BUILTIN as shown in the Blink example?

Yes, but the macro addresses pin 25 that works for the normal "non w" version of the pico...

did you select Pico W in the Tools menu?

don't turn off the LED in your code ... that way it is easy to see when it turns on

Are you using Arduino Pico framework by Earle PHilhower? I saw a recent fix on v4.3.1 that suppose fixed the LED problem. Do a library update to make sure you had the v4.3.1 if you are using the Arduino-Pico core.

FYI. For Pico W, the LED is WL_GPIO0 on the Infineon 43439 WiFi chip.

I am using Arduino IDE via Platformio and I was not able to find distinction for the "w"...
Where is WL_GPIO0 defined?

As far as I know, the Pico W's internal LED is connected to the Wi-Fi chip (CYW43439) and controlled via GPIO 2.

I am using Arduino IDE via Platformio okay so what's the platformio.ini? If you selected your board = rpipicow, then LED_BUILTIN will be correct.


text:
Could a bluetooth, speaker and microphone equiped arduino be used to form a range sensing swarm?
I am trying to figure out how to build a system of devices that could, on command, notify similar devices that are within a configurable distance. Maximum ranges would need to be around 20' though up to 40' would be preferable. Accuracy +- 20% is acceptable as is degradation due to things such as large intervening objects, walls, buildings etc. Only one notification is expected in any given 10 second block.
I was thinking the sending device could send a ultrasonic ping, and then send a data packet with the ping time stamp and range notification to all devices in range. And then each receiver could compare the ping receive time and range notification and calculate if it is within the range given in the data packet.
Would this work? Is there a better way to do this?


text:
Servo library unable to control more than 11 servos
I am working on assembling the ROFI robot from Project Biped (http://www.projectbiped.com/prototypes/rofi) and I have not been able to run any arduino program as they will not function correctly.
To be more specific, when I attempt to run 12 servos on a single Arduino Mega, the servos twitch uncontrollably and do not move to the positions which are set in the program.  At the same time the power light on the arduino mega blinks and does not turn solid (as opposed to if I use less than 11 servos when the pwr light is solid).  I predict it might be the power source but after checking the batteries with the multimeter they check out to be fine (7.6 V).  The circuit is pretty simple, I am using a servo shield connected to a 6V regulator connected in parallel to two 7.2 V 1350 mah LiPo batteries.  The arduino is connected through the dc power jack to the same circuit in parallel.
Here is the code...
   #include <Servo.h>

// 0 Right Ankle (roll)
// 1 Right Lower Leg
// 2 Right Knee
// 3 Right Middle Leg
// 4 Right Upper Leg
// 5 Right Hip (roll)
//LEFT LEG JOINTS
// 6 Left Ankle (roll)
// 7 Left Lower Leg
// 8 Left Knee
// 9 Left Middle Leg
// 10 Left Upper Leg
// 11 Left Hip (roll)

int c=0;

Servo rightAnkle;
Servo lowerLeg;
Servo rightKnee;
Servo rightMiddleLeg;
Servo rightUpperLeg;
Servo rightHip;
Servo leftAnkle;
Servo leftLowerLeg;
Servo leftKnee;
Servo leftMiddleLeg;
Servo leftUpperLeg;
Servo leftHip;

void setup(){
  rightAnkle.attach(0);
  lowerLeg.attach(1);
  rightKnee.attach(2);
  rightMiddleLeg.attach(3);
  rightUpperLeg.attach(4);
  rightHip.attach(5);
  leftAnkle.attach(6);
  leftLowerLeg.attach(7);
  //leftKnee.attach(8);
  //leftMiddleLeg.attach(9);
  leftUpperLeg.attach(10);
  leftHip.attach(11);
}

void loop(){
  rightAnkle.write(90);
  lowerLeg.write(90);
  rightKnee.write(90);
  rightMiddleLeg.write(90);
  rightUpperLeg.write(90);
  rightHip.write(100);
  leftAnkle.write(90);
  leftLowerLeg.write(90);
  leftKnee.write(90);
  leftMiddleLeg.write(90);
  leftUpperLeg.write(90);
  leftHip.write(90);
}

What are the specs of the 6 volt regulator?

It sounds to me like you're exceeding the current limits of your power supply. Add up the current drawn by your servos (and their controller(s), and also the current drawn by your Arduino and any other circuits you have. I bet you'll find that at 12 servos, you go over the current limit of your regulator. You might need a higher current regulator or a second one.

Servo library unable to control more than 11 servos

because the library isn't written to control more.
this approach (https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/) can drive arbitrary number of servos over multiple ports / pins.
it is written for a pic but it has links to AVR implementation as well.