text:
Question about configuration EEPROM or Flash
I want to make an external (not related to Arduino) computer application that creates a big 'setup file' (like max. 64 KB). This setup file contains lookup tables (which are configurable and the tables with data themselves).
This 'setup file' needs be stored in the Arduino.
Now I thought of the following alternatives:

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).
Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).
Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.
Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.
Can you please give me some more information which alternative would work or not? Or maybe I missed out something trivial or an alternative is impossible?

Somehow let end users use the computer application to store the setup file they created into the Arduino's extended EEPROM (I will add a 64KB EEPROM for this). However I don't know if a computer application can be made that can do this (i.e. store the information to EEPROM).

Perfectly viable - although an SPI Flash chip would be more appropriate.

Do like above, but store it in Flash (as far as I know, only the Arduino computer application can do this, to send a sketch to USB).

It is the bootloader that can write to flash. I don't thing the main program can write to flash, or it would wipe itself out. You may need a special bootloader with your own protocol and upload program to go with it.

Create an application that 'adds' the setup file to the sketch. However, probably end users cannot store it in the Arduino without the Arduino software which is unwanted.

Perfectly viable, but tricky to say the least.

Use a SD card and read information from there; however, I read 512 bytes SRAM is needed.

Yes, 512 bytes of SRAM, since that is the size of one block on an SD card. But an UNO has 2048 bytes of SRAM - more than enough for SD card support.
The SD card would be my route of choice. It's the easiest from a user's perspective (slip the card into their computer and copy the files), and pretty simple and straight forward to connect and program the Arduino for.

To make it more complicated, I want the Arduino sketch to handle like reading on average 50 random bytes from the storage the setup file is stored, and perform several algorithm (not so difficult but still) and do this in max. 10-20 ms.

If you know where in the file the byte are then you can seek() straight to them. Takes almost no time. 20ms is an eternity for a microcontroller.

Thanks for these great answers! I have one additional question, 20 ms is an eternity ... wondering if reading like 20 blocks (of 512 bytes) can be done too from an SD card within 20 ms?

10K might be pushing it - especially as you can't store that data - you'd have to be processing it on the fly.

Thanks very much ... Maybe I can store the (useful) data... or maybe even better: I can store a lot of data with the computer application and read it for the Arduino in the most easy way.

Not sure what it is you are trying to achieve, but if you are going to use an SD card, you've got a very very large amount of storage available. You could maybe do some pre-processing on the data before storing it on the SD card. Create multiple versions of the file that are pre-randomized. Similar to what  rainbow-tables do; use more diskspace, to lower computation time.

Yes, something like that sounds good... I will add a bit of what I need in my question as background.

@Majenko you say 20 ms is an eternity but I asked a more detailed question about the speed in http://arduino.stackexchange.com/questions/35610/how-fast-is-a-sd-page-read-from-a-file/35611?noredirect=1#comment70985_35611  and it shows the speed is about 200 KB/s which means one 512 byte page to read in 2.5 so I can read like 8 maximum per 20 ms?


text:
Arduino WiFi/ESP8266 WiFi Password Changed
I am working on a project for a friend who is not very tech savvy involving an ESP8266. It will need to be connected to his WiFi network.
The issue is that he occasionally changed the password to his WiFi network. Since I will not be able to access this device at a moments notice, it needs to be able to adapt to a change in the password. Is this possible with the ESP8266, or should I switch to an Arduino WiFi board, or is something more powerful necessary?

The most common solution is to have the ESP act like an accesspoint, if it can't connect to the wifi network. It will then host a webpage, where you can set the correct networkname and password.

The ESPEasy firmware does the trick, but it may not do whatever you preprogranmed it to do

The WiFiManager library was written for exactly this purpose.

Yes that's possible.
Just don't hard-code the password: store it in EEPROM.
A common way of doing it if for the ESP to present a wifi access point which serves a configuration page when it cannot successfully connect to another access point.  Store the SSID and password in EEPROM.

On my laptop, if the wifi network password changes, I do not need to re-enter the password, it figures it out automatically. Is there a way I can do this on the ESP?

I think you are mistaken about that.

Ok, I just realized I can use bluetooth for this project as well. Is there a way I can add a password to bluetooth to restrict access to specific devices?

That's a new question.

Bluetooth authentication isn't very strong, you could do an ethernet connection, since these aren't password protected.

Think about it, you don't want any device to be able to do this.  Imagine you got hacked and someone got your password.  If this was possible, then you wouldn't be able to stop them by changing the password.

source: Stack Exchange

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

sort: votes


text:
Another problem with code; boolean?
Maybe another problem for trained eyes. I seem to get the alarm to cycle regardless of the state of "trigsensor" and "away" (they should both need to be true in order for the alarm to run after an incorrect code is entered). Thanks for any response to this, as I am still learning C:
//////////////////////////// initialize & includes //////////////////////////
#include <elapsedMillis.h>
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

int PIR_SensorPin = 2;
int Alarm_OutPin = 11; //green
int Light_OutPin = 12; //red
int alarm_count = 0;
volatile boolean trigsensor = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection;
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("GSM Alarm starting up."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = Network READY");
    digitalWrite (Alarm_OutPin, HIGH);
  }
  delay (10000);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
  Serial.println ("System Ready");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop() {
  if (trigsensor == true) {
    alarm();
  }
  else {
    readKeypad();
  }
}

//////////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  //  alarm();
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.print ("away="); Serial.print (away); Serial.print (" ");Serial.print ("trigsensor=");Serial.println (trigsensor);
  Serial.println("at Alarm");
  if (away == true && trigsensor == true) { ////////////////////////////////
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
  }
  // else if (trigsensor == true) {  /////////////////////////////////////////////
  for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
    digitalWrite (Light_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
    digitalWrite (Light_OutPin, LOW);
    digitalWrite (Alarm_OutPin, HIGH); delay (1000);
    digitalWrite (Alarm_OutPin, LOW); // End by turning off light
    Serial.println(alarm_count);
  }
  digitalWrite (Alarm_OutPin, HIGH);
  trigsensor = false;
  away = false;
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {  //attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // reattach interrupt
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    tone(10, 900, 100);
    Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  digitalWrite (Alarm_OutPin, HIGH);
  digitalWrite (Alarm_OutPin, LOW);
  detachInterrupt(0);
  trigsensor = false;
}

//////////////////////////////// incorrect PIN /////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  Serial.println ("@ incorrect PIN ");
  delay(10000); // a slight delay aded to allow leaving without triggering the alarm
  trigsensor = false;
  away = true; /////////////////////////////////
  digitalWrite (Alarm_OutPin, HIGH);
  attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH);
  alarm();
}

Shouldn't this: if (trigsensor == true) be more along the lines of if (trigsensor == true && away == true) in the loop() function?

Would that really matter, as the problem seems to be the output of the operand, regardless of where it might be placed? I just tried it in the loop function and not any different.

attachInterrupt() doesn't support attaching on HIGH. Oh, and instead of if (trigsensor == true) you could write if ((trigsensor == true) == true), or maybe if (((trigsensor == true) == true) == true) (just kidding, if (trigsensor) is all you need).

Using "HIGH" with attacheInterrupt on a UNO seems to work. Is it a reliability concern?

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


text:
LCD isn't working with if statement
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#define trigpinyellow 10
#define echopingreen 9
#define Grove_Water_Sensor 8
void setup()
{
    Serial.begin(9600);
    pinMode(trigpinyellow,OUTPUT);
    pinMode(echopingreen,INPUT);
    pinMode(Grove_Water_Sensor, INPUT);
    lcd.begin(16, 2);
}

void loop()
{
    long duration,distance;
    digitalWrite(trigpinyellow,LOW);
    delayMicroseconds(1000);
    digitalWrite(trigpinyellow,HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigpinyellow,LOW);
    duration=pulseIn(echopingreen,HIGH);
    distance = (duration/2) / 29.1;
    Serial.println(distance);

    if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) >=20  )
    {
        lcd.clear();
        lcd.print("water_came");
        lcd.setCursor(0, 1);
    }
    if( digitalRead(Grove_Water_Sensor) == LOW && digitalRead(distance) <=8 )
    {
        lcd.clear();
        lcd.write("Tank_is_full");
    }
    if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) >=20 )
    {
        lcd.clear();
        lcd.print("Fill The Tank PLEASE");
    }
    if( digitalRead(Grove_Water_Sensor) == HIGH && digitalRead(distance) <=8 )
    {
        lcd.clear();
        lcd.print("Tank_is_FULL");
    }
}

You might want to change digitalRead(distance) >=20 to just distance >=20

Your collection of if statements has holes which could result in no output to the lcd. For example, if Grove_Water_Sensor is LOW and distance is 10 would result in no output.

I will try it Gerben, 6v6gt and thanks for the advice

But why it will not show any output

Voted down. Please add more content, what is not working?

@Omar: you read some distance to variable distance. So this variable now contain some more/less random long number. Then you call digitalRead(distance) where you read pin with this number - so you read some random (maybe even non-existent) pin. With digitalRead you read digital, so result is else HIGH or LOW (which are 1 or 0). And then you compare valoue of 1 or 0 (obtained from random pin) with values like 8 or 20. Do you see, why it does not work this way?

Okay my problem is that When it is<=8 it gives tank is full but when it becomes >=20 after the lcd remains tank is full so the lcd display isn't changing at all so please help me

@Omar - the "answer" area is not for clarifying your question or replying to comments. This is not a forum. If you are asked a question in a comment, make a comment to reply. If you need to clarify your question edit the question.

Every time you instantiate digitalread(), you poll the pin. Here, you're polling pins 8 times every loop. Instead, poll the two pins at the start of the loop to update the variable, and then do your math and make your decisions afterward. Right now you're doing math with your distance variable, and then overwriting the variable during your if conditionals. Not sure if that's what you intend. You're also creating the variables duration and distance every single loop. instead, create those variables globally and just update them every loop.


text:
SPI communication Problem Arduino
I'm trying to set up SPI communication between two Arduinos (UNO and Mega),
I want to read the status of the slave output pin from the master.
I connected a diode to pin 9 of Mega and I wanted to display its state on the virtual terminal of the master (Uno). The problem is that when the LED flashes I do not receive values just at the terminal level but when I hold it to zero or 1 the display is correct.
I used another code I found online.
MASTER code

#include <SPI.h>
const byte btn =8;

void setup(void) {

Serial.begin (9600);
pinMode (btn, INPUT_PULLUP);
digitalWrite (SS, HIGH);
SPI.begin ();
SPI.setClockDivider (SPI_CLOCK_DIV8);

}

void loop(void) {

byte Mvalsent,Mvalreceived;
digitalWrite (SS, LOW);
for (int jj=0; jj<255; jj++)
  {
      Mvalsent =jj;
      Mvalreceived =SPI.transfer (Mvalsent);
      Serial.print ("Retou d'etat ");
      Serial.print (Mvalsent);
      Serial.print ("\t ,l'etat de la diode est ");
      Serial.println (Mvalreceived);
      delay (400);
  }

  digitalWrite (SS,HIGH);

}

SLAVE Code
#include <SPI.h>
byte state;
const byte led =9;
volatile boolean process_it;
volatile byte Svalreceived, Svalsent;
int jj=0;
void setup (void)
{
  Serial.begin (9600);
pinMode (led,OUTPUT);
//set MISO pin as output
pinMode (MISO, OUTPUT);
//turn on SPI in slave mode
SPCR |= _BV (SPE);
//get ready for an interrupt
process_it = false;
//now turn on interrupts
SPI.attachInterrupt ();
}
ISR (SPI_STC_vect)
{
  Svalreceived = SPDR;
  process_it =true;
}
void loop (void)
{
 if (process_it)
 {

   digitalWrite (led, LOW);
   state =digitalRead(led);
   SPDR = state;
   Serial.print("l'etat de la diode est: ");
    Serial.println (state);
    delay (400);

    process_it =false;
  }
}

Not too familiar with arduino, but this seems to be a simple case of sampling.  You also need to clarify what you mean by "I do not receive values just at the terminal level" - do you get always incorrect values? Random values? Or does it not read at all?

Why not use I2C slave-master between arduinos?  You can hook up other arduinos or devices on I2C simultaneously (as long as each uses a distinct address).
And you still keep the SPI for a microsd card adapter, for example.
Follow this official tutorial:

MASTER ARDUINO 1
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

SLAVE ARDUINO 2
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

This is an alternative example of a setup using a nodemcu (which doesnt function in slave mode, btw).

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


text:
Ultrasonic sensors with 12v motors will not work! (ADRUINO)
ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results...
in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple!
but the wheels on the left side of my robot will stop! and just do nothing!
The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.
this is the shield I am using: https://www.pololu.com/product/2507
if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...
the code.
#include "DualVNH5019MotorShield.h"
DualVNH5019MotorShield md;

#define trigPin 7
#define echoPin 8

void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() {
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

//This is the sensor testing if somthing is in range!
if (distance < 4){
        Serial.println("in range");
        md.setM1Speed(100);
        md.setM2Speed(-100);
}
else {
        Serial.println("not in range");
        md.setM1Speed(-100);
        md.setM2Speed(100);
}

if (distance >= 200){
        Serial.println("!");
}
else {
        Serial.print(distance);
        Serial.println(" cm");
}
    Serial.println(distance);
    delay(500);
}

Why are you delaying the loop 500 ms at the end of each iteration?

TLDR: change your project (both program and connection) to use ultrasound sensor on any two of pins 3,5,11 and it should work.

You are using pins 7 and 8 for ultrasound.
At the same time you are using the shield  https://www.pololu.com/product/2507 for motors, but if you look at the shield description on picture Dual VNH5019 motor driver shield with an Arduino (shield and Arduino powered separately).https://a.pololu-files.com/picture/0J3753.1200.png?5877a2053bf73d6dbb43d10e7d268ce5
You will see, that the shield is using pin 7 as M2INA and pin 8 as M2PINB
So each loop you push M2INA (trigPin) LOW, then HIGH then LOW, then wait until the sensor write HIGH to M2INB (echoPin) just to immediately send PWM pulses to both trigPin (M2INA) and echoPin (M2INB) via commands
    md.setM1Speed(100);
    md.setM2Speed(-100);

No way it can work as you expect.
You must use other pins (unused by the shield) for your ultrasound sensor. I suggest to declare
#define trigPin 3
#define echoPin 5

and connect your ultrasound sensor there acordingly.
(You can use also pin 11 if you want. I would not recomend pin 13, as there is connected the Arduino LED, which is used by bootloader too so you could confuse the sensor, nor the pins 1 and 2, as they are used by Serial (and USB). Also you can use the "analog pins" A2..A5 as digital pins, but it may confuse you a little (AVR can use "analog" pins as "digital" but many beginers does not like constructs as "digitalWrite(A2)", "digitalRead(A3)").
Also keep in mind, that A4 and A5 are used for I2C communication, if you would use I2C later in project.

it works now! thank you very much! this is my first time using this website and it has saved my life :) thank you!!!!!!
I tried 3 and 5 and it didn't work... I tried 1 and 0 and it worked great! your smart XD thanks.

Nice, that it works now :) Can you mark it as answer?

I think I did it. I clicked the checkmark and the up arrow button.

Maybe it took some time to propagate thru th whole system :)


text:
Controlling common anode RGB LED with PWM - Can individual colors be done w/o transistors?

I am using PWM (analogWrite) with a common anode LED. My previous experience is using a common cathode. My breadboard is as shown:

simulate this circuit – Schematic created using CircuitLab
This creates a semi-bright white (ugly red-green-blue mixture) like I expected. I am using only one PWM output (It is currently fading).
Now, what I ask is how can I use multiple PWM outputs to make different colors display without transistors? I was thinking that I could have 3 dedicated pins on the Arduino that switch from ground to floating extremely fast, but is there an easier way?
If not, a little explanation on how to do it with transistors (mostly just a small wiring diagram) would be great. Cheers!

As long as each LED in the array uses 20mA or less you can do it directly with the Arduino:

simulate this circuit – Schematic created using CircuitLab
Note that the blue LED will have a higher forward voltage than the red and green ones, hence the lower resistor.
Also note that the PWM will be inverted. Writing 255 to a channel will switch that LED off, while writing 0 will give it full brightness.

Why exactly does this work? Also, does the PWM pin mode need to be input? Thanks!

A PWM pin cannot be input - that makes no sense. It works because when a pin is an output (as in when you are using PWM, or just simple digitalWrite()) it is either connected to +5V or to GND. When on +5V there isn't enough voltage difference across the LED for it to light. When it's connected to GND there is 5V across the LED and the resistor, making the LED light up.

@Blake I keep meaning to make a video tutorial describing exactly how a GPIO pin on a device like an Arduino actually works. It would show you instantly how this arrangement can work. Maybe I will get round to it over the next day or so.

I get it now! I was doubting to ask if it was an input anyway, like you said, that would make no sense. I just didn't know that is was 5V or to GND, thanks!

@Majenko My brain just had a fight with the yesterday as I was trying to explain it to someone else. The best I could come up with is that the Arduino is outputting a (PWM-proportional) "voltage” and it’s "butting heads" w/ the 5V going into the LED. So with 255 it’s a complete head-butt, no voltage drop across LED since it’s the same(-ish) on both sides. As the Arduino output voltage drops the differential increases, hence more differential, hence more light.

What I don’t quite grok is the Arduino pin circuitry—is the nutshell that in-between PWM pulses the LED is connected to the Arduino’s internal ground? I mean, it must be, but I’m trying to square that with the pin being set to output, but I guess if it’s outputting 0V somehow the pin circuitry does the right thing? I can build circuits, but I don’t always have a clear picture in my head why they act like they do :/

@DaveNewton Maybe this will help: https://majenko.co.uk/blog/what-exactly-gpio-pin

@Majenko Ah you did write it :) I think it helps--AFAICT it's more or less how I was thinking of it in my head, except with actual details. Thanks!

I am using only one PWM output (It is currently fading).

use three independent pwm channels to drive three leds.

how can I use multiple PWM outputs to make different colors display without transistors?

the answer depends on the leds. for leds that require small current, it is totally doable, just connect the pwm output to them.
for leds that require lots of current, no solution.

I agree with this, but why would you say that there is no solution for high-current LEDS? Would it be different if it was a common-cathode LED? I mean, if not, I understand.

There is indeed a solution for high-current common-anode RGB LEDs: use a transistor driven by the PWM pins. For example: https://electronics.stackexchange.com/a/64623, or https://electronics.stackexchange.com/a/241384 .


text:
Generating a short pulse after a delay
I am trying to use one of the hardware timers on the arduino uno to generate a short pulse some number of microseconds after receiving a pulse on an input.
Currently my code looks like this:
uint16_t pulse_delay = 12000; //half-microseconds
uint16_t pulse_length = 20;

void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
}
void loop(){}
ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match

  OCR1A = pulse_delay + pulse_length;
}

This code should theoretically do the task, but it doesn't produce any output at all - to my oscilloscope it looks like the output pin just stays low.
However, if I replace the last line (OCR1A = pulse_delay + pulse_length;) of the compare match interrupt with the following two lines, it outputs a pulse just fine. The issue with this is that it uses significantly more CPU time, and it can only count time from when the interrupt starts so if the interrupt is executed late the pulse will be longer.
  delayMicroseconds(pulse_length);
  TCCR1C = _BV(FOC1A); //manually trigger match event

All that the first version is doing differently is triggering the match event via an 'alarm' set on the timer, rather than waiting to trigger the match manually.
Why does the first version not work, and how can I make it work??

Just a quick guess, which I may develop into a complete answer when I have time, a little bit later: do TIFR1 = _BV(OCF1A); right before TIMSK1 |= _BV(OCIE1A);.

Also just a guess. Instead of  OCR1A = pulse_delay + pulse_length I'd just try OCR1A = TCNT1 + pulse_length;

@6v6gt I have tried that and it also fails. It also has the problem that it lengthens the pulse by the amount of time spent waiting for interrupts to be re-enabled in case the interrupt is triggered during a noInterrupts() block.

Expanding on my comment, after checking experimentally that this was
indeed the issue.
Short answer
You should do
TIFR1 = _BV(OCF1A);  // clear interrutp flag

right before
TIMSK1 |= _BV(OCIE1A);  // enable match interrupt

Explanation
Whenever the timer reaches the value stored in one of its “compare
match” registers, this triggers a “compare match” event, which has the
effect of raising the corresponding interrupt flag (OCF1A in your
case). If the associated interrupt is enabled, that fires an interrupt
request, and the flag is automatically cleared when the CPU starts
executing the interrupt vector.
However, if the interrupt is not enabled, the flag just stays set. If
you later enable the interrupt when the flag is already set, the
interrupt request is sent immediately. This is not what you want, you
want the interrupt to fire only on the next match. For this to happen,
you have to clear the interrupt flag prior to enabling the interrupt.
The interrupt flags have a very non-intuitive behavior: you clear the
flag by writing a logic one to it. Thus the line:
TIFR1 = _BV(OCF1A);  // clear interrutp flag

For completeness, I would also clear ICF1 before enabling ICIE1,
although this seems to not be critical for the working of your program.
Also, as a side note, be aware that the timer can increment while the
CPU is in the middle of executing TCNT1 = TCNT1 - ICR1;. If you want
the cleanest possible timings, leave the timer free-running and just set
OCR1A to the appropriate values: ICR1+pulse_delay, then
ICR1+(pulse_delay+pulse_length).

Thank you! I've been pulling my hair out over this, but this finally works!

In case you are interested, I've finished packaging the library this was for: https://github.com/AJMansfield/TriacDimmer


text:
Arduino MIDI Program Change to Voodoo Labs GCX Converter
To define the problem, the L6 Helix can generate 6 immediate MIDI messages. These messages are pretty flexible as to what you want, but the Voodoo Labs GCX needs at least 8 CC messages to properly configure it worst case. Also, I don't want to burn all of my immediate commands to control most of the GCX. So I had the idea to create a Arduino project that would take MIDI PC and MIDI Bank Select to produce a 8 bit value which I could then convert into 8 CC messages between CC#80 and CC#87.

To solve this problem I used an Arduino UNO and a Olimex MIDI shield. I also want to use MIDI PC messages and Bank Selects.
For reference:

A Channel 16 PC 77 with Bank select 0 converts to binary 0x4D => Binary 01001101
A Channel 16 PC 77 with Bank Select 1 converts to binary 0xCD => Binary 11001101

Just to point out, the Bank Select value basically controls bit 8 and the PC value represents bits 6 down to 0
Based on the binary output, I scroll through bits 0 to 7 and send messages on CC 80 to CC 87. If a bit is a 1, I turn the loop on by setting the corresponding CC value to 127 and if it is a zero, I set the CC value to 0.
The Helix can generate a Bank Select and PC as one message, so for the price of one message, this project will make me 8 CC#'s effectively. ;)
It should allow other messages through, with the Arduino's SW loop latency. There maybe some other side effects to, but those should be limited to channel 16 only.
I have tested this on a Arduino UNO board with an Olimex MIDI Shield.
// GCX Editor
// By Rich Maes
// Converts MIDI PC's on channel 16 to GCX CC's starting at 0x80
// Allows everything else to pass.

#define MIDI_PC_CH16 0xCF
#define MIDI_CC_CH16 0xBF
#define MIDI_SYSEX 0xF0
#define MIDI_SYSRT_CLK 0xF8

boolean byteReady;
boolean sendCCMessage;
int ccMsgsToSend;
unsigned char midiByte;
unsigned char capturePCByte;
unsigned char captureCCByte;

// Queue Logic for storing messages
int headQ = 0;
int tailQ = 0;
unsigned char tx_queue[128];

int getQDepth();
void addQueue(unsigned char myByte);
void addCCQueue(unsigned char captureCCByte, unsigned char capturePCByte);
unsigned char deQueue();

static enum {
    STATE_UNKNOWN,
    STATE_1PARAM,
    STATE_1PARAM_CONTINUE,
    STATE_2PARAM_1,
    STATE_2PARAM_2,
    STATE_2PARAM_1_CONTINUE,
    STATE_PASSTHRU
  } state = STATE_UNKNOWN;

void setup() {
  // put your setup code here, to run once:
  //  Set MIDI baud rate:
  Serial.begin(31250);
  sendCCMessage = false;
  byteReady = false;
  midiByte = 0x00;
  state = STATE_UNKNOWN;
  captureCCByte = 0;
  capturePCByte = 0;
  ccMsgsToSend = 0;
}

int getQDepth() {
int depth = 0;
    if (headQ < tailQ) {
        depth = 128 - (tailQ - headQ);
    } else {
        depth = headQ - tailQ;
    }
    return depth;
}

void addQueue (unsigned char myByte) {
    int depth = 0;
    depth = getQDepth();

    if (depth < 126) {
        tx_queue[headQ] = myByte;
        headQ++;
        headQ = headQ % 128; // Always keep the headQ limited between 0 and 127
    }
}

void addCCQueue(unsigned char myCaptureCCByte, unsigned char myCapturePCByte) {
    int i;
    if (getQDepth() < 80) {
        // There is enough space to add our CC messages
        for (i = 0; i < 8; i++) {
            addQueue(0xBF);
            addQueue(80 + i);
            addQueue(127 * ((((myCaptureCCByte * 128) + myCapturePCByte) >> i) % 2));
        }
    } else {
        // This is an error condition.  So reset the queue and pointers
        headQ = 0;
        tailQ = 0;
        byteReady = false;
        for (i = 0; i < 128; i++) {
            tx_queue[i] = 0;
        }
    }
}

unsigned char deQueue() {
    unsigned char myByte;
    myByte = tx_queue[tailQ];
    tailQ++;
    tailQ = tailQ % 128;  // Keep this tailQ contained within a limit
    // Now that we dequeed the byte, it must be sent.
    return myByte;
}

void loop() {
    if (byteReady) {
        if (midiByte >= 0xF0) {
            // This automatically passes all clocks and System Realtime Messages
            state = STATE_PASSTHRU;
        } else if (midiByte >= 0x80) {
            switch (midiByte) {
            case MIDI_PC_CH16:
                state = STATE_1PARAM;
                break;
            case MIDI_CC_CH16:
                state = STATE_2PARAM_1;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }  else {
            switch (state) {
            case  STATE_1PARAM:
                capturePCByte = midiByte;
                state = STATE_1PARAM_CONTINUE;
                addCCQueue(captureCCByte, capturePCByte);
                break;
            case STATE_2PARAM_1:
                if (midiByte == 32) state = STATE_2PARAM_2;
                else state = STATE_2PARAM_1_CONTINUE;
                break;
            case STATE_2PARAM_2:
                state = STATE_2PARAM_1_CONTINUE;
                captureCCByte = midiByte;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }
    }

    if ((state == STATE_PASSTHRU) && byteReady) {
        // Just pass messages unaltered.  Also don't let any of our modified message through if
        // we are passing though.  Our burst of modified CC# can wait.
        // Serial.write(midiByte);
        addQueue(midiByte);
        // state = STATE_UNKNOWN;
    }
    byteReady = false;

    if (getQDepth() > 0) {
        // We have a byte to send, dequeu and send it
        Serial.write(deQueue());
    }
}

// The little function that gets called each time loop is called.
// This is automated somwhere in the Arduino code.
void serialEvent() {
  if (Serial.available()) {
    // get the new byte:
    midiByte = (unsigned char)Serial.read();
    byteReady = true;
  }
}


text:
missing some data after data is sent by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)
I miss some data ( mostly, the latest characters of one data) when I want to send several messages from arduino to another arduino.
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules. If I only want to sent Hello there It works very well but if I want to send several things I miss something. for example for this code, it works very well :
Transmitter:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx();
  delay(1000);
}

receiver:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

the result is :
Device is ready
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
Received: Hello there
for this code I missed some data:
transmitter:
#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{

char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx();
  char msg2[7]="Goodbye";
  vw_send((uint8_t *)msg2, 7);
  vw_wait_tx();
delay(1000);
}

The result is :
Device is ready
Received: Hello there
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t
Received: Goodbye
Received: Hello t

Your array is too short. "Hello there" is char[12] because of the implicit null terminator. so you are corrupting your program. same applies for goodbye. also the receiver code is identical to the transmitter code.

Also,  the delay(1000) in the loop() of the receiver could cause the receiver to be in a wait state while the transmitter is sending something.

Thank you,I did both of these, but it doesn't work


text:
Toggle a led with a switch
My code:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool buttonState = 0;         // variable for reading the pushbutton status
bool ledState = 0;
void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}
void loop() {
  buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
 {
  ledState = !ledState;
 }
  if (ledState == HIGH)
 {
   digitalWrite(ledPin, HIGH); // turn LED on:
 }
   else
 {
    digitalWrite(ledPin, LOW); // turn LED off:
 }
}

So this is supposed to toggle a led's light on and off. currently it does do that but its not always the case. Currently, if the button is pressed on the arduino board, it has a 50-50 chance of changing its state. What part of the code is leading to this outcome?

Do you have a pullup (or pulldown) resistor on your button? If not, then use pinMode(buttonPin, INPUT_PULLUP); then invert button logic, i.e. value is LOW when pushed and HIGH otherwise.

In addition to the debouncing suggested by the other answers, you have a further problem: your loop() will whiz through in a very short time, and run again while your finger is still on the button, turning the light off.  And then run again, turning it back on again, and so on.
You need to wait for the button to be released before registering another change.
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

bool ledState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);   // initialize the LED pin as an output:
  pinMode(buttonPin, INPUT); // initialize the pushbutton pin as an input:
}

void loop() {
  bool buttonState = digitalRead(buttonPin);// read the state of the pushbutton value:
  if (buttonState == HIGH)
  {
    // Poor-man's debounce. There are much better ways of doing this!
    delay(20);

    ledState = !ledState;
    if (ledState == HIGH)
    {
      digitalWrite(ledPin, HIGH); // turn LED on:
    }
    else
    {
      digitalWrite(ledPin, LOW); // turn LED off:
    }

    // Wait for the button to be released
    while (digitalRead(buttonPin)) {}

    // Poor-man's debounce. There are much better ways of doing this!
    delay(20);
}

If you're connecting the button from pin 2 to ground and not using an external pull-up, it can lead to trouble. Either use an external pull-up or set the internal one:
pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input:

Also, you need to debounce the button.

The mechanical switches bounces. That's all. It's too fast for you to see it but MCU is much faster, so output state is switched many times before contacts are stabilized and no more bounces are causing "turning on and off".
The term you are looking for is debouncing

So how may I be able to stop this debounce? is it something I must change from software or Hardware?

If you look for the term debouncing (I don't know, maybe on google), you'll found out there are several ways how to do it. Usual way is "confirmation" of state after about 10ms.

@Utsav Or in this case you can add delay(50) and mentioned INPUT_PULLUP if you don't have external one and it should work just fine


text:
Interrupt routine for button somehow respondng to room lamp turning off and on
I have a sketch that has been running fine on an Uno 24x7 for a few months now.  The part of interest is an interrupt routine associated with a momentary contact switch [on pin 2].  When pressed, the interrupt routine handles debouncing and simply toggles a boolean variable.  The main routine checks status, takes action, warbles a buzzer, and does a Serial.print of the event.
Today, I moved the unit to the other side of the room and plugged it into a different PC via USB. Whilst it was running, I happened to turn on a nearby fluorescent light [not connected to anything but a 120v outlet].
The Uno buzzer went off, and appropriate msgs were written to the serial connection.  I flipped the light back on, and got the same kind of results.  I repeated this numerous times and got the same.  I could flip the light or push the button attached to the Uno, and the results were indistinguishable.
I unplugged the USB cable and used the power jack instead.  I got the same results, sans the print msgs to the serial connection.
The board itself has only a DS3231, an 8x8 LED matrix, a button, two LEDs & resistors, and a buzzer.
What is happening?  How can I resolve the problem?  [If another person had posted this, I would be disinclined to believe it, but surely someone out there understands the situation.]
I can readily supply a minimal code set and a Fritzing if it would help, though I suspect it would not.

Long wires to your switch, missing pullup/down resistor are possible causes of sensitivity to electrical activity near by. Polling a switch rather than triggering an interrupt is more usual.

Yours is a problem of EMI (electromagnetic interference). The ballast from the fluorescent light may interfere via two mechanisms:

Conducted EMI through the power lines (unlikely). In order to rule out this condition, power your Uno through a battery or a battery-powered device (a laptop disconnected from mains). If EMI effects disappear, then you have a problem of conducted EMI and you must use some kind of power-line filter. If it doesn't disappear, then it's a problem of radiated EMI (continue reading).
Radiated EMI (most likely). There are some things you can do to mitigate its effects:

Use wires as short as possible.
Twist wire pairs whenever possible.
Avoid operating conditions that leave inputs unterminated (be sure they're always either pulled up or low). This can easily happen when switchs are used and they leave an input in a high-impedance (disconnected) state.
Increase the debouncing time or use a more robust, glitch-tolerant debouncing routine.
Consider polling the input instead of using an interrupt. However, doing this will be of little use if you don't improve your debouncing routine.
Consider adding hardware debouncing.

Regarding the last three points, I recommend you to read this this. You'll have a better grasp about the art of debouncing inputs.
SPOILER: One thing you can do to make your debouncing routine far more robust is to wait for N consecutive readings with the same value (to happen during a given time T = N x Interval) before considering it good, instead of just waiting for a second reading after a constant time T.

Thank you, very informative.   I'm sure I can handle it from here.
As a note, I used battery power and experienced the same problem, as you predicted.  I also noticed that actually disconnecting the switch has no effect as long as the lead wires [ about 12"] are still in place.  I can easily change the configuration and shorten them considerably.

My guess: pickup on the input line from interference.  (I'd expect this more if the switch were on a long cable away from the Arduino.)
If the button uses an external pull-up resistor, try a smaller value (maybe 5k?).  If it uses the internal pull-up, try adding an external one.


text:
Arduino code is not working for unipolar stepper motor
I am using unipolar 1.8 degree stepper motor. I have written code to rotate stepper motor i.e. when A0 pin becomes HIGH it should rotate in clockwise and when A1 pin becomes HIGH it should move anti clockwise but motor is rotating only once when I am making A0/A1 HIGH and then stops. After that it is not rotating even if i am making A0, A1 pin high. I am very new to this please tell how to solve this problem. I am using microstepping drive, nema 17 stepper motor and Arduino Uno board.
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = A0;
int buttonBpin = A1;
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}

Split the problem up, check you button code is working by using them to light a LED.  Then get your motor spinning.  (Any reason why you are using the Analog Pins?)

I think yo need to read the buttons with analogRead() as you have connected them to A0 and A1 pins of arduino (A0 & A1 pins are analog ).

how many wires does the motor use?

your code looks like it is written to drive a regular motor

I have mentioned in the comments that you should read the buttons with analogRead(). But you can do it other way by simply connecting the button pin to digital inputs on arduino(any from 0-13). Analog pins are mostly used for accessing the sensor data as far as I know. I am correcting your code as below:
#include <Stepper.h>

#define STEPS_PER_MOTOR_REVOLUTION 32

#define STEPS_PER_OUTPUT_REVOLUTION 32 * 200 //2048

Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 9, 8);
int  Steps2Take;
int buttonApin = 4; //connect button to digital pin 4 on arduino
int buttonBpin = 5; //connect button to digital pin 5 on arduino
int dirpin = 8;
int steppin = 9;
void setup()
{
  pinMode(buttonApin, INPUT);
  pinMode(buttonApin, INPUT);
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  small_stepper.setSpeed(1900);
}
void loop()
{
  int valA = digitalRead(buttonApin);

  if (valA == HIGH)
  { digitalWrite(dirpin, HIGH);
    for (int x = 0; x < 100; x++)
    { digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
    }
  }
  int valB = digitalRead(buttonBpin);

  if (valB == HIGH)
  {
    digitalWrite(dirpin, LOW);
    for (int x = 0; x < 100; x++)
    {
      digitalWrite(steppin, LOW);
      delayMicroseconds(1000);
      digitalWrite(steppin, HIGH);
      delayMicroseconds(1000);
    }
  }
}


text:
Working on a simple door lock
this is my first project on an Arduino platform. My aim is to build up a door lock unlockable by playing a short melody on a one-octave piano keyboard. I think the idea is cool!
I'm thinking at everything, but I can't figure out how to make Arduino move something (which in my case would be the proper door lock). I thought about a little motor, but I don't know if it is or not  feasible...
To be clear, what I want to do is a simple door lock like this
(or even simpler) being moved from an Arduino program. How can I do that?

Your question is more about robotics than Arduino. I suggest you post it there: http://robotics.stackexchange.com/

if you need a lock that works w/o power or despite bugs (life safety-level) and with a key, use something like an apartment complex, https://www.amazon.com/Electric-Strike-14C-Extra-Small/dp/B00C0ZENAQ/ref=pd_lpo_60_tr_t_3 , which are pricey, but easy to self-hack. If it's for a hobby or secret compartment, half the fun is engineering something for as close to $0 as possible...

if you don't need to be able to electronically unlock it, you can use a rubber band, a push pin, a piece of iron/steel, some epoxy and one of these electro magnets to get something working. the rubber band pulls back the bolt, the electromagnet keeps it from being pulled back...

You want a solenoid.
Looks like people sell ones which are specifically made for door locks.

Oh, i didn't even know they exist. But I should install it in my door and it's not so viable. I just need something to put ON my door... By the way, thanks for the answer!

I've added a link to the generic type of solenoid, as well as the ones made to function as door locks.  That's what you'll have to do - if you want to move something in an in/out direction, a solenoid is what you want. They come in all shapes and sizes - ones to open car door locks, ones to open gas valves. You'll have to dig around and find the right one for your application, but I hope knowing what it's called will get you started.

Well, sure! I'll search about!

solenoids are unsafe because strong magnets can reach through the door to unlock by sinking the plunger. make sure it doesn't retract w/o power as well.

@dandavis That is true. Anyone could get into your bathroom simply by employing an enormous electromagnet in the other side of the door. Those bolts pictured in the question, however, are widely known to be able to withstand a force equivalent to the weight of six blue wales.


text:
Do (cheap) SD modules support file I/O?
I noticed there are cheap SD modules and complete SD shields.
I assume the last are used for a 'final' product and not for bread-boarding (?)
However, I was wondering, is there also a difference in functionality or more important, support for e.g. the sd library (thus having file I/O in addition  to SPI interface)?
E.g. can I use the file I/O and the SD library with the This SD module?

i don't know weather any shields does not support file IO.

@PrashanthBenny and would the SD module I mention support file I/O with the sd library?

this module supports SPI interface, it is likely to work with the arduino SD library.

I have not seen one not work myself!

Thanks (going to try it ... after I do some basic experiments getting the Arduino today).

I have never managed to get an SD card reader to work, and yes I have tried one that looks like it might be that one.

There are Uno compatible SD shields which are great for prototyping IF you are using an Uno, they don't work too well with a Nano.  The modules are fine, but you end up with wires everywhere, but they do work with more formats of Arduino.
The ability to do file operations is separate to the protocol you use to talk to the module (SPI).  Lots of device (not just SD cards) use SPI, but not all of them do file operations.  An LCD, a GPIO expander, an EEPROM memory chip are all examples of devices that could use SPI.
What actions the SD module/shield is capable of is really up to the library/software.  The module will have to comply to some set of standards and this will let the caller perform certain operations.  Lets say one of the operations is to read one byte from an address.  This operation would need to be used by the library to read a file, also it would need to use it to find where the file is.  It would also need it when writing a file, because it would need to know what free space was left on the card.  You are shielded from all this by the Library you probably have a read file, write file and delete file function.  (This is an example of abstraction which you will see a lot in programming).
The will also have a set of standards to allow a controller to interface with the module, SPI, I2C, Serial or a proprietary one.  These communication protocols allow the controller to send the file commands to the module, like the read command above, and lets the module return data to the controller.
So to answer your question

If you use a module and shield that use the same IC (chip) to access
the SD card and the same library then they will almost always behave
the same.
If you use two different shield (different ICs) which
need different libraries then they MIGHT have different
functionality.
If you use two different shields which use the SAME library then the MIGHT have the same or different functionality.

Summary : Yes No Maybe :)
If you want something special find a library that does what you want and then find a bit of hardware supported by that library that also does it.  Otherwise, chances are you will be fine.
==== Edit ===
When you think of hardware/software abstraction think of it as a Television.  You deal with the TV at the very highest level, you turn it on/off and change channels.
When you change channel what really happens is the remote control converts your button press into an encoded infra-red signal which hopefully hits the TV and the TV decodes this and executes some code which selects a pre-programmed channel.
Now you don't care about that all you care about is you press the button and you favourite soap opera appears on the screen.
There is another level of abstraction that is happening when the TV selects the pre-programmed channel, it has to convert the signal into some reference to the stored information that produces some information that is passed to the tuner and....  Well it just gets silly, you just want to watch your soap.
So back to the subject in question, you buy a SD reader module, you find a library that works with it and in your code you call WriteFile().  Does it really matter how it does it?  Do you care that the library is scattering you bytes across the SD card? Well as long as it retrieves it no not really?  Does it matter that WriteFile() is actually storing it on the hard disk of a PC somewhere in the world?
Your call to WriteFile() is abstracted away from the underlying process hiding it, because it doesn't really matter.  Most of the libraries use this Abstraction process, look at the code in Wire.cpp, it looks really simple when you are calling read() and write() but it isn't.

Thanks for this detailed answer (although I have to find some more info about what are all consequences ... like you talk about a 'controller' but on a SD module, does it contain the controller already ?
For example, can I use the SD library (and thus file I/O) with the module I mention above (in my updated question)?

Sorry - By 'Controller' I mean the Arduino.  The SD Module/Shield needs to be controlled by an Arduino (or similar).  It will have an IC (silicon chip) on the SD module that accesses the hardware but this provides the lowest level of commands, much lower than you want to worry about.

Thanks again ... yes of course I should have known (that the Controller is the Arduino). Just getting into it (getting my first Arduino tomorrow).

Short answer. Yes, it will work.
I have used the same MicroSD Card Adapter module [it is marked MOSO instead of MISO on one of the pins] for a few projects.  I found no problems or special considerations doing so [except for getting the pin mapping correct].
In contrast, I've used one shield that worked sporadically, because of intermittent header contact.  It would work for a while, then stop until I "massaged" it properly.  It was probably just a bad assembly, though.
Many people prefer working with shields, while I do not, and would rather build on PCB board once I have a working version of my project.  It's cheaper as well.


text:
A question on physical locations of the registers in ATmega328P
When I read about registers I always encounter the following illustration:

So there are 32 registers in the above diagram. They are processor registers.
But in the data-sheet of ATmega328P at page 428 there is a section called "Register Summary".
Here in that list there are much more than 32 registers. Do the rest of the registers physically stay somewhere else?
Lest's take an example of ADMUX register. Where is that register physically inside the DIP? It is not one of the 32 registers? And if stays somewhere else how does it connected to the ALU?

Physical location or memory location? The datasheetss has the later.

I mean is ADMUX one of those 32 reg?

In the table that you refer to, ADMUX is mapped to memory location 0x7C.

No, R0 to R31 are General Purpose registers for use in your application. The compiler usually takes care of using them appropriately. All the other registers are special purpose and can only be utilised explicitly. Those registers form the state machine of the MCU.

Is GPIO a subset of SFR?

And are they all SFT and 32 tegistrts all inside sram?

You are confusing CPU registers and SFRs, Special Function Registers.
CPU registers only exist within the CPU core. SFRs exist within the RAM bus's memory map.
CPU registers are used by the CPU to execute instructions and do calculations, etc. SFRs are a part of the logic of the rest of the chip and directly affect the working of the various peripherals.
As far as the CPU is concerned an SFR is just a bit of SRAM, but it affects physical workings when written to, and reflects physical states when read from.

Chapter 8.3 in the ATMEGA328P datasheet (ver 10/2014) has a memory map of SRAM. Here it uses the term IO Register and Extended IO Register to refer to the Special Function Registers.

Every manufacturer has their own name for them. SFR is an accepted standard name for the concept.

Are those 32 registers called GPIO?

No. They are called registers. They are the internal memory of the CPU. You have very limited access to them in C, but in assembly they are all you have for doing any form of calculations with.

Some wrote under my question that they re called general purpose registers. Is that right?

Yes, since the CPU can use them for any purpose it needs. Really, unless you are writing assembly language programs, you don't even need to know about the existence of these 32 registers. They are like the spark plugs in your car - you don't need to know about them to be able to drive it.


text:
What controller should i use?
I'm working on a little DIY project in which I intend to make my own dataglove. Now I'm kinda stuck on choosing the right microcontroller. And since it can be quite costly, I thought to ask for some help.
So: I'm going to use 12 flex sensors (maybe 14) and 1 IMU (probably the 6050). now the problem is that I need a total of at least 14 AI.. And the small controllers only have about 6.
The controller can't be too big for dexterity reasons and also will need the availability to add a Bluetooth module.
I've been looking at some multiplexing/shield options but I'm just not confident (and rich) enough start ordering..
Peace out,
Lars
PS: other brands besides Arduino work for me to

Use suppliers parametric searches. I use PIC32 mainly, and I know they have plenty of analog inputs.

How about a Teensy? The guys that make Teensy have developed many of the well known Arduino libraries and have also helped develop the Arduino IDE in the past so they know their stuff.
I see the Teensy LC at about $11. the spec says its almost the same as Teensy 3.1 which has 20+ Analog In
https://www.pjrc.com/store/teensylc.html
https://www.pjrc.com/teensy/index.html
The 3.1 and 3.6 are more powerful and more expensive at around $29
note: Read the index for which boards are 5v tolerant if that's what you need.


text:
Initializing pointer to vector of objects inside another object
i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):
INO file
#include "LedDevice.h"

LedDevice device;

void setup() {
  device = LedDevice(10, 10, 10);
}

void loop() {
  Serial.println(F("Ticking"));
  device.Tick();
  delay(500);
}

LedDevice
#if !defined(_LEDDEVICE_H)
#define _LEDDEVICE_H

#include "Preset.h"
#include<Arduino.h>

class LedDevice {
public:
  Preset* Presets[];

  LedDevice(){}
  LedDevice(int numPixels, int numPresets, int numPatterns)
  {
    *Presets = (Preset*)malloc(sizeof(Preset) * numPresets);

    for (int p = 0; p < numPresets; p++)
    {
      Presets[p] = new Preset("test", numPixels, numPatterns);
    }
  }

  void Tick()
  {
    Serial.print(F("Preset ")); Serial.println(Presets[0]->Name);
    Presets[0]->Tick();
  }
};

#endif  //_LEDDEVICE_H

Preset
#if !defined(_PRESET_H)
#define _PRESET_H

#include "Pattern.h"

class Preset {
public:
  char *Name;
  int NumPatterns;
  Pattern* Patterns[];

  Preset(char* name, int numPixels, int numPatterns) : NumPatterns(numPatterns)
  {
    Name = (char *)malloc(strlen(name) + 1);
    strcpy(Name, name);

    *Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p] = new Pattern(numPixels);
    }
  }

  void Tick()
  {
    for (int p = 0; p < NumPatterns; p++)
    {
      Patterns[p]->Tick();
    }
  }
};

#endif

Pattern
#if !defined(_PATTERN_H)
#define _PATTERN_H

class Pattern {
public:

  Pattern(int numPixels){}

  void Tick(){}
};

#endif

The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.
Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.
Can you tell if anything is not being done correctly in the constructors?

You may have provided enough info – I don't know – but I think it would be helpful if you edit your question to include a Minimal, Complete, and Verifiable example of code, as well as the snippets.  Otherwise, anyone who wishes to test an answer before posting it has to do the busy work of putting the snippets together.

My concept of what new does is: allocate memory for an object and construct the object.  Doesn't *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets); allocate memory for an array of Presets and for ... Presets[p] = new Preset(...) allocate the same amount again?  (This would be a problem, not the problem.)

I'm new to Arduino, but isn't it possible to use a 2 dimensional array (of Pattern)? Or does Device has more properties than only a list an array of patterns?

@jwpat7 I added a complete version of the code. If i remove the New keyword from the objects initialization it complains that "cannot convert 'Preset' to 'Preset*' in assignment", so i tought it was still necessary despite the malloc.

@MichelKeijzers each class, LedDevice, Pattern and Preset has other attributes and functions, therefore i need a class for each, even a structure won't do. I'm already having issues initializing 1 dimensional array, if i go for 2 i guess it will be even worse

@LuisFerreira yes in that case it's getting worse (if you need more). I think the problem might be in too much initialization like jwpat7 says above. But I only know C and C++, not Arduino language yet well enough to answer.

@MichelKeijzers i just read this tutorial: https://arduino.land/FAQ/content/4/26/en/how-to-use-dynamic-memory.html
which clear some doubts. Using New is the C++ way of reserving memory. Malloc is the C way. Only one way is needed. I will do some more tests knowing this.
And Arduino uses GCC to compile, so its C++ and C compatible

Three things that need to be different:
Pattern* Patterns[];

should be
Pattern** Patterns;

It's a pointer to some pointers to patterns, not a pointer to an array (which is basically a pointer itself so same basic idea but an array implies a known size).
and
*Patterns = (Pattern*)malloc(sizeof(Pattern) * NumPatterns);

should be
Patterns = (Pattern*)malloc(sizeof(Pattern*) * NumPatterns);

*Patterns is the thing pointed to by Patterns which at this point is undefined. You want to set Patterns to the allocated address.
And we only need to allocate space for the pointers not the actual objects.
Your for loops then become
for (int p = 0; p < NumPatterns; p++)
{
  (Patterns+p) = new Pattern(numPixels);
}

You then have the same issues with Presets.
And finally
LedDevice device;
void setup() {
  device = LedDevice(10, 10, 10);
}

should be
LedDevice device(10, 10, 10);
void setup() {
}

Thank you for the input, some of those errors i was aware, and others i didn't know, but i can understand the logic now.

Sorry, just realised that the origional post was wasting too much memory, As Nick pointed out the new command is allocating the space for the actual objects. All you need to malloc is enough space for the pointers to those objects rather than enough space for the entire objects.

This is wrong:

Device device;

void setup()
{
   device = Device();
}

I don't know what your intentions are, but the first line instantiates device. You don't need to do anything in setup here. It sort-of looks like you are trying to call the constructor but that is called when the class instance is created (in the first line).

Preset* Presets[];

What's this? A pointer to an array of zero length?

    *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);

Now you are allocating memory for a pointer to the array to be big enough to hold the contents of the array.

for (int p = 0; p < NumPresets; p++)
{
    Presets[p] = new Preset("test", NumPixels, NumPatterns);
}

Now you are allocating memory for the contents of the array again.

There is too much dereferencing going on here. Please post a Minimal, Complete, and Verifiable example. For example, make the classes in question do not much. Then make code we can actually work on.

I realize the first call is to the default constructor, but in the setup i do the real construction ...

Well, you can't call the constructor twice. What is commonly done is to do nothing (or almost nothing) in the constructor, and then make a begin function which you call in setup. This function can then do whatever is required at the proper time.

I just updated the code to a Complete version. Here are some answers:

i declare Device, now named LedDevice outside of the setup because i want to use it in the Loop cycle as well. Is there another way to do it? I realize the first call is to the default constructor, but in the setup i do the real construction
I would like to be able to initialize the Preset and Pattern vector during run-time, so i am creating a pointer to a vector that i don't know the size yet. At least that's what i tought, is this wrong?
so i dont need to use both malloc and new? what is the correct way?

See amended answer.

malloc allocates memory. new also allocates memory but also calls the constructor. You should use new when allocating memory for classes.


text:
Connecting two arduinos with wifi over the Internet
I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.
Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.
One board with only send data, and one will only receive.
Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.
thx in advance :)

i don't see why you need the unos for this, just use two ESPs to keep cost and complexity to a minimum.

How long is a "long" distance?

need two uno as one is connected to a senor which gives analog output,whicle the other is used to control a screen(LCDor led)and a few servos.long distance means communication over the internet.

The ESP8266 has one analog port and and supports SPI and I2C which will let you connect to a range of ADC devices.  Look at the ESP8266 12E of 12F.

The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.
If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

So can I send and receive real time data over the internet, and
  receive it fast?

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?
Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).
tl;dr: The network will be a much greater limitation than the ESP devices.
Update:

the problem i see is the delay with communication over the internet
  between the two uno if i use a server.can i communicate between the
  two with out the use of a server

Of course. Using an intermediate server might be a useful step on the way to getting your devices to talk directly. It would allow you to focus on the clients themselves at first and leave (most of) the networking issues to work out later. But you'll still have the issues of any network and especially a public network. If you have no other choice, you build it and you get whatever you get for performance. How serious are the consequence of a delay or a lost packet? Inconvenience? Delayed system functions? Will it cost someone money? Could someone get hurt? Could someone die? How dire the consequences could be will determine how stringent (and expensive) your solution has to be and what backups might have to be in place.

thx for ur reply, 9600 baud should suffice (need to practically check),but the problem i see is the delay with communication over the internet between the two uno if i use a server.can i communicate between the two with out the use of a server

Have you considered using Particle Photons instead?
They're $19, wifi enabled, Arduino compatible and they come with a very extensive cloud API functions that will allow you to pass information between them really easily:
https://docs.particle.io/reference/firmware/photon/

looks promising but its too costly.


text:
Does SoftwareSerial use hardware timer?
I'm asking this because I'm using a timer to generate a 38KHZ signal to drive an IR diode, and I also need to use SoftwareSerial to talk to an HC-12 radio using serial communication.
The code I'm using was written by Nick Gammon and is here:
//Setup Conter/overflow to create 38KHZ drive for IR38KHZ
//38khz, no interrupts
#define IR_CLOCK_RATE 38000L
// toggle on compare, clk/1
TCCR2A = _BV(WGM21) | _BV(COM2A0);
TCCR2B = _BV(CS20);
// 38kHz carrier/timer
OCR2A = (F_CPU/(IR_CLOCK_RATE*2L)-1);
pinMode(IR38KHZ, OUTPUT);

I'm not quite up-to-date on the timer use on an Arduino (I'm using a Nano), plus I've no idea what the SoftwareSerial library uses.

No. It uses pin-change interrupts to trigger reception, and both reception and transmission use calibrated delay loops.  However, interrupts are disabled during both transmission and reception so that the calibrated delay loops remain always the precise length - so if you do anything with any other interrupts they will not work at the same time as SoftwareSerial.

The SoftwareSerial uses almost all cpu time. The AltSoftSerial uses less cpu time, but it does use Timer1 : https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
Since you use Timer2, you still have the option to use AltSoftSerial.
Even when all three timers are used, it is still possible to add a speaker to your Nano with TimerFreeTone: https://bitbucket.org/teckel12/arduino-timer-free-tone/wiki/Home

When I try to link to altsoft serial, I get this:The owner of www.pjrc.com has configured their website improperly. To protect your information from being stolen, Firefox has not connected to this website.
This site uses HTTP Strict Transport Security (HSTS) to specify that Firefox may only connect to it securely. As a result, it is not possible to add an exception for this certificate.

I was able to get a copy of the library directly from github......now to try it out.....THANKS.


text:
Arduino 5v output dead?
i've got a bit of a problem with my Arduino UNO.
So coming back to my (pretty basic) build after a bathroom break, I go to un-assemble my circuit (on the breadboard) and grabbing the LED causes a static shock.
Since then I haven't been able to get any power to come out of the Arduino to the breadboard circuitry.
I have tried:

Different Breadboards
All new parts, LED's/cabling/buttons/resistors.
Different power and ground cables (from Arduino to breadboard)
Giving the Board more time to 'cool down' (I heard there was a
temperature based reset device?)
using the 3.5v output (I'm not sure if by doing this i should remove
the resistor? i'm VERY new to electronics
using the alternate ground input

Looking around here for 'shorts' or 'damaged Arduinos' returns mostly results about non communication to the board. the difference here is I can absolutely still upload programs to my Arduino and then run them (I've only tried the pre-existing blink, but i don't think there is any difference). And my computer's USB ports are also fine. So if there is a duplicate question i apologize, but i haven't been able to find anything related.
Any help would be much appreciated!

What does  “get power to come out of the Arduino to the breadboard circuitry” mean?  Which output pin isn't working?  Have you tried some other pins?

But you can still upload and run the blink sketch on this 'damaged' Uno ? WIre a led (it's polarity sensitive) with a series resistor say 330R between the GND pin and +5V pins on the Uno to show if you have power there, then check the connections between the Uno and the breadboard.

If you got zapped touching an LED and the circuit doesn't work any more, and since you're sure the Arduino uploads programs OK, then either the LED (or something else on your breadboard) or the pin driver within the Arduino is probably damaged.

Try changing the LED.
If that doesn't work, try changing the pin(s) the sketch uses to talk to your breadboard, rewire your breadboard to use those pins, and test again. If it works this time, the pin driver was probably damaged.
If there are any other components (e.g., not wires or resistors) on the breadboard whose failure might cause the LED not to light, replace those and test again.
If replacing the external components doesn't fix it, and if your Arduino's MCU is a 28-pin chip in a socket, a new one with the bootloader already loaded into it typically costs $5-$6 in the US.

Update:

...i have listed all these things as already tried.

Right - I read right past it. :( So you've done the right things (except no mention of testing other pins) so I'm not sure what your question is. The title asks about the board's 5v supply but that must be up b/c your board uploads and runs Blink. That really leaves only the the pin driver(s) you were using when you zapped it.
You can salvage the board by testing all the pins in their input, output, analog, and other functions, and make a note of what capabilities have been lost. Clearly not all of them - pin 13 still works, for instance, because Blink worked. You can't repair damage internal to the chip without replacing it, and I would always consider it suspect, but it will be fine for many hobby uses if you just avoid the damaged functions.

In my OP i have listed all these things as already tried.
Looks like i'll just have to pick up a new Arduino then :(
Thanks!


text:
Arduino and USB power, what to choose
I am a beginner at Arduino. I want to power the Arduino through the USB cable that is usually plugged in the USB of the laptop, but plugged in the wall instead of the laptop.
Here are my questions:

Can I use a phone charger that has a USB (in which the end of the USB
cable will go instead of the USB of the PC)?
What should I look for written on the charger so it is best
compatible?
Is it ok to be done that way?
Will it be the same as means of power like when it is plugged in the
PC (for example when later on I connect LCD display, diodes, etc.)?

I did my research, but it got confusing, so I wanted to ask my own question. Thanks in advance.

Yes, you can power the Arduino using a USB phone charger.
The Arduino Uno draws less than 100mA when connected by itself. So ideally you would want the USB phone charger to provide at least 100mA. All of the USB chargers I have come across to date provide more than 400mA. Most of the modern USB chargers provide upwards of 1A for fast charging of your phone.
A USB(2) port of a laptop can provide up to 700mA to the Arduino (500mA continuous).
In terms of the overall current draw, it really depends on what you have connected to the Arduino. LEDs generally draw 20mA or less per LED. Some screens can draw anything from <100mA to a couple of amps. Most of the screens I have come across draw less than 1A. It really depends on the devices you want to connect.
For the most part, a USB charger will be sufficient.

As you are still a beginner so I would not go into complex details. Your Arduino can run perfectly on a laptop powered USB but try to avoid connecting the power hungry electronics with your Arduino while powering it from the laptop USB port.
A Laptop USB port can give nearly 700mA that is enough for Arduino to run a couple of sensors easily.
Secondly, most wall chargers give 1A(1000mA) current that is better in my opinion. It can handle some power hungry electronics better then connecting your Arduino with the Laptop USB port.
I personally power my Arduino with either a Wall Charger or a power bank. Hope it helped solve your problem.
The more you dig into Arduino, the more fun it becomes. So have fun and be Creative.

How many V should the charger be? 5V or 12V? @M. Hussnain

He doesn't really have to worry about blowing up his USB port on the laptop, the arduino board has a 500mA poly fuse on the USB power in line so it should blow before his laptop USB gets damaged. You can't draw more than 500mA from USB, you can only draw about 1A from the barrel power jack, although it's the absolute maximum as the voltage regulator will get very hot very quickly.
@the.matrix the barrel jack must have more than 7 volts to get 5V out of it, but try to keep it as close to 7V, 9V is fine, 12V is meh. The bigger the voltage difference (Vin - 5), the hotter it will get.

And how many volts should a charger that goes into the USB be @Andrei Dragan ?

The USB voltage is 5V.

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 on Arduino bypasses the regulator, and can damage your board.

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


text:
Arduino Serial and myserial clarification. How to print out rx output?
I currently have a camera I am trying to run off an Arduino. I am new to Arduino and I have had trouble figuring out what serial and myserial really do. I also don't understand why, when I have something like serial.write(0x56) I will get the output in the serial monitor to be V in hex, but If I have the Arduino also connected to an oscilloscope, I won't be able to see the signal.
Yet if I have myserial.write(0x56), I won't see anything in the serial monitor, but will see the bits on my oscilloscope.
Also, if I send a command to my camera, my camera should send back some hex values if the write command is sent. I understand I can send commands via myserial.write(0x56), but how would I read the hex values the camera would send back?

It seems like you are using both the hardware UART pins and two other pins for SoftwareSerial i.e. UART emulated by the arduino.
When you write Serial.read() or Serial.write(), Arduino knows to use the UART hardware on the chip which is has RX/TX pins 0 and 1 for most Arduinos. So by using these functions you will be able to communicate with any device which is connected on these pins.
Generally, when you have the Arduino connected to your computer, these RX/TX pins internally go to a serial port on your computer via the USB, hence you can send/receive data to the computer and view it on the Serial Monitor. Great for debugging purposes!
Sometimes, like in your case for controlling the camera, you need to have another serial port for communication because UART is point to point i.e. only 2 devices can communicate via it. SoftwareSerial helps you do that by using  two other pins on the Arduino into RX/TX pins. If you look at the top of your code file you will see a line like this
SoftwareSerial mySerial = SoftwareSerial(...);

Inside the brackets you will also see the two pin numbers which are being used as RX/TX. In the software serial example pins 10,11 are being used. So whatever is connected to these pins (i think your camera module is) will be able to send/receive data using mySerial.write() and mySerial.read().
Hence, to be able to receive data from the camera you will use mySerial.read().


text:
sleep and wake up arduino mega according to ds3231 interrupt
how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.
here is my code
#include <DS3231.h>
#include <Wire.h>
#include <avr/sleep.h>

 int wakePin = 2;   // pin used for waking up
 int led = 13;

 DS3231 clock;
 RTCDAteTime dt;

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

 // initialize DS3231
 Serial.println("Initailize DS3231");
 delay(100);
  clock.begin();
  pinMode(wakePin,INPUT_PULLUP);
  pinMode(led,OUTPUT);

   //Disarm alarms and clear alarms for this example, beacuse alarms is battery backed.
   //Under normal conditions, the settings should be reset after power and restart microcontroller
   clock.armAlarm(false);
   clock.clearAlarm();

   //Set Alarm1 - Every 20s in each minute
   // setAlarm1(date or day,hour,minute,second,Mode,Arrmed=True)
     clock.setAlarm1(0,0,0,20,DS3231_MATCH_S);
     attachInterrupt(0,wakeUpNow,LOW);

   //check alarm settings
    checkAlarms();
  }

   void checkAlarms()
  {
   RTCAlarmTimea1;
   RTCAlarmTimea2;

    if (clock.isArmed1())
   {
    a1 = clock.getAlarm1();

     Serial.print("Alarm1 is triggered:);
     switch(clock.getAlarmType1())
    {

       case DS3231_MATCH_S:
       Serial.print("When seconds match: ');
       Serial.println(clock.dateFormat("_ _:_:s",a1));
       delay(100);
        break;
        default:
         Serial.println("UNKNOWN RULE");
         break;
     }
    }
   }

       void wakeUpNow()
   {
       //execute code here after wake-up before returning to the loop() function
      //timers and code using timers(serial.print and more...)will not work here.
     //we don`t really need to execute any special functions here, since we
     //just want the thing to wake up
      Serial.print("Woke up");
     delay(100);
     }

      void sleepNow()
     {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);  //sleep mode is set here
      sleep_enable();   //enables  the sleep bit in the mcucr register
      attachInterrupt(0,wakeUpNow,FALLING); //use interrupt 0(pin2) and run function
      sleep_mode();
         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

         sleep_disable();  //first thing after waking from sleep: disable sleep
         detachInterrupt(0); //disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
          time.
        }

         void loop()
        {
           dt=clock.getDateTime();

             Serial.println(clock.dateFormat("d-m-Y H:i:s-I",dt));
              delay(100);
           //Call isAlarm1(false)if you want clear alarm1 flag manualy by                     cleaAlarm1();
              if(clock.isAlarm1())
           {
                 Serial.println("ALARM 1 TRIGGERED!");
                 digitalWrite(led,HIGH);
                   delay(1000);
                  digitalWrite(led,LOW);
                  Serial.println("Entering Sleep");
                    delay(100); //sleep fucntion called here
                     sleepNow();
               }
                delay(900);
               }

It depends what you mean by sleep here. There are methods for putting the chip into an inactive sleep state for extreme power savings in battery powered applications. I guess here you simply mean that during a certain period of the day, as determined from the real time clock, you want to suppress the sensor monitoring and the solenoid valve activity. Is that correct or is your goal to minimise power consumption in a battery powered application ?

both..is it possible??

Yes it's possible. For extreme power saving techniques with AVR (which Arduino Mega) look at http://www.gammon.com.au/power . However, if your application includes a solenoid valve then shaving a few microamps from the power consumption through cpu sleep/wakeup cycles may not make a big difference to the overall power consumption. I'd start by reading the  RTC in the loop, determining if is day or night, reading the sensor and switching the valves as necessary, then as a later activity, optimising the power consumption.

i have separate power supply for my solenoid valve

can you help me fixing a code for it? I will send you my sketch and you can change it and send it back. please help me.

If you've currently (a) got some code and (b) have some specific questions about correcting or adding features to it, then post these here.

First, Arduino Mega does not have an RTC (Real Time Clock) built-in. So, to program it the way you like, would mean either using a module like DS3231 or similar, or have the Mega connected to internet, with a network card module like ENC28J60 and getting the time from there. If you don't use any of those methods basing your scheduler only on the Arduino internal timer (using sleep for example) will result in program needing to set the correct time each time Arduino is powered.

i have RTC ds3231 and Arduino mega 2560, solenoid valve, soil mosure sensor


text:
Arduino Serial Port. COM1 does not exist
Hello everyone I'am new to this site so please bear with me.
I have an Arduino Uno that I'm using in my simple project using VS 2008. I got this error says The Port COM1 does not exist. The flow of my project is after inserting a coin into the coin slot the arduino will pass the data into my project and it will display into a Label or Textbox the value of the inserted coin.

This error is not on Arduino side but on the PC side (.NET code or configuration), hence off-topic here. Voting to close it.

Probably it is on another COM port. When I checked my IDE (from Arduino) the Arduino was found at COM3.
You probably have to iterate through the (PC) COM ports to find out where the Arduino is connected to.

Thakns. I inspect my PC Manager and I don't an arduino driver

Never used Visual Basic but:

There is no such thing as Serial1 on Arduino Uno. There is only Serial. (Serial1, 2, 3 are available on ArduinoMega) Reference: Arduino
For COM port you should check your device manager. Often it appears at COM3 so probably you should check this issue.

Just for curiosity: Why VB? Is it only your choice or it use less ram or memory, works faster or anything?

The Serial1 is from the design built-in in VS 2008 or 10. Just for curiosity: Why VB? A: don't know how to use another language yet

Can you program an Arduino?  If so you know the basics of C C++ and C#(.Net).  Switch from VB to C#, its better, trust me, and won't take much learning.


text:
Explain what is meant by "Arduino core"
What is an "Arduino core"?
Are there many different "Arduino cores"? such as a core that applies to LCD
displays, another core that applies to servos, etc.?

The Core is the software API for a specific group of chips.
For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.
It is the code that provides things like digitalRead(), analogWrite(), millis() etc.
Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.
In your default IDE installation the Arduino AVR core can be found within the hardware/arduino/avr/cores/arduino folder.
Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.

The "core" provides the low-level APIs (Application Programmer Interfaces) which are documented in the Arduino Reference page. For example, digitalRead, digitalWrite, delay and so on.
The core files usually contain the "include" files from Atmel which provide documented names for the various registers in the chip (eg. DDRB for data direction register B).
Since each chip type will have different addresses for the registers you will need a different core for each processor chip. Also in some cases people have assembled the chip onto different boards, and the cores will reflect how the board is wired. For example "edge pin 8" on one board may connect to a different pin on the processor chip compared to another board. Thus if you buy a board from a third-party they may also supply their own core files.

Are there many different Arduino cores such as a core that applies to LCD displays, another core that applies to servos?

These are usually implemented in libraries which you can optionally include into your code. The libraries extend the core. Often the same library will work with different cores as the core code handles the differences between chips, so that the library doesn't have to.

Selecting a core
As Majenko mentions in his answer, selecting a board in the IDE (Integrated Development Environment) usually tells the IDE to select the appropriate core for that board/chip combination.
More recent versions of the IDE allow you to install more cores by providing a link to where the core files are to be found, and then allowing you to choose one or more cores from that site.

As far as I know the cores are the different products which can be found at Products. In this list the Arduino cores can be selected in the IDE: Cores
LCD display (driver) etc. are mostly referred as shields or modules. A shield is a small 'board' you can stack on top of the Arduino (Core) and a module is normally to be used on a breadboard.

The collection of MCU's that are part of the Arduino family have differences from one to another in features like the address in memory-space of the basic processor registers, the I/O pin assignments to the I/O registers, nature and operation of timers, A/Ds, etc. The kinds of things we do with calls like pinMode(), digitalWrite(), or attachInterrupt().
These are considered the basic or "core" functions to be presented to the programmer by using libraries to present a common interface and hide those differences. The core libraries are managed by the Arduino IDE and the proper one(s) are selected when you select a board-type from the Tools | Board menu.
This is different from the user-contributed and other non-core dependent libraries you keep in your workspace 'libraries' folder. Both kinds are code libraries, but the so-called "core-libraries" are specific to the kind of processor you are compiling your sketch to run on.


text:
Tiny RTC I2C module not working
I bought a Tiny RTC I2C module and it doesn't work.
When i run the TimeRTCSet from TIME library all i get is:
Unable to sync with the RTC
0:00:00 0 0 1970
0:00:01 1 1 1970
0:00:02 1 1 1970
0:00:03 1 1 1970
0:00:04 1 1 1970
0:00:05 1 1 1970
0:00:06 1 1 1970
0:00:07 1 1 1970

The module is connected like this:
Vin -> 5V
Gnd -> Gnd
SCL -> A5
SDA -> A4
I'm using arduino uno.
I tried with a simple i2c scanner, but it returned two devices!
Scanning...
I2C device found at address 0x50  !
I2C device found at address 0x68  !
done

Only the clock is connected. I tried removing the battery for night to reset it, but it didn't fix it.
Could you help me?

Could you please edit your question to include a link to the I2C RTC you are using.

The RTC module includes a memory module which is also addressable via I2C hence the 2 addresses. Have you tried sample code like here: https://www.elecrow.com/wiki/index.php?title=Tiny_RTC

Looks like the RTC is running correctly but has not been initiated with the current time?

This issue can be fixed by deleting the library downloaded using arduino library manager and replacing it with the library from github.

Try using the example code from the MD_DS1307 library to find the settings on your RTC, when I first wired mine up the clock was not running and I couldn't set the time on it. After I enabled it, it worked just fine.

Thank you for help. I fixed the issue. It was caused by the library which I got from arduino library manager. I deleted it and downloaded the library from github. Now it works great.