body:
I have the Arduino Starter Kit and I'm on project 10 Zoetrope. I've removed the switch that changes the direction as I don't want the reverse to happen when I press a switch. I want the reverse to happen based on time.

For example using code, I want the reverse to happen every second (the motor moves clockwise for the first second, counterclockwise for the next second, clockwise for the third second etc.)

I've search for solutions but I haven't found anything yet. I had no luck with the `millis` function as well.

title: Reverse DC motor direction every second automatically

Answers: 1

body:
Consider code of the following form.

    // Declare some globals
    byte direction=0, second, prev=0;

    void loop() {
      second = millis()/1000;
      if (prev != second) {
        prev = second;
        direction = second & 1; // Direction is 0 or 1
        OutputTheNewDirection(direction);
      }

More generally, suppose you want to make a pattern of clockwise for *j* time units, alternating with counterclockwise for *k* time units.  Suppose a time unit is *m* milliseconds long.  You can use code as in the following example, where *m* is 500, *j* is 10, and *k* is 1.

    // Declare some globals and constants
    byte direction=0, tunit, prev=0;
    enum { m=500, j=10, k=1 };

    void loop() {
      tunit = (millis()/m) % (j+k);
      if (prev != tunit) {
        prev = tunit;
        direction = tunit < j; // Direction is 0 or 1
        OutputTheNewDirection(direction);
      }


body:
I have a 9V Lion 990mAh battery. I am not sure if I can use it to power an Arduino externally?

Can you please guide me how to understand current specifications of any device?

Thanks and Regards,
Manish

title: Can I power my Arduino Uno with a 9V / 990mAh battery?

Answers: 2

body:
It says 7-12v on the site, so it should work https://www.arduino.cc/en/Main/ArduinoBoardUno

You can look at the datasheet for the Atmega328, but the current largely depends on what you connect to the Arduino. So it all depends what you do with it. It can certainly power and idle Arduino, driving motors and dozens of LED's maybe less so.

body:
While this answer addresses the specific question it should also prove useful as a link to resources relating to current reduction in other microcontroller projects.

Short:

The "C" rate for a cell is a current in mA numerically equal to the capacity in mAh
eg 1000 mA for a 1000 mAh cell.

In the absence of a specific data sheet a LiIon or LiPo cell is **probably** safe for maximum charge and discharge rates of C/2 and C.
ie 500 mA max charge rate for a 1000 mAh cell and
1000 mAh max discharge rate for a 1000 mAh cell.

In many cases double those rates will be safe.
Charge rates are seldom higher than C but discharge rates of substantially higher than 2C MAY be safe - see data sheet!.

In your example case, the operating time will be approximately mAh/average_current. Consult the data sheet for your microcontroller and/or measure current drain.

A typical "bare" Arduino with processor, USB IC, LEDs and "glue" components probably draws typically 50 mA and maybe up to 100 mA. Adding external loads can increase this - depending entirely on the load.

At say 100 mA average drain you'd get approximately 900/100= 9 hours operation. Running just the processor and on board components / peripherals you'd probabaly get twice times as long. By targeting low current methods (see refs ate end) you could get MUCH longer.
_____________________

Most LiIon batteries are rated to charge at up to the "C" rate - ie 990 mA for a 990 mAh battery and to safely discharge at several times as much. Some manufacturers rate their batteries for lower maximum charge rates and this also can vary with the intended cell application. A "high energy" cell is liable to have lower charge and discharge rates than a "high power" cell. This relates to means of construction and to be safe the manufacturer's data sheet should be consulted.

The battery "capacity" rises somewhat as rates decrease below 'C' and fall significantly for rates above C.

Here is [**an excellent example data sheet for selected Sanyo LiIon cells**](http://www.awilco-multiplex.dk/files/pdf/Batteries Li-Ion/Sanyo_Lithium_Ion_catalogue_10_2007.pdf) . These are only examples but give a reasonable idea of what can be expected from a reasonable quality product.

___________________

[Arduino per pin current limitations](http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations)

Typical current draw](http://gadgetmakersblog.com/arduino-power-consumption/)

Excellent - [Methods of reducing Arduino power consumption](http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/)  & [Related](https://alanbmitchell.wordpress.com/2011/10/02/operate-arduino-for-year-from-batteries/) & [more](https://alanbmitchell.wordpress.com/2011/10/09/design-of-the-extended-battery-life-power-controller-for-the-arduino/)

Stack exchange discussion - [How much current do you require in Arduino and embedded systems projects?](https://electronics.stackexchange.com/q/1707/3288)


body:
    int coilSetOne = 0;
    int coilSetTwo = 1;
    int coilSetThree = 2;
    int coilSetFour = 3;
    int switchInput = 4;

    void setup()
    {
      pinMode(coilSetOne, OUTPUT);
      pinMode(coilSetTwo, OUTPUT);
      pinMode(coilSetThree, OUTPUT);
      pinMode(coilSetFour, OUTPUT);
      pinMode(switchInput, INPUT);
    }

    void loop()
    {
    var switchMode = digitalRead(switchInput)
        if ( switchMode == HIGH ) {
            digitalWrite(coilSetOne, HIGH);
            delay(20);
            digitalWrite(coilSetOne, LOW);
            delay(10);
            digitalWrite(coilSetTwo, HIGH);
            delay(20);
            digitalWrite(coilSetTwo, LOW);
            delay(10);
            digitalWrite(coilSetThree, HIGH);
            delay(20);
            digitalWrite(coilSetThree, LOW);
            delay(10);
            digitalWrite(coilSetFour, HIGH);
            delay(20);
            digitalWrite(coilSetFour, LOW);
    }}

If the arduino detects that the switch is powered, it should power the coils. They  should stay on for 20m and the delay between coils turning on should be 10ms.

title: I need to power some coils sequentially, can someone help me with the code?

Answers: 1

body:
I ran your code, and the problem seems to be the "var" you declare, which is not an Arduino type. Use int instead. Also if you have PINs 0 and 1 as output, Using the Serial might prove difficult.

        int coilSetOne = 0;
        int coilSetTwo = 1;
        int coilSetThree = 2;
        int coilSetFour = 3;
        int switchInput = 4;

        void setup()
        {
         // Serial.begin(9600);
          pinMode(coilSetOne, OUTPUT);
          pinMode(coilSetTwo, OUTPUT);
          pinMode(coilSetThree, OUTPUT);
          pinMode(coilSetFour, OUTPUT);
          pinMode(switchInput, INPUT);
        }

        void loop()
        {
          int switchMode = digitalRead(switchInput); //Use int
         /* Serial.print(digitalRead(switchInput));
          Serial.print(" ");
          Serial.print(digitalRead(switchInput) == HIGH);
          Serial.print(" ");*/

          if ( switchMode == HIGH ) {
            Serial.print("#Triggered");

            digitalWrite(coilSetOne, HIGH);
            delay(20);
            digitalWrite(coilSetOne, LOW);
            delay(10);
            digitalWrite(coilSetTwo, HIGH);
            delay(20);
            digitalWrite(coilSetTwo, LOW);
            delay(10);
            digitalWrite(coilSetThree, HIGH);
            delay(20);
            digitalWrite(coilSetThree, LOW);
            delay(10);
            digitalWrite(coilSetFour, HIGH);
            delay(20);
            digitalWrite(coilSetFour, LOW);
          }
         // Serial.println();
        }

You didn't explain us the problem so I'm sorry if I missed the point.


body:
My question is, can I use a Arduino as a battery charger timer, I have a 3.7 v 1200 mah lithium battery that I have been charging with a 4.2 450 ma charger for quite some time, I normally just use gator clamps to connect the leads to charge it, but today I was charging it and forgot about it and let it over charge. I don't want to ruin the life of the battery or possible have it blow up, so I got the idea of using my Arduino as a timer so it will shut off when it is done (or close to done).  My plan was to connect a transistor to it and have the Arduino running to the base pin to control when it will turn on or off and add a diode for both feedback and voltage droppage. I am aware that I will have to add a resistor/diode, so its not charging at around 6 volts.
But I want to know if I can run a program through my Arduino that will have it charge for say 2 hours?  If anyone knows if the uno is capable of doing this please let me know.
Also will I be able to connect a standard phone charger which I believe is 5 volts 2 amp to power my arduino?
Thank you for ur replies, if there is a program please link it
P.S. If anyone would like to know more information or would like to me fix any information please just comment and I will have it fixed shortly.

title: Using arduino uno as a battery charger timer

Answers: 2

body:
Can you use an Uno to switch something on and off?  Yes.

Should you?  No.

In this case you are talking about controlling something that if it is not controlled could have serious safety implications.  Are you confident enough in you ability to code not to get this wrong?  What if the hardware fails, the Uno freezes?

Yes you could do it, but I think you would be better off buying a tried and tested COTS solution.

body:
As others have already said, you could time the charge, but your idea has some major flaws;
First, since you can more easily read voltages than you can keep track of time, you should stop the charge once a certain voltage is reached, so you could also charge other batteries or half charged ones.

MORE IMPORTANTLY,
Lipos always need fairly complex charging circuits (compared to other rechargeable types). This is an area you should read up on extensively before tinkering, since LoPo's respond explosively to mistakes.

A good starting tutorial;
 http://learn.adafruit.com/li-ion-and-lipoly-batteries/overview

I would suggest using a commercial charger, so that you are sure to be protected from over charge, over voltages, shorts, and fires, and will stop charging when the battery is charged. This one should also have a connector so you can connect it to your phone charger, and costs 0.90$.
http://www.electrodragon.com/product/tp4056-lithium-battery-charging-board-1a/
Please note this is a reference, you should find more economic offerts.


body:
    #include <Wire.h>
    #include "RTClib.h"

    #if defined(ARDUINO_ARCH_SAMD)
    // for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
    #define Serial SerialUSB
    #endif

    RTC_DS1307 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {

    #ifndef ESP8266
    while (!Serial); // for Leonardo/Micro/Zero
    #endif

    Serial.begin(9600);
    if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
    }

    if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
    }
    }

    void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.print(" since midnight 1/1/1970 = ");
    Serial.print(now.unixtime());
    Serial.print("s = ");
    Serial.print(now.unixtime() / 86400L);
    Serial.println("d");

    // calculate a date which is 7 days and 30 seconds into the future
    DateTime future (now + TimeSpan(7,12,30,6));

    Serial.print(" now + 7d + 30s: ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();

    Serial.println();
    delay(3000);
    }

[![enter image description here][2]][2]

If i use 57600 i'll get random symbols in one line 1 line.
I have connected PIN5 IN1307N to A4, PIN4 IN1307N to A5

  [1]: https://i.stack.imgur.com/JfhUP.jpg
  [2]: https://i.stack.imgur.com/fCeRB.png
[![enter image description here][1]][1]

title: Difference between DS1307 and IN1307N, I am using RTClib for making rtc module using IN1307N getting RTC is not running

Answers: 1

body:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/Bp4lc.jpg

Following this circuitry solved my issue but still i've not understand the difference between DS1307 and IN1307N.


body:
I want to send some test codes to a MIDI synthesizer, so I wrote a program that lets me just type in hex codes on the serial monitor and send it over serial as the byte value. For example typing "90 45 63" should turn on note 0x45 with a velocity of 0x63.  This part works ok and I have the arduino hooked up to a midi connector and from there to a midi synth. I've verified that this works ok with some test code.

Where I'm having trouble is that MIDI requires a rather unorthodox baud rate of 31250.  The problem is then that on an Arduino Uno, I don't see how I can enter serial data when the Arduino's serial monitor doesn't allow that baud rate. Also trying to set that baud rate under Linux using stty generates an "stty: invalid argument ‘31250’" error.  So is there a way to use a different baud rate for input than for output or some other solution here?  I do have a Teensy 3.1 with multiple Serial ports, but its kinda tied up at the moment and I just thought I could use an Uno for this.

UPDATE: It works now. Something to keep in mind when working with complex external components like a professional synthesizer. The Roland JV-880 that I'm interfacing with wasn't receiving program changes even though I was sending the 0xC0 0x03 codes or whatever. This is why I made this debugging program to begin with. After searching around and being stumped, I looked around the system settings on the synthesizer and discovered a setting called "System MIDI Rx switch Program change=OFF". After I changed that to ON the program change codes worked. Sometimes the problem is nothing in your code or circuit.

title: Way to use other baud rates in console or different input/output rates

Answers: 1

body:
The Arduino Uno is powered by an ATmega328P microcontroller. This
microcontroller has only one UART which is _not_ capable of using
different baud rates for sending and receiving.

You could look into the different software serial port implementations
for the sending side. Another solution would be to continually change
the baud rate: each time you get a complete message from the serial
monitor,

* you switch the baud rate to 31250 bps
* you send the packet to the midi synth
* you `Serial.flush()` to make sure the bytes have actually been sent
* you switch back the baud rate to whatever you used in the serial
  monitor

You will probably see some garbage on serial monitor as it receives the
bytes at the wrong rate, but that should not be an issue.


body:
I noticed something when I was trying something with leds;

      pinMode(13,HIGH); // giving +5V to pin 13.
      delay(1000);      // waiting for 1 sec.
      pinMode(13,HIGH); // giving +5V to pin 13 again.
      delay(1000);      // waiting for 1 sec again.

      //loops forever.
But I couldn't light the led. What is the reason behind this? Shouldn't it be lit forever?

title: Weird Arduino LED behaviour

Answers: 1

body:
As already in the comments, you are using `pinMode(...)` where you should be using `digitalWrite(...)`

The code should look like

    void setup() {
      pinMode(13, OUTPUT); // sets the pin to an OUTPUT, it can now source or sink current
    }

    void loop() {
      digitalWrite(13, HIGH); // sets the pin to +5V
      delay(1000); // waits 1 sec
      digitalWrite(13, HIGH);
      delay(1000);
    }

When you use `pinMode(13, LOW)` you are actually writing `pinMode(13, INPUT)` as `LOW` and `INPUT` are two aliases for the same value (0, by the way).
When in `INPUT` mode the PIN doesn't source or sink any considerable current, so I can't say much more about why the LED is turning on unless you provide a schematics of your circuit (but I have idea you are doing something really wrong).

It might be useful to have a look at [this simulation][1]:

 - on the left the LED is connected directly to voltage source without control from Arduino
 - in the middle, the LED is controlled by Arduino on the high side: click on the letter to toggle the pin state
 - on the right the LED is controlled on the low side

  [1]: http://www.falstad.com/circuit/circuitjs.html?cct=$ 1 0.000005 10.200277308269968 50 5 50
R 224 112 176 112 0 0 40 5 0 0 0.5
g 224 240 224 304 0
162 224 112 224 176 1 2.1024259 1 0 0
r 224 176 224 240 0 220
r 368 176 368 240 0 220
162 368 112 368 176 1 2.1024259 1 0 0
g 368 240 368 304 0
L 368 112 320 112 0 0 false 5 0
L 512 240 464 240 0 1 false 5 0
162 512 112 512 176 1 2.1024259 1 0 0
r 512 176 512 240 0 220
R 512 112 464 112 0 0 40 5 0 0 0.5


body:
For a school assignment I need to make a LED blink on/of 3 times then stop.
Now I have come up with the following code:

[![Repeat!][1]][1]

  [1]: https://i.stack.imgur.com/CVi5O.png

I think it's ''clean'' enough for what it has to do, but I have a feeling that here must be a easier way to make the LED blink 3 times.

**Question is: Is there a way to reapeat the part of code 3 times without copy&pasting it?**

title: How do I repeat a piece of code

Answers: 3

body:
Here you can use a loop. a classic for loop in C++ looks like this

    for (int i = 0; i < n; i++)
    {
        // content in between these brackets
    }
where n is the amount of times you want to loop

you can also instantiate the `i` before the loop.

    int i;
    for (i = 0; i < n; i++)
    {
        //content here
    }

The code below should work. Toy around with it and see what you get.

    int ledPin = 13;
    int delayPeriod = 500;

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

        for (int i = 0; i < 3; i++){
            digitalWrite(ledPin, HIGH);
            delay(delayPeriod);
            digitalWrite(ledPin, LOW);
            delay(delayPeriod);
        }
another approach you can do is using a while loop. These kinds of loops will loop until a given parameter has been met. In your case you want an LED to stop blinking after 3 times.

    int start = 0;
    int stop = 3;

    while (start <= stop){
        //content here
    }

While loops will continue to go as long as the parameter is true. This means something like `while(1)` will continue to run forever.

body:
Another way is to declare a function. This method will give you more chance of using it in various ways.

        int LED_PIN = 13;

        void flashing(size_t times=1) { // By default it will flash once, you can chance this into your desire
            int delayPeriod = 500;
            for (size_t loop = 0; loop < (times*2); ++loop) {
              digitalWrite(LED_PIN, (loop % 2)?HIGH:LOW);// Use Modulus
              delay(delayPeriod);
            } // Thanks to [Matt][1] and [Edgar Bonet][2] for their comments
        }

        void setup() {
            pinMode(ledPin, OUTPUT);
            flashing(3);
        }

        void loop() {
            // Do something here
        }

  [1]: http://arduino.stackexchange.com/users/10394/matt
  [2]: http://arduino.stackexchange.com/users/7508/edgar-bonet

body:
You could also look at optimising the 4 lines of code inside you loop:

    const int ledPin = 13;
    const int delayPeriod = 500;
    const size_t count = 3;

    void setup()
    {
        pinMode(ledPin, OUTPUT);
        for (size_t loop = 0; loop < (count*2); ++loop) // size_t because variable is never negative.
        {  // Two time count, because you only have half the code
            digitalWrite(ledPin, (loop % 2)?HIGH:LOW);// Use Modulus
            delay(delayPeriod);
        }
    }


body:
I'm having trouble getting information off the accelerometer I'm trying to use. What code should I use to read the X,Y, and Z axis?  I've read the data sheet but I don't have any experience with SPI communication.

[Spec sheet](http://www.st.com/content/ccc/resource/technical/document/datasheet/6e/c2/95/d9/3a/3f/4f/cb/DM00162193.pdf/files/DM00162193.pdf/jcr:content/translations/en.DM00162193.pdf)

title: Arduino SPI Communication with H3LIS100DL accelerometer

Answers: 1

body:
The basic [SPI][1] operations looks like this. First read single register:

    uint8_t readRegister(int index)
    {
      digitalWrite(CS, LOW);
      SPI.beginTransaction(SPI_SETTING);
      SPI.transfer(READ | index);
      uint8_t res = SPI.transfer(0);
      SPI.endTransaction();
      digitalWrite(CS, HIGH);
      return (res);
    }

And second write single register:

    void writeRegister(int index, uint8_t data)
    {
      digitalWrite(CS, LOW);
      SPI.beginTransaction(SPI_SETTING);
      SPI.transfer(WRITE | index);
      SPI.transfer(data);
      SPI.endTransaction();
      digitalWrite(CS, HIGH);
    }

Some more details:

    const uint8_t WRITE = 0x00;
    const uint8_t READ = 0x80;

It is also possible to read/write a sequence of registers by providing the register index with the MS set. This will auto-increment the register index.

SPI_SETTING is left as an exercise (to be updated).

Cheers!

  [1]: https://www.arduino.cc/en/Reference/SPI


body:
   My goal is not upload sketch to Arduino Pro mini through bluetooth module HC06. I have made a breadboard version of DTR signal simulator which takes LED status pin as a source. The output from the detector goes to RST pin of Arduino. When connection is initiated the status LED stops blinking and output pin goes low and than high which leads to Arduino rebooting. This part works fine. Unfortunately avrdude from Arduino IDE does not see the bootloader and shows the following error in the console:

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

  I have noticed that HC06 stops blinking with some delay after a connection is initiated. I suspect that this might be a problem. To overcome this issue the boot loader should probably be changed. Unfortunately I am not familiar with the embedded C programming, thus if someone has experience in changing the bootloadder, please help me to solve this puzzle.

The following is a scheme of detector:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/qkIUZ.png

title: Arduino programming through HC06

Answers: 1

body: Setting serial speed on your computer side doesn't change speed on the HC-06 side. So you have to set the same speed for HC-06 interface (and in your sketches) as a bootloader is using.


body:
I just started working with arduinos recently. I'm really interested in working with relays. I would like to turn a desk lamp on and off using an ios app or a web browser button. I have no experience working with relays but I would love to experiment with relays in order to turn a desk lamp on or off based on an external switch in like an IOS app or a browser.

 I am wondering what are the risks in relays with arduino ? I would like to switch a desk lamp on or off using a relay but I don't really understand the risks with creating a desk lamp powered using a wall socket and turned on or off using a arduino relay module . What is the worst case scenario if I screw up ? What are the risks and precautions I should take while working with relays and trying to build a relay controlled desk lamp?

I live in an apartment and I am trying to make sure that my entire building does not lose electricity or I don't screw up the electricity in my unit. What are protective measures that I can take to minimize damages while working on this project?

title: Arduino relay. risks?

Answers: 3

body:
Basic safety precautions:

1. Always fully unplug the lamp before working on any wiring, even when working with the low-voltage side of things.
2. Invest in a proper enclosure and follow the rules of insulation and earthing: if the enclosure is metal or has exposed metal they have to be earthed. If it is plastic it is insulated and there is nothing to earth (plastic is best).
3. Use nylon bolts etc when situated near mains voltages.
4. A proper relay module with good screw terminals is recommended.
5. **Do not** tin your mains wires when screwing them into a terminal block
6. Do your mains wiring with your left hand in your pocket (an old electrician's trick: if you should get a shock the path to earth is down the side of your body and through your foot. If you have your left hand touching something the path to earth could well be straight across your chest, through your heart, and down your other arm, killing you. It has saved my life a few times...)
7. Keep mains voltages and low-voltage areas separate. Cable ties and self-adhesive nylon cable tie pads are great for keeping cables where they should be.
8. Shield any exposed mains connections from touch. Things like the underside of the relay module where the terminal blocks are soldered, that sort of thing.
9. Don't let the relay module wave around loosely. Keep it well secured in the enclosure.

I'm sure I could find more tips if I tried :)

The main thing to remember is that mains electricity is deadly and should be treated with the utmost respect.

For the ultimate in safety though you could get an *isolating transformer*. This separates your work from the main supply and means that the only way of getting a shock is by actively touching *both* outputs of the transformer at once - something you're not really likely to do - and even then it's usually a very localised path for the electricity (through a finger or two).

Adding an ELCB to the lamp's plug (if it is earthed) can be a good precaution while you are working too - and making sure the socket is connected to a ring main that is protected by an RCD is pretty much essential (in the UK it is the law that all ring mains are protected by an RCD - I would hope the same is the case where you live).

body:
Read through the [Sparkfun Beefcake Relay Hookup Guide](https://learn.sparkfun.com/tutorials/beefcake-relay-control-hookup-guide).  It points out many things to keep in mind.

The kit is quite good, I just finished putting one together to control a humidifier off an Arduino with a DHT-11 to keep ambient humidity within a range.

**As people have posted, don't ever do any work while the mains are plugged in!**

In your project, you'll be able to test the relay without the mains being plugged in, the relay will make a nice "clicking" sound and if you use the "Beefcake" kit, an LED will light up when the relay is "on".

Be sure to have everything in a "housing" and not flopping around. They sell blue plastic junction boxes for about $1 which is what I used.  A GFI or GFCI socket is safer to use, though more expensive.

Good luck!

body:
this is andrew.
I saw your Question.
Relay's are not even risky Electronic device , it can be controlled by 5v or 12 v.

On behalf, you can just run your simple led blink program to Start up your relay.
Just use the Default (13th) pin for relay input. Run your Code. If your code runs successfully, the relay activates, led in the relay will light up and as well as Your default Led also light up in your arduino Board. After that you can give the output 220v power to control electronic Devices.
if any doubt just ping me.


body: I'm making a project and I neee to use 2 different references on the same ADMUX. One reference is 0-5V and the other is 0-2.5V. I'm aware that I can use the reference of the Arduino to the 5V sensor. But how I put a 2.5V reference while using the 5V at the same time?

title: Using two references in the same ADMUX

Answers: 1

body:
First of all a reference is just a voltage, not a range.

If you use a reference of say 5V than your `analogRead(...)` calls will return a 10 bit number where 0 stands for 0V and 1023 stands for 5V.

Second, the `AREF` pin is there for that purpose: feed your 2.5V reference to that pin and use:

    analogReference(EXTERNAL);
    analogRead(...);

when you want to read using the 2.5V reference (0 stands for 0V and 1023 stands for 2.5V in this case), or

    analogReference(DEFAULT);
    analogRead(...);

when you want to read using the 5V reference (supposing your Arduino is powered by 5V).

**UPDATE**

Nothing can be done **at the exact same time** on an Arduino/ATmega328 because it has one single processing unit. In case of analog to digital conversion you can not even perform two conversions on two pins too fast because you have only one ADC which is multiplexed (shared) among all the analog pins.

You have no choice to perform one reading, wait, then perform the other reading. You can change the voltage reference between the two conversions though, but you need to ensure the internal ADC capacitor is properly discharged: if you read a 5V line and then read a 2.5V line without discharging the internal ADC you are more than probably going to always read the maximum value.

How long you will have to wait depends on the impedance of the line you are sampling: higher the impedance, longer the time you have to wait for the ADMUX capacitor to discharge/charge up (Arduino/ATmega328 ADC is a _store and sample_ comparator).


body:
I've designed a custom board meant for high-powered model rocket telemetry & duel-deployment.  (More info upon request)

To do this, I've soldered a ATMEGA2560 (yes, overkill, but I needed multiple hardware serials), with the plan on using the ICSP programming header I designed on the board to burn the Arduino bootloader, and then use the super-easy ftdi-compatible serial connector to program the board....

Problem is, I have thus far been completely unable to burn the bootloader.  I've double-checked the wiring ten times, checked the labeling on my board, checked my board's schematic twice, and re-checked the chip's datasheet to make sure I didn't screw up the pinout, even held a jumper past my fancy reset circuitry that I largely copied from the official Uno schematic.

I've largely been using Nick Gammon's excellent "bootloader programmer" sketch [Link](http://www.gammon.com.au/forum/?id=11635) on a Clone Arduino Mega.  But I've tested the connections and sketch by using it to program the bootloader on a Arduino Pro Mini successfully with no hitch at all.  :(

`Attempting to enter ICSP programming mode..........................................
Failed to enter programming mode. Double-check wiring!`

Here's a [Board](http://hydra.13-thirtyseven.com/Misc/board.png) and (Schematic I can't post because I'[m new to the Arduino side of stack overflow...  so replace the URL with schematic.png) of my board, and I'll upload a picture of my soldered board soon, but I'm actually quite confident of my soldering job...

Really just completely out of ideas, and very demoralized because the project I've been working on for months isn't working, and I have nothing specific to even point at...

title: Problems burning bootloader on custom ATMEGA2560 board for High-powered model rocketry

Answers: 1

body:
> I have thus far been completely unable to burn the bootloader.

In what sense? What (error) messages did you get?

In your shoes I would be seeing if I can "talk" to the chip. My [chip detector sketch](http://www.gammon.com.au/forum/?id=11633) will help you to see if the chip is "alive" or not. See my post about https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board

You may possibly have inappropriate fuse settings for your clock source. If you get some sort of response from the chip using the chip detector sketch please post what it is.

---

> Also to note is that this is a completely virgin chip from the manufacturer, so I'm not sure what the clock settings come as in that case

According to the datasheet, 8 MHz internal oscillator with CKDIV8 fuse set. That *should* work.

However you need to resolve that before going any further. I would be taking voltage readings at various points.

* Make sure you have Vcc at all the appropriate places, and Gnd.
* Note that there are multiple Gnd and Vcc pins. You should also have 5V at AVcc.
* Check that /RESET is normally high (5V) and check that it drops to 0V during the programming attempt (and stays there).
* Check you have decoupling capacitors between Vcc and Gnd where necessary.
* Assuming you have the TQFP-pinout chip, make sure that you have your SPI connections at pins 19, 20, 21 and 22.
* If you have a scope or logic analyser make sure that there is some "action" on SCK, MOSI pins during attempts to program it. There should also be a response on MISO.
* There should not be a capacitor in *series* with /RESET as I have occasionally seen people do. The programmer has to hold /RESET low during the entire programming sequence.


body:
I am using the following code to create a snake-like affect (3 LED's wide) moving through 24 LED's using 3 shift registers:

     for(int i = 0; i < 27; i++){
        setRegisterPin(i, HIGH);
        writeRegisters();
        if(i >= 3){
         setRegisterPin(i-LEDLength, LOW);
         writeRegisters();
        }
        delay(100);
      }//end for

The problem with this is that the snake has to completely end before it starts again, instead of looking like one continuous snake going in circles.

So when the three LED's get to the end I want it to immediately begin to light the beginning again. If 2 are lit at the end then 1 should be lit at the start, etc. Like this pattern:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/sk63d.png

title: Seamlessly loop through LED's - Shift Register

Answers: 1

body:
You mean something like this? (untested):

    void loop() {
      // use static or global variables to remember positions (these are initialized only once):
      static uint8_t hi_pos = 0;  // where HIGH should be set
      static uint8_t lo_pos = 21; // where LOW should be set

      setRegisterPin(hi_pos, HIGH); // turn on led in head
      setRegisterPin(lo_pos, LOW);  // turn off led in tail
      writeRegisters();             // update registers

      // ensure it won't overflow:
      if (++hi_pos == 24) hi_pos = 0;
      if (++lo_pos == 24) lo_pos = 0;

      // or:  hi_pos = (hi_pos+1) % 24;  // but divisions are slower on AVR

      delay(100);
    }

It will go in sequence:

    ON  OFF
     0   21
     1   22
     2   23
     3    0
     4    1
    ...
    22   19
    23   20
    0    21
    ...
forever


body:
I am trying to manipulate a project and the simplest way to do what I am trying to do would be to use the existing code.  This code is designed to take an input from the serial monitor using serial.read() and manipulate it.  For example if I type *hello* into the serial monitor's command bar, the code would read it and manipulate it.  I was wondering if there is any way to create a serial command to run in the code which would act in a way as to bypass the serial monitor since this project is not going to be connected to a computer when it is in use.  The command will be the same every time and will be in response to a single switch input.

    #include <avr/pgmspace.h>
    #include <MorseEnDecoder.h>
    #include <stdio.h>

    // Pin mapping
    const byte morseInPin = 7;
    const byte morseOutPin = 13;
    String check = "";
    String origin = "S";
    const int maxItems = 3;
    char myStr[] = "Help is Coming";
    int x;
    char myArray[maxItems], curChar;
    char nextChar;
    int i;
    int y;

    // Instantiate Morse objects
    morseDecoder morseInput(morseInPin, MORSE_KEYER, MORSE_ACTIVE_LOW);
    morseEncoder morseOutput(morseOutPin);

    // Variables dealing with formatting the output somewhat
    // by inserting CR's (carriage returns)
    long lastTransmissionTime;
    long currentTime;
    boolean transmissionEnded = true; // Flag to mark old trans finished

    // Minimum transmission pause time to insert carriage returns (CR)
    // Adjust depending on Morse spd. IE 13 wpm = 646 ms btw words (no CR).
    const long transmissionPaused   = 1000; // Suitable for 13 wpm?

    void setup()
    {
    Serial.begin(9600);
    Serial.println("Morse EnDecoder Geocache");

    // Setting Morse speed in wpm - words per minute
    // If not set, 13 wpm is default anyway
    morseInput.setspeed(5);
    morseOutput.setspeed(5);

    lastTransmissionTime = (long)millis();

    }

    void loop()
    {
    currentTime = (long)millis();

    // Need to call these once per loop
    morseInput.decode();
    morseOutput.encode();

    // SEND MORSE (OUTPUT)
    // Encode and send text received from the serial port (serial monitor)
    if (Serial.available() && morseOutput.available())
    {
    // Get character from serial and send as Morse code
    char sendMorse = Serial.read();
    morseOutput.write(sendMorse);

    // Not strictly needed, but used to get morseSignalString before it is      destroyed
    // (E.g. for morse training purposes)
    morseOutput.encode();

    // Also write sent character + Morse code to serial port/monitor
    Serial.write(' ');
    Serial.write(sendMorse);
    // Morse code in morseSignalString is now backwards
    for (int y=morseOutput.morseSignals; y>0; y--)
    {
      Serial.write(morseOutput.morseSignalString[y-1]);
    }
    }

    // RECEIVE MORSE (INPUT)
    // If a character is decoded from the input, write it to serial port
    if (morseInput.available())
    {

    char receivedMorse = morseInput.read();
    //Serial.print(receivedMorse);
    // A little error checking
    if (receivedMorse == '#') Serial.println("< ERROR:too many morse   signals! >");
    morseOutput.write('#');
    morseOutput.encode();

    //Create Array out of receivedMorse Chars

        curChar = 0;
        nextChar = receivedMorse;
        curChar +=nextChar;
        myArray[i] = curChar;
        check.concat(myArray[i]);
        Serial.println(check);

      //Check input and respond
      if (check == origin)
      {
    Serial.println("check = origin");

    // Encode and send text set in myStr[x]

    for (x = 0; x < sizeof(myStr) - 1; x++)
    {
    char sendMorse = myStr[x];
    morseOutput.write(sendMorse);

    // Not strictly needed, but used to get morseSignalString before it is destroyed
    // (E.g. for morse training purposes)
    morseOutput.encode();

    // Also write sent character + Morse code to serial port/monitor
    Serial.write(' ');
    Serial.write(sendMorse);
    // Morse code in morseSignalString is now backwards
    for (int y=morseOutput.morseSignals; y>0; y--)
    {
    Serial.write(morseOutput.morseSignalString[y-1]);
    }
    }

      }

     if (receivedMorse == '#') Serial.println("< ERROR:too many morse signals! >");
     }
     // two strings not equal:
     if (check != origin) {

     }
     }

This is a morse code encoder and decoder.  I have adapted it to do a certain thing when a certain string of morse code is entered.  I am trying to get it to then encode and respond with a morse string, but the only way it is programmed to do such a thing is through the `serial.read()` command  There is a library that I am not sure how to attach, it can be found here
<https://www.dropbox.com/s/eg21qmg0151gxz6/Morse_EnDecoder_2012.11.25.tar-2.gz?dl=0> this also includes all of the original codes.  My additions can be found directly under the comment `//Create Array out of receivedMorse Chars` and continuing to the bottom (The last 45 lines or so not including char, string, and int declarations).  I apologize if some of the edits I have made are hideous or "not in the spirit of the language".  I am a novice and a hobbyist.

The Code I have adapted will print my string exactly as it appears (`myStr[]`), however it will not encode it to Morse nor will it output it through the LED or the buzzer.  The 'serial.read()' command appears to work outside of my if statement, but really I have no idea how I would fix this.

title: Can I create a serial.read command with the arduino code alone?

Answers: 1

body:
The serial input is read into a variable.

You could comment out the serial read and assign *whatever* value you need directly to the variable.  By commenting out the serial read, you will have a marker of where you made the changes.

This should work since you are saying the inputs are known and do not change.


body: I am running a linux distro on my pc(Ubuntu 16.04). I have installed Arduino IDE(version 1.0.5 since it's the only one available on the store) from the Ubuntu Software Center and also using the .ZIP file from the official Arduino website(version 1.6.11). When I ran IDE(1.0.5) the "Serial Port" drop-down was greyed out. Next ran the IDE(1.6.11) and again the "Port" drop-down under Tools was greyed out. I have spent hours looking online for a solution but all in vain. A tried and tested working solution will be highly appreciated.

title: Serial ports(in 1.0.5 & Port in 1.6.11) is greyed out under tools

Answers: 1

body:
Information on a “[Serial Port Setup](https://fedorahosted.org/fldigi/wiki/Documentation/HOWTO/Serial_Port_Setup)” page at fedorahosted.org should be adequate to sort the problem manually.  Here are a few snippets from that page, along with notes about application to the current problem.

• Use command `ls -l /dev/ttyUSB*` to find out the serial port's group.  For example, on my Ubuntu system that shows

    crw-rw---- 1 root dialout 188, 0 Aug 20 11:13 /dev/ttyUSB0

Note, substitute for ttyUSB if the port you're concerned about doesn't start with that.

• Use command `groups` to find out which groups you belong to.

• The fedorahosted page says to use command `sudo adduser (username) dialout` to add dialout to your groups list.  I haven't tried that approach, and would be more inclined to instead try `sudo usermod -a -G dialout (username)` [where  “`(username)`” represents your username].


body:
The sketch example from page ["Wifi.beginAP()"][1] causes compiler error because the return values are not defined for -WL_AP_LISTENING or -WL_CONNECT_FAILED.

Board: Arduino MKR1000 WiFi

Compiler:  Arduino IDE

Library: Github WiFi101 v0.9.1

Missing:  definition of "WL_AP_LISTENING" and "WL_CONNECT_FAILED"

ERROR....
beginAP.ino: In function 'void setup()':

beginAP:55: error: 'WL_AP_LISTENING' was not declared in this scope

    if (status != WL_AP_LISTENING) {

                  ^

Arduino WiFi101-MKS1000 examples\beginAP\beginAP.ino: In function 'void loop()':

beginAP:78: error: 'WL_AP_CONNECTED' was not declared in this scope

      if (status == WL_AP_CONNECTED) {

                    ^

exit status 1
'WL_AP_LISTENING' was not declared in this scope

  [1]: https://www.arduino.cc/en/Reference/WiFi101BeginAP

title: where to get Arduino WIFO101 library that supports WiFi.beginAP() on board MKR1000

Answers: 1

body:
It is AP_SimpleWebServer.ino at Github Wifi101 release 0.9.1 examples.
It builds ok by using the old definitions for .beginAP return values.
Problem is Arduino .beginAP page has example that relies on the LATEST Github WiFi101 ("0.9.1++" not released yet).
Also example AP_SimpleWebServer is missing from Arduino Wifi101 page.


body:
I've been playing with my [Arduino Boards][1] for a while. I have an [Arduino Nano][2] and a Duemilanove 328.

I've been able to program both of them without problems for weeks. Any example project I try will compile and upload with no issue.

I recently got an Ethernet shield... I'm trying some test sketches and no matter which board I try, with the shield attached I get:

    avrdude: stk500_getsync(): not in sync: resp=0x00

As I said, without the Ethernet shield attached all is bliss....

Do I have a bad shield or am I just doing something stupid?

  [1]: https://www.sabdel.com/shop/electronics/5v-4-channel-relay-shield-expansion-board-for-arduino/
  [2]: https://www.sabdel.com/shop/electronics/328p-multifunction-expansion-board-v3-0-for-arduino-nano-uno/

title: Arduino code won't upload with Ethernet Shield attached

Answers: 1

body:
The Ethernet Shield uses the pins  D10, D11, D12 and D13 on the Arduino UNO. I presume there is a conflict and you use one or more of these digital pins in your setup already.

A nice overview of possible conflicts between shields and arduino boards can be found at:
[http://playground.arduino.cc/Main/ShieldPinUsage][1]

  [1]: http://playground.arduino.cc/Main/ShieldPinUsage


body:
I don't understand where the access point's IP comes from.
Sketch uses `WiFi.beginAP( ssid )`   ..to start the AP.
Then, `printWifiStatus()` gets the access point's IP with:

    IPAddress ip = WiFi.localIP();

How does `.beginAP()` create the IP?  What does it use for a mask?

I'm creating network service on a MKR1000, and want to use `.beginAP()` to make it an access point, so I don't need a "middle man" (router).  Going to have mobile device (iPhone) connect directly to Arduino MKR1000.

title: where does access point's IP address come from for sketch AP_SimpleWebServer.ino in Github WiFi101 examples

Answers: 1

body:
If you look into that github source code, you can see `startAP` function and mainly rows with `strM2MAPConfig.au8DHCPServerIP`:

    uint8_t WiFiClass::startAP(const char *ssid, uint8_t u8SecType, const void *pvAuthInfo, uint8_t channel)
    {
     tstrM2MAPConfig strM2MAPConfig;

     if (!_init) {
      init();
     }

     if (channel == 0) {
      channel = 1; // channel 1 is the minium channel
     }

     // Enter Access Point mode:
     memset(&strM2MAPConfig, 0x00, sizeof(tstrM2MAPConfig));
     strcpy((char *)&strM2MAPConfig.au8SSID, ssid);
     strM2MAPConfig.u8ListenChannel = channel - 1;
     strM2MAPConfig.u8SecType = u8SecType;
     strM2MAPConfig.au8DHCPServerIP[0] = 0xC0; /* 192 */
     strM2MAPConfig.au8DHCPServerIP[1] = 0xA8; /* 168 */
     strM2MAPConfig.au8DHCPServerIP[2] = 0x01; /* 1 */
     strM2MAPConfig.au8DHCPServerIP[3] = 0x01; /* 1 */

     if (u8SecType == M2M_WIFI_SEC_WEP) {
      tstrM2mWifiWepParams* wep_params = (tstrM2mWifiWepParams*)pvAuthInfo;

      strM2MAPConfig.u8KeyIndx = wep_params->u8KeyIndx;
      strM2MAPConfig.u8KeySz = wep_params->u8KeySz;
      strcpy((char*)strM2MAPConfig.au8WepKey, (char *)wep_params->au8WepKey);
     }

     if (m2m_wifi_enable_ap(&strM2MAPConfig) < 0) {
      _status = WL_CONNECT_FAILED;
      return _status;
     }
     _status = WL_AP_LISTENING;
     _mode = WL_AP_MODE;

     memset(_ssid, 0, M2M_MAX_SSID_LEN);
     memcpy(_ssid, ssid, strlen(ssid));
     m2m_memcpy((uint8 *)&_localip, (uint8 *)&strM2MAPConfig.au8DHCPServerIP[0], 4);
     _submask = 0x00FFFFFF;
     _gateway = _localip;

     // WiFi led ON (rev A then rev B).
     m2m_periph_gpio_set_val(M2M_PERIPH_GPIO15, 0);
     m2m_periph_gpio_set_val(M2M_PERIPH_GPIO4, 0);

     return _status;
    }


body:
I want to **turn on and off** I2C Sensors with the Arduino Mega 2560.

----------

I use one max. 0.4A NPN Transistor, which controls the Vcc line to the sensor.

When I plug my Arduino into my laptop and the sketch begins working everything is fine. The sensor is turned on and is working.

**But when I set the Transistor Base to Low and cut the Vcc the sensor acts weird.
The LED on the sensor breakout board shines very weak. So the sensor/breakout board is getting electricity from somewhere else; probably from the I2C connections.**

[![Arduino Sensor Power Control Circuit][1]][1]

----------

Same results with this small experiment:

 1. Breakout board directly connected to the Arduino (without Transistor)
 2. Vcc-3.3V pin wire disconnected from the Arduino female pin

----------

How can i properly turn on and off an I2C sensor with an Arduino?

Do I have to use additional transistors for every I2C line? Are better circuit solutions available or maybe a software solution?

How should I design my circuit and my software if I have multiple I2C sensors connected to my Arduino and I want to use them independently from each other?

----------

Used hardware: Arduino Mega, Sensor Breakout Board

----------

Software excerpt for power control:

    void setup() {

        pinMode(7, OUTPUT);
        digitalWrite(7, HIGH);

        ...

        delay(10000);
        digitalWrite(7, LOW);

        ...
    }

  [1]: https://i.stack.imgur.com/3J9Vw.png

title: How to turn I2C Sensors on and off with an Arduino Mega 2560?

Answers: 2

body:
The SDA and SCL pins have pull up resistors on them. So their voltage is 5V. By disconnecting Vcc on the sensor you are running the sensor out of spec. since the voltage on the SDA and SCL pins exceed Vcc.

Most chips have clamping diodes. So the chip is clamping the 5V on the I2C pins to Vcc. So you are powering the chip through the pull-up resistors on the I2C pins.

This would explain why the power led is lit, but not as bright.

body: if your sensor does not consume more that 20ma, you can power it's GROUND pin with an arduino pin by using pinMode(sensor, OUTPUT), analogWrite(sensor, 255) : at that stage no power flows to the sensor since all its pins are high. When you want to power back the sensor, you need to lower the value of "255" to 0 , if your sensor uses 5v or to around 40 , if your sensor uses 3.3v. I have been using this system for a while without any problem.    You might need a small delay(50), to give time for the sensor to power up.


body:
I need to use multiple photocells as input, but its more than the amount of analog pins that my arduino has.

I'm wondering if theres any way to use a photocell as a digital input, with the photocell triggering at a specific set threshold of light.

It doesn't seem quite possible but I thought I'd ask.

title: Use photocell as digital input

Answers: 3

body:
**Yes**, you can use LDRs(photocells) as an indirect digital input.

You can design a **voltage divider circuit**, which incorporates your LDR and gives LOW or HIGH digital readings based on your **pre-calibrated threshold light values**.

Your voltage divider circuit must reach a specific voltage for your wanted light threshold to give you a HIGH reading.

----------

The following are the voltage thresholds guaranteed to be read as HIGH.

> When a pin is configured as an INPUT with pinMode(), and read with
> digitalRead(), the Arduino (Atmega) will report HIGH if:
>
>     a voltage greater than 3 volts is present at the pin (5V boards);
>     a voltage greater than 2 volts is present at the pin (3.3V boards);

[Source of Quote][1]

  [1]: https://www.arduino.cc/en/Reference/Constants

body:
I see two possible options for achieving what you want:

## Voltage divider

This is the solution proposed by William Roy: you make a voltage divider
circuit and check whether it gives a voltage above the threshold of the
digital input. For example:

    +5V ---+
           |
           R
           |
           +--- digital input
           |
          LDR
           |
    GND ---+

There are a couple of issues with this approach though:

1. Every digital input is fitted with a [Schmitt trigger][] which makes
   it hysteretic, meaning the voltage threshold for switching from `LOW`
   to `HIGH` is higher than the threshold for switching from `HIGH` to
   `LOW`. If the pin voltage is between the two thresholds, it will read
   either `HIGH` or `LOW`, as determined by the history of that voltage.
   Depending on your application, this may not be a problem, and may
   even be desirable. But if you want, as you wrote in your question, “a
   specific set threshold of light”, it sure will be problematic.

2. You do not know what those threshold voltages are. The [datasheet of
   the ATmega328P][datasheet] (the main chip of the Uno) states that
   they should “typically” be around 2.1 and 2.6 V, but it only
   guarantees that the low threshold should be no less than 1.5 V
   and the high threshold no more than 3 V. For any input voltage
   between 1.5 and 3 V (which is a very significant range), the
   chip manufacturer doesn't guarantee what the pin will read.

The first issue can be solved by using a write-before-read protocol:
first you set the pin to OUTPUT LOW, which will force the input Schmitt
trigger to the LOW state. Then you set it to INPUT and take a reading.
This way you will read HIGH if _and only if_ the pin voltage is above
the high threshold. The low threshold becomes irrelevant. Example code:

<!-- language: lang-c++ -->

    /*
     * Read the given pin avoiding the input hysteresis.
     *
     * Returns HIGH if the pin voltage is above the upper (LOW to HIGH)
     * threshold, LOW otherwise.
     *
     * WARNING: The pin is set to OUTPUT LOW for a very short time.
     */
    int anhystereticRead(uint8_t pin) {
        pinMode(pin, OUTPUT);
        digitalWrite(pin, LOW);
        pinMode(pin, INPUT);
        return digitalRead(pin);
    }

The second point can be solved by calibrating your input using a trimpot
instead of a resistor. You would adjust the pot until the threshold is
exactly what you want. Using fixed resistors instead of a pot will make
it very difficult to achieve your “specific set threshold of light”,
unless you can live with a very rough precision.

## Capacitive measurement

The second option is use the LDR as the resistor in an RC circuit, and
measure the charging time of the circuit, like this:

    digital output --- LDR ---+--- digital input
                              |
                          capacitor
                              |
                             GND

Starting with a discharged capacitor, you set the output to `HIGH` and
measure how long it takes for the input to read `HIGH`. This time is
typically something like 0.73 _R_ _C_, where _R_ is the
resistance of the LDR and _C_ the capacitance of the capacitor. The
exact numerical factor is not know, as it depends on the high threshold
voltage of the digital pin.

For details and example code, you could check the [Capacitance Meter and
RC Time Constants][capmeter] Arduino tutorial, or search the Web for
“Arduino capacitance meter”. You will find material about how to measure
an unknown capacitance using a know resistance, but you can use the same
technique to measure an unknown resistance using a known capacitance.
And you should replace the waiting loop:

    while (analogRead(input) < THRESHOLD) {}  // wait

by a similar loop using the digital input threshold:

    while (digitalRead(input) == LOW) {}  // wait

The interesting thing about this technique is that you do not need a
trimpot to set the illuminance threshold: you will _measure_ the
charging time and set the threshold in software. Also, this technique is
not affected by the input hysteresis. The main drawback is that the
measurement takes longer than the voltage divider technique.

**Edit**: I found a blog post describing this exact method in greater
detail: [Measuring resistance or voltage with 1 digital I/O][blog post],
by Moser.

[Schmitt trigger]: https://en.wikipedia.org/wiki/Schmitt_trigger

[datasheet]: http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_datasheet.pdf
[capmeter]: https://www.arduino.cc/en/Tutorial/CapacitanceMeter
[blog post]: https://reibot.org/2011/05/23/measuring-resistance-or-voltage-with-1-digital-io/

body:
**LDR in a Wheatstone bridge + OpAmp as a comparator**

For more (temperature...) stability of your LDR threshold it could be better to use a wheatstone bridge instead of a simple voltage divider.

Then you can send the output of your wheatstone (or your divider) to a simple OpAmp comparator circuit that will output High or Low, which you can plug in any digital port.

To know more on Wheatstone and OpAmp:
(you can use directly the last schema by plugging the output of the Opamp to the digital pin of your arduino (instead of sending it to the transistor)

http://www.electronics-tutorials.ws/blog/wheatstone-bridge.html

Hope that can help,

Gaetan

----------


body:
I want to make a piezo buffer beeping with assembly code, but i haven't managed to yet. I have an Arduino UNO board (ATMega328p) and using avra and avrdude to build and load. The buzzer just stay silent. Here's my code:

    .nolist
    .include "m328pdef.inc"
    .list

    .equ _a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

    .cseg
      ;wgm02..0 = 7 (fast pwm, top = ocr0a)
      ;cs02..0 = 4 (N=256)
      ;com0b1..0 = 2 (clear on compare match, set at bottom)
      ldi r16, 0b00100011
      sts tccr0a, r16 ;need out!
      ldi r16, 0b00001100
      sts tccr0b, r16 ;need out!
      ;ocr0a = _a to obtain 440Hz
      ldi r16, 141
      out ocr0a, r16
      ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
      ldi r16, 71
      out ocr0b, r16
      ;enable output at D5 aka oc0b aka Arduino pin 5
      sbi ddrd, 5
      loop:
      rjmp loop

Wiring is good and the buzzer too, since it works with a C sketch

EDIT: I found my answer by myself (with the help of answerers). I was accessing IO ports (tccr0a and tccr0b) with sts, while i had to use out. (tccr0a and tccr0b are IO ports defined in "m328pdef.inc" as IO addresses, not as memory addresses)

title: Controlling buzzer with assembly

Answers: 1

body:
I translated you program to GNU as syntax, and it works as expected: I
get a 440 Hz square wave on digital pin 5. Here is the
translated program:

    #include <avr/io.h>

    ; I'm too lazy to always type the full name of these macros
    #define io(reg) _SFR_IO_ADDR(reg)
    #define mem(reg) _SFR_MEM_ADDR(reg)

    _a = 141 ;(16000000 / 256) / 440(frequency of A) - 1

      ;wgm02..0 = 7 (fast pwm, top = ocr0a)
      ;cs02..0 = 4 (N=256)
      ;com0b1..0 = 2 (clear on compare match, set at bottom)
      ldi r16, 0b00100011
      sts mem(TCCR0A), r16
      ldi r16, 0b00001100
      sts mem(TCCR0B), r16
      ;ocr0a = _a to obtain 440Hz
      ldi r16, 141
      out io(OCR0A), r16
      ;ocr0b = ocr0a/2 to obtain a duty cycle of 50%
      ldi r16, 71
      out io(OCR0B), r16
      ;enable output at D5 aka oc0b aka Arduino pin 5
      sbi io(DDRD), 5
      loop:
      rjmp loop

As shown in my comment to your question, I suspect the problem is a
misunderstanding of the meaning of things like `tccr0a` and `ocr0a`.
In the translated version above, I admit I do _not_ know what `TCCR0A`
and co. mean. And I need not to: I can treat these as opaque
identifiers, as the avr-libc recommends to _always_ use them with the
macros `_SFR_IO_ADDR()` and `_SFR_MEM_ADDR()`, which provide the I/O
address and the data address of the register respectively.

I do not know how to use avra, so I cannot tell you how the get the I/O
or data address of a register. But there certainly must be a way. You
should always use the data address with `sts` and the I/O address with
`out` and `sti`.


body:
I am attempting to create a library out of an existing code to use inside of another code.  To clarify, I have one code, I need to add the functionality of another code to.  Instead of plopping the 400+ lines inside of my existing code, I would like to create a library to house the other code so I can make my code easier to read.  I followed the Arduino Library tutorial to get to where I am, but their code is simpler than mine.  Ironically, my code is also about Morse code.  I have included the library files and the code I am using to troubleshoot.  I have attempted to troubleshoot these errors on my own by googling problems, I managed to cut the list about in half, but I just can't seem to root out these last few.

I am posting in this order: Morse.cpp, Morse.h, Library Test Code, The errors I need help with (all of which relate to the above three files) and the functioning code as it was before I tried to create this library.

The Following is the Morse.cpp Library File

    /* Morse.cpp - Library for flashing Morse code.
    Created by Young on Sept. 1, 2016 */

    #include "Arduino.h"
    #include "Morse.h"

    Morse::Morse(int LED);
    {
    pinMode(LED, OUTPUT);
    _LED = LED;
    }
    Morse::Morse(int BEEP);
    {
    pinMode(BEEP, OUTPUT);
    _BEEP = BEEP;
    }

    _note = 587;

    _dotLen = 75;

    _dashLen = dotLen * 7;

    _elemPause = dotLen * 4;

    _Spaces = dotLen * 10;

    _wordPause = dotLen * 14;

    void MorseDot();
    void MorseDash();
    void LightsOff(int delayTime);
    void GetChar(char tmpChar);

    void Morse::MorseDot()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dotLen);     // start playing a tone
    delay(dotLen);                // hold in this position
    }

    void Morse::MorseDash()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dashLen);    // start playing a tone
    delay(dashLen);               // hold in this position
    }

    void Morse::LightsOff(int delayTime)
    {
    digitalWrite(led13, LOW);     // turn the LED off
    digitalWrite(BEEP, LOW);      // Silence the Beep
    delay(delayTime);             // hold in this position
    }

    digitalWrite(led13, LOW);     // turn the LED off
    digitalWrite(BEEP, LOW);      // Silence the Beep
    delay(delayTime);             // hold in this position

    void Morse::GetChar(char tmpChar)
    {
    // Take the passed character and use a switch to find the morse code for that character
    switch (tmpChar) {
        case 'a':
            MorseDot();
            LightsOff(elemPause);
            MorseDash();
            LightsOff(elemPause);
            break;
        case 'b':
            MorseDash();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            break;
        case 'c':
            MorseDash();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            MorseDash();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            break;
    /*This continues for the rest of the alphabet as well as numbers and characters,
    however to save space and time I have only listed a,b, and c */

The following is the Morse.h Library file

    /* Morse.h - Library for flashing Morse code.
    Created by Young on Sept. 1, 2016 */

    #ifndef Morse_h
    #define Morse_h

    #include "Arduino.h"

    class Morse
    {
    public:
    Morse(int LED, int BEEP, int delayTime, char tmpChar);

    void MorseDot();
    void MorseDash();
    void LightsOff(int delayTime);
    void GetChar(char tmpChar);

    private:
    int _LED;
    int _BEEP;
    int _delayTime;
    char _tmpChar;
    int _note;
    int _dotLen;
    int _dashLen;
    int _elemPause;
    int _Spaces;
    int _wordPause;
    };

    #endif

The following is the test code

    #include <Morse.h>

    int delayTime;
    int tmpChar;

    Morse dot();
    Morse dash();
    Morse dark(int delayTime);
    Morse set(char tmpChar);

    char stringToMorseCode[] = "N 36° 00.19518   W 084° 13.88856";    //Final Coordinates

    // Create variable to define the output pins
    int LED = 13;      // blink an led on output 12
    int BEEP = 14;      // output audio on pin 8
    int i;

    void setup()
    {

    }

    void loop()
    {
    // Loop through the string and get each character one at a time until the end is reached
    for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++);
    {
    // Get the character in the current position
    char tmpChar = stringToMorseCode[i];
    // Set the case to lower case
    tmpChar = toLowerCase(tmpChar);
    // Call the subroutine to get the morse code equivalent for this character
    set.GetChar(tmpChar);
    }

    // At the end of the string long pledause before looping and starting again

    dark.LightsOff(8000);            // hold in this position

    }

These are the errors I get when I run this code.

    /Users/DMYoung1/Documents/Arduino/Morse_Library_Test/Morse_Library_Test.ino: In function 'void loop()':
    Morse_Library_Test:33: error: request for member 'GetChar' in 'set', which is of non-class type 'Morse(char)'
       set.GetChar(tmpChar);
           ^
    Morse_Library_Test:38: error: request for member 'LightsOff' in 'dark', which is of non-class type 'Morse(int)'
     dark.LightsOff(8000);            // hold in this position
          ^
    exit status 1
    request for member 'GetChar' in 'set', which is of non-class type 'Morse(char)'

In case this will also help, this is the original code which I know works.  Hopefully this could help someone else understand the transformation of a slightly more complicated morse reader code into a library, so please feel free to respond as though I know nothing.  It will help me and could help someone else.

    /*
    Morse Code Project
    This code will loop through a string of characters and convert these to morse code.
    It will blink an LED light and play an audible tone on a piezo speaker.
    */

    char stringToMorseCode[] = "Convert to Morse"; //String to Convert

    // Create variable to define the output pins
    int led13 = 1;      // blink an led on output 12
    //int led6 = 0;        // blink an led on output 6
    int BEEP = 0;      // output audio on pin 8
    int note = 587;      // music note/pitch

    /*
    Set the speed of your morse code
    Adjust the 'dotlen' length to speed up or slow down your morse code
    (all of the other lengths are based on the dotlen)

    Here are the ratios code elements:
    Dash length = Dot length x 3
    Pause between elements = Dot length
    (pause between dots and dashes within the character)
    Pause between characters = Dot length x 3
    Pause between words = Dot length x 7

    */
    int dotLen = 75;     // length of the morse code 'dot'
    int dashLen = dotLen * 7;    // length of the morse code 'dash'
    int elemPause = dotLen * 4;  // length of the pause between elements of a character
    int Spaces = dotLen * 10;     // length of the spaces between characters
    int wordPause = dotLen * 14;  // length of the pause between words

    // the setup routine runs once when you press reset:
    void setup() {
    // initialize the digital pin as an output for LED lights.
    pinMode(led13, OUTPUT);
    pinMode(BEEP, OUTPUT);

    }

    // Create a loop of the letters/words you want to output in morse code (defined in string at top of code)
    void loop()
    {
    // Loop through the string and get each character one at a time until the end is reached
    for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++)
    {
    // Get the character in the current position
    char tmpChar = stringToMorseCode[i];
    // Set the case to lower case
    tmpChar = toLowerCase(tmpChar);
    // Call the subroutine to get the morse code equivalent for this character
    GetChar(tmpChar);
    }

    // At the end of the string long pause before looping and starting again
    LightsOff(8000);
    }

    // DOT
    void MorseDot()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dotLen);   // start playing a tone
    delay(dotLen);              // hold in this position
    }

    // DASH
    void MorseDash()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dashLen);   // start playing a tone
    delay(dashLen);               // hold in this position
    }

    // Turn Off
    void LightsOff(int delayTime)
    {
    digitalWrite(led13, LOW);     // turn the LED off
    digitalWrite(BEEP, LOW);      // Silence the Beep
    delay(delayTime);             // hold in this position

    }

    // *** Characters to Morse Code Conversion *** //
    void GetChar(char tmpChar)
    {
    // Take the passed character and use a switch case to find the morse code for that character
    switch (tmpChar) {
    case 'a':
    MorseDot();
    LightsOff(elemPause);
    MorseDash();
    LightsOff(elemPause);
    break;
    case 'b':
    MorseDash();
    LightsOff(elemPause);
    MorseDot();
    LightsOff(elemPause);
    MorseDot();
    LightsOff(elemPause);
    MorseDot();
    LightsOff(elemPause);
    break;

    //Again, this switch case would continue through the alphabet, but I am stopping
    //here because that would dramatically increase the length of this page

title: Creating a Library Help with errors

Answers: 1

body:
The problem is that you are trying to call a class function without an object (hence the error). The original code works because the functions are created without a class. When you add the class (in the library), you need to create an object to perform those functions with it. To do this, use the constructor `className object(parameters)`

So in your case, you'd do `Morse Object(LEDpin)`

To use your functions you can now do `Object.Function(parameters)`


body:
I'm new to Arduino. For my first project,  I want to make aviation strobe lights. My challenge is to use ONE Arduino to blink both sets of lights. My issue is,  I DON'T want them to be synchronized. I saved a sketch of the blink example from the Arduino IDE software after editing it to do what I want. But, the LED's are synchronized. One LED strobes twice,  while the other strobes once as I want them to. However, they begin their loops together currently and stay synchronized,  which isn't what I want.

So my question is: What is the code I need to write to make each LED blink unsynchronized from the other without having to use 2 Arduino units?

Code:

    int led = 11;
    int led2 = 12;

    void setup() {
      pinMode(led, OUTPUT);
      pinMode(led2, OUTPUT);
    }

    void loop() {
      digitalWrite(led, HIGH);
      delay(50);
      digitalWrite(led, LOW);
      delay(1000);
      digitalWrite(led2,  HIGH);
      delay(50)
      digitalWrite(led2, LOW);
      delay(100) ;
      digitalWrite(led2,  HIGH);
      delay(50)
      digitalWrite(led2, LOW);
      delay(1000);
    }

title: How to blink LED's unsynchronized?

Answers: 3

body:
It is not possible to escape the fact that both LEDs will be driven from a common clock.  However, it is possible to arrive at a convincing solution where the LEDs appear to be unsynchronized.  What is necessary is a rather fast event loop and rather large numbers which are not quite multiples of one another. As an example consider a loop with a delay of 10ms and two counter which will count up to 100 and 51 respectively.  Each time the counters reach their goal their respective LED is toggled and the counter is reset to zero.  One LED will appear to turn on off on with a period of about 2 second.  The other LED will turn on off on with a period of about 1 second.  However, over time,the second LED will start to trail the first.  Giving the appearance that they are not synchronized.

You can use any numbers you wish.  Edger suggested in the comments to use golden ratio numbers 144 and 89.

If you want to emulate the short burst of strobe lights you need to alter the suggested design (which provides a 50% duty cycle) to something that provides, say, a 10% duty cycle.

Let's adapt your code from above.  Add 2 counters one each for LED1 and LED2.  Define numbers for the period of LED1 and for LED2. Also define a number for the length of time the LEDs will be on for.  Notice that we only need one 10ms call to the delay method. All counters are incremented each time we enter the loop method.  Since our delay is 10ms we enter the loop method 100 times a second.  Inside the loop method we keep track and cap the counters at their predefined limits.  When we get close to those limits we turn on the appropriate LED.  When we hit the limit we turn off the appropriate LED and clear that LED's counter.

    // What is the period of led 1 in 10s of milliseconds.
    #define LED1_PERIOD_10MS 144
    // What is the period of led 2 in 10s of milliseconds.
    #define LED2_PERIOD_10MS 89
    // How long to keep the LED on in 10s of milliseconds.
    #define LED_ON_TIME_10MS 10

    int led = 11;
    int led2 = 12;
    unsigned int count_led1;
    unsigned int count_led2;

    void setup() {
      pinMode(led, OUTPUT);
      pinMode(led2, OUTPUT);

      count_led1 = 0;
      count_led2 = 0;
    }

    void loop() {
      count_led1++;
      if(count_led1 == LED1_PERIOD_10MS - LED_ON_TIME_10MS)
      {
        digitalWrite(led, HIGH);
      }

      if(count_led1 > LED1_PERIOD_10MS)
      {
        count_led1 = 0;
        digitalWrite(led, LOW);
      }

      count_led2++;
      if(count_led2 == LED2_PERIOD_10MS - LED_ON_TIME_10MS)
      {
        digitalWrite(led2, HIGH);
      }

      if(count_led2 > LED2_PERIOD_10MS)
      {
        count_led2 = 0;
        digitalWrite(led2, LOW);
      }

      // Delay 10ms.
      delay(10);
    }

I have only proof read the above code.  If you find any problems make a comment below and I will make the corrections.

body: You need to implement a pair of LFSRs, one for each LED. This will give a result that eventually repeats, but with registers of differing lengths and the correct polynomials it won't repeat quickly enough for it to matter.

body:
The Arduino Blink example uses `delay()` to pause the Arduino in a specific state, so that for a specific amount of milliseconds the device will keep the `blinkPin` `HIGH` or `LOW`.

Instead of using a `delay()`, you should use `millis()`. The main advantage of `millis()` over `delay()` is that it *does not* interrupt the code. When you call a `delay()` the whole code pauses, nothing can be done during those milliseconds. But `millis()` doesn't work that way. You also don't call it the same way as `delay()`.

What `millis()` does is that it stores a timer value into an `unsigned long`. At a later point in time you can substract a new `millis()` from your previously stored `millis` in the `unsigned long`. The result is a difference in time between each `millis()` in milliseconds.

Now, instead of using only one `unsigned long`, we use two different ones: one for each LED. Now you can log a time interval, independently, for each LED. Furthermore, if you apply the logic of `millis()` for keeping the LEDs on or off, you don't have to interrupt the code with `delay()` functions. This means, that regardless of each LEDs state (`HIGH` or `LOW`), the timer keeps running, keeps logging and thus can control both LEDs simultaneously.

To give you a bit more information on `millis()`, below are some references that will get you started in how to implement. If you have more questions, just comment on this answer :)

 - [`millis()` reference on the Arduino website](https://www.arduino.cc/en/Reference/Millis)
 - [Blink without Delay example](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay)


body: Is there a way to log events on Arduino when developing using C / AVR toolchain, and not the Arduino IDE? Working on Ubuntu.

title: Logging without IDE

Answers: 2

body: Any of these are straightforward: python (serial library) or processing (same type of user interface, will happily build portable java programs for linux/win/mac). I use an awful perl script for logging stuff, can't recommend it. If you don't prefer the two first options, have a look at IPC::Open2 or IPC::Open3 - I use a bidirectional connection so I can send stuff, but I rely on 'tip' to do the serial connection stuff. If I wanted to log more than a few things, I would probably use python, which is much easier to read (later), and it will require a small fraction of the memory a fullblown java applet.

body:
On Ubuntu, I usually simply do

    stty -F /dev/ttyACM0 raw 9600
    cat /dev/ttyACM0 > the.log.file

Replace 9600 with your baud rate of choice.


body:
I have an ESP8266 module connected to my Arduino Mega 2560. I sketched a simple code to pass whatever command I typed from the Serial Monitor to ESP8266 and vice versa:

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

    void loop() {
      if (Serial.available())
      {
        Serial2.write(Serial.read());
      }

      if (Serial2.available())
      {
        Serial.write(Serial2.read());
      }
    }

So from here on I just type my AT commands inside Serial Monitor and receive the output also inside Serial Monitor. Managed to connect into a wifi network using the command:

    AT+CWJAP="SSID","password"
And obtain my ESP8266 module's IP address using the command:

    AT+CIFSR

    +CIFSR:APIP,"192.168.4.1"
    +CIFSR:APMAC,"5e:cf:7f:c2:ce:30"
    +CIFSR:STAIP,"192.168.1.103"
    +CIFSR:STAMAC,"5c:cf:7f:c2:ce:30"

    OK
Problem is, whenever I run CMD and "ping 192.168.4.1" or "ping 192.168.1.103" from my PC which is connected to the same network, I will get "request timed out". Pinging my own PC's IP gets me a reply. What is wrong here? Totally clueless... :-/

*EDIT* My PC's IP address is 192.168.56.1

title: Cannot ping ESP8266's IP address from a computer on the same network

Answers: 2

body:
First, you need to confirm that your PC's wireless connection is on the same IP subnet as the ESP8266. At the CMD prompt, type:

    ipconfig /a

and look for the wireless adapter. Hopefully the IP address will start with `192.168.1.`... It should but there's no harm in checking!

Second, check that your WiFi router _hasn't_ disabled pinging between its clients - some do (mine did, until I threw it out...). Do you have a smartphone or other WiFi device? If so, find out its IP address (hopefully also `192.168.1.`...) and confirm that you can ping it.

Pinging your own address isn't very useful. Normally it detects the fact that it's its own address, and replies with no attempt at sending over the air.

body:
The IP address `192.168.4.1` is the default IP address used by the ESP8266 when it is running as an access point. You can ignore that, it doesn't actually exist.

You need to make sure that you are actually connected to the access point by issuing `AT+CWJAP?` which should respond with the access point name an `OK` if it is connected.

Secondly you need to make sure that you are on the same network segment as your ESP8266 - that is, the same *subnet*.  If your computer isn't on an address in the range 192.168.1.1 to 192.168.1.254, and your subnet mask is set to (what is usually the default) 255.255.255.0, then you won't be able to communicate unless there is an appropriate route between the subnets.

Also some wireless routers impose *client separation* on the WiFi channel, which means that WiFi devices cannot talk to each other, and LAN devices cannot talk to the WiFi devices. This is usually something that can be disabled in the router's configuration.


body:
I am trying to do voltage measurement using Arduino. I am using a voltage divider circuit to reduce the voltage to less than 5V. I measured the voltage on the 5V pin of Arduino and found out that its 4.279 V (I am powering through USB).  So, I am doing following calculations for voltage measurement:

    int data1   = analogRead(A0);
    float data2 = data1 * (4.279/1023.0);
    float volts = data2 * (10 + 2.2)/2.2;  //R1=10k , R2=2.2k
    Serial.println(volts);

    if(volts > 12.00)
    {
      digitalWrite(6,HIGH);
    }
    if(volts < 12.00)
    {
      digitalWrite(6,LOW);
    }

So I am getting exact values of voltage. Now I have put a condition like if volt is greater than 12V, turn on an output, else turn off the output. For output, I have a transistor and mosfet connected. As soon as the voltage increases above 12V, output get on but the problem is that when the output is on, Arduino displays wrong values. Like if the voltage is 12.3, it shows 13.6.

I looked it into more and found out that the voltage at 5V pin of Arduino (`4.279`) gets reduced to `3.865` and due to which calculation goes wrong and it displays wrong values of voltage.

Is there anything which I am doing wrong? Is there any function or keyword in Arduino libraries which can tell us the voltage or is there any way through which we can measure it? I tried putting the 5V pin to analog pins to read it and convert it into volts but again for this we need a reference voltage.
I hope I have explained the question clearly.

Schematic

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/RacXP.png

`A0` is the analog pin and `PIN6` is digital output of arduino

title: How to read Arduino voltage

Answers: 1

body:
It would appear that the wrong A/D reading is due to the reduced +5V output. The A/D reference is powered by the input to the computer chip. The big question is what is causing the voltage drop. Are you powering something else
from the USB supply when the FET is turned on? Bottom line is that you cannot
expect the A/D to read the same voltage when the voltage input to the computer chip is changed.


body:
I'm using RFduino to do analogRead at pin 2 and pin 0. Pin 2 works perfectly, and I got the result. However, for pin 0 it returns all zero.

    #include <RFduinoBLE.h>

    static const int topPin = 2;
    static const int bottomPin = 1;

    int top;
    int bottom;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(topPin, INPUT);
      pinMode(bottomPin, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
        RFduino_ULPDelay( SECONDS(0.01) );

        bottom = analogRead(bottomPin);
        top = analogRead(topPin);

        Serial.print(top);
        Serial.print(" ");
        Serial.print(bottom);
        Serial.print("\n");
    }

I double checked the wires and it's OK. I measured the voltage across pin 0 and it's 3.3V. How do I fix this problem? There's no shortage between pin 0 and 3.3V.

title: AnalogRead(0) always returns 0 on RFduino

Answers: 2

body:
Without RFDuino specs handy, I'm guessing - but I think it's likely - that the A/D converter gets shut down in an ultra low power sleep and requires some amount of time to wake up. The mis-reading pin, pin 0, is the one your sketch reads immediately on waking. That read call probably takes long enough that the A/D wakes up by the time your read pin 2 so it gives a better reading.

Try switching the order in which you read the pins and see if pin 2 mis-reads if you try to read it immediately after waking. If it does, the cure may be as simple as a 10-100 uSec delay between waking and trying to read any analog data. I just pulled that number out of the air; you might start with a couple of milliseconds and see how low you can make it before you start to see errors, then double that amount.

body:
I couldn't find an usable datasheet for the RFduino, seems like a very
poorly documented board. But I found an enlightening [comment in the
source code of the RFduino library][source]:

> Only pins 1-6 is avaliable [sic] for using as ADC inputs

If you read the source, it is clear that calling `analogRead()` on an
inappropriate pin is supposed to return 0.

[source]: https://github.com/RFduino/RFduino/blob/master/cores/arduino/wiring_analog.c#L97


body:
I'm using a RFduino to do analogRead at pin 2, and pin 0.

Pin 2 works correctly. Pin 0 returns zero all the time. I measured the voltage at pin 0, and it's 3.3V (Vcc).

I turned off the circuit, and double checked that there's no connection between pin 0 and Vcc (used the multimeter, at the sound mode). As soon as I plug into power, V at pin0 is Vcc.

How do I fix this problem?

    #include <RFduinoBLE.h>

    static const int topPin = 2;
    static const int bottomPin = 0;

    int top;
    int bottom;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(topPin, INPUT);
      pinMode(bottomPin, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
        RFduino_ULPDelay( SECONDS(0.01) );

        bottom = analogRead(bottomPin);
        top = analogRead(topPin);

        Serial.print(top);
        Serial.print(" ");
        Serial.print(bottom);
        Serial.print("\n");
    }

title: analogRead problem

Answers: 0


body:
This seems to be a very common error, I am struggling to understand what exactly the solution to this is.  I am attaching everything, library files, code, and errors.  If you have a moment, I need help with these two errors which appear to be caused by the same problem.  Fixing these errors may however not be the end of my problems so if you notice something else please point it out!!  I recognize my own incompetence regarding this topic any help will be appreciated.

This is a Morse Code Encoder, my goal is to transform the original functional code into a library so that I can insert it into another code more easily.

The Following is the Morse.h Library File (I created this with the Arduino Library Tutorial)

    /* Morse.h - Library for flashing Morse code.
    Created by Young on Sept. 1, 2016 */

    #ifndef Morse_h
    #define Morse_h

    #include "Arduino.h"

    class Morse
    {
    public:
    Morse(int LED, int BEEP, int delayTime, char tmpChar);

    void MorseDot();
    void MorseDash();
    void LightsOff(int delayTime);
    void GetChar(char tmpChar);

    private:
    int _LED;
    int _BEEP;
    int _delayTime;
    char _tmpChar;
    int _note;
    int _dotLen;
    int _dashLen;
    int _elemPause;
    int _Spaces;
    int _wordPause;
    };

    #endif

The following is the Morse.cpp Library (I created this with the Arduino Library Tutorial)

    /* Morse.cpp - Library for flashing Morse code.
    Created by Young on Sept. 1, 2016 */

    #include "Arduino.h"
    #include "Morse.h"

    Morse::Morse(int LED);
    {
    pinMode(LED, OUTPUT);
    _LED = LED;
    }
    Morse::Morse(int BEEP);
    {
    pinMode(BEEP, OUTPUT);
    _BEEP = BEEP;
    }

    _note = 587;

    _dotLen = 75;

    _dashLen = dotLen * 7;

    _elemPause = dotLen * 4;

    _Spaces = dotLen * 10;

    _wordPause = dotLen * 14;

    void MorseDot();
    void MorseDash();
    void LightsOff(int delayTime);
    void GetChar(char tmpChar);

    void Morse::MorseDot()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dotLen);     // start playing a tone
    delay(dotLen);                // hold in this position
    }

    void Morse::MorseDash()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dashLen);    // start playing a tone
    delay(dashLen);               // hold in this position
    }

    void Morse::LightsOff(int delayTime)
    {
    digitalWrite(led13, LOW);     // turn the LED off
    digitalWrite(BEEP, LOW);      // Silence the Beep
    delay(delayTime);             // hold in this position
    }

    digitalWrite(led13, LOW);     // turn the LED off
    digitalWrite(BEEP, LOW);      // Silence the Beep
    delay(delayTime);             // hold in this position

    void Morse::GetChar(char tmpChar)
    {
    // Take the passed character and use a switch to find the morse code for that character
    switch (tmpChar) {
        case 'a':
            MorseDot();
            LightsOff(elemPause);
            MorseDash();
            LightsOff(elemPause);
            break;
        case 'b':
            MorseDash();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            break;
        case 'c':
            MorseDash();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            MorseDash();
            LightsOff(elemPause);
            MorseDot();
            LightsOff(elemPause);
            break;
    //This continues through z and then 0-9, I have shortened it hear for ease of
    //reading.  Each break statement functions fine in the original code.

The following is the test code

    #include <Morse.h>

    int delayTime;
    int tmpChar;

    Morse dot();
    Morse dash();
    Morse dark(int delayTime);
    Morse set(char tmpChar);

    char stringToMorseCode[] = "String to be converted to morse code";

    // Create variable to define the output pins
    int LED = 13;      // blink an led on output 12
    int BEEP = 14;      // output audio on pin 8
    int i;

    void setup()
    {

    }

    void loop()
    {
    // Loop through the string and get each character one at a time until the end is reached
    for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++);
    {
    // Get the character in the current position
    char tmpChar = stringToMorseCode[i];
    // Set the case to lower case
    tmpChar = toLowerCase(tmpChar);
    // Call the subroutine to get the morse code equivalent for this character
    set.GetChar(tmpChar);
    }

    // At the end of the string long pledause before looping and starting again

    dark.LightsOff(8000);            // hold in this position

    }

These are the errors I get when I run this code.

    /Users/Young1/Documents/Arduino/Morse_Library_Test/Morse_Library_Test.ino: In function 'void loop()':
    Morse_Library_Test:31: error: request for member 'GetChar' in 'set', which is of non-class type 'Morse()'
    set.GetChar(tmpChar);
        ^
    Morse_Library_Test:36: error: request for member 'LightsOff' in 'dark', which is of non-class type 'Morse()'
    dark.LightsOff(delayTime);            // hold in this position
         ^
    exit status 1
    request for member 'GetChar' in 'set', which is of non-class type 'Morse()'

This is an exercise for me in improving my own skills.  I have spent a day since my last issue (trying to call a class function without an object) researching my problems, however I have been unable to relate the variety of similar questions and answers to my own code.  It seems that most of them deal with a misplaced ().  If you find something that is wrong, please assume that I know nothing.  Post as though you are trying to teach a child how to use Arduino.

I am adding the original code which I am trying to transform into a library for the purpose of inserting it into another code without inserting all 453 lines.

    /*
    Morse Code Project

    This code will loop through a string of characters and convert these to morse code.
    It will blink two LED lights and play audio on a speaker.
    */

    char stringToMorseCode[] = "String to convert to Morse";

    // Create variable to define the output pins
    int led13 = 1;      // blink an led on output 12
    //int led6 = 0;        // blink an led on output 6
    int BEEP = 0;      // output audio on pin 8
    int note = 587;      // music note/pitch

    /*
    Set the speed of your morse code
    Adjust the 'dotlen' length to speed up or slow down your morse code
    (all of the other lengths are based on the dotlen)

    Here are the ratios code elements:
    Dash length = Dot length x 3
    Pause between elements = Dot length
    (pause between dots and dashes within the character)
    Pause between characters = Dot length x 3
    Pause between words = Dot length x 7
    */
    int dotLen = 75;     // length of the morse code 'dot'
    int dashLen = dotLen * 7;    // length of the morse code 'dash'
    int elemPause = dotLen * 4;  // length of the pause between elements of a character
    int Spaces = dotLen * 10;     // length of the spaces between characters
    int wordPause = dotLen * 14;  // length of the pause between words

    // the setup routine runs once when you press reset:
    void setup() {
    // initialize the digital pin as an output for LED lights.
    pinMode(led13, OUTPUT);
    pinMode(BEEP, OUTPUT);

    }

    // Create a loop of the letters/words you want to output in morse code (defined in string at top of code)
    void loop()
    {
    // Loop through the string and get each character one at a time until the end is reached
    for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++)
    {
    // Get the character in the current position
    char tmpChar = stringToMorseCode[i];
    // Set the case to lower case
    tmpChar = toLowerCase(tmpChar);
    // Call the subroutine to get the morse code equivalent for this character
    GetChar(tmpChar);
    }

    // At the end of the string long pause before looping and starting again
    LightsOff(8000);
    }

    // DOT
    void MorseDot()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dotLen);   // start playing a tone
    delay(dotLen);              // hold in this position
    }

    // DASH
    void MorseDash()
    {
    digitalWrite(led13, HIGH);    // turn the LED on
    tone(BEEP, note, dashLen);   // start playing a tone
    delay(dashLen);               // hold in this position
    }

    // Turn Off
    void LightsOff(int delayTime)
    {
    digitalWrite(led13, LOW);     // turn the LED off
    digitalWrite(BEEP, LOW);      // Silence the Beep
    delay(delayTime);             // hold in this position

    }

    // *** Characters to Morse Code Conversion *** //
    void GetChar(char tmpChar)
    {
    // Take the passed character and use a switch case to find the morse code for that character
    switch (tmpChar) {
    case 'a':
    MorseDot();
    LightsOff(elemPause);
    MorseDash();
    LightsOff(elemPause);
    break;
    case 'b':
    MorseDash();
    LightsOff(elemPause);
    MorseDot();
    LightsOff(elemPause);
    MorseDot();
    LightsOff(elemPause);
    MorseDot();
    LightsOff(elemPause);
    break;

    //This continues through z and then 0-9, but it adds a few hundred lines we
    //don't need to read here.

title: Debugging my created Library - Error - request for member ... which is of non-class type

Answers: 1

body:
The main problem lies with your object instatiation:

    int delayTime;
    int tmpChar;

    Morse dot();
    Morse dash();
    Morse dark(int delayTime);
    Morse set(char tmpChar);

Morse has a constructor format thus:

    Morse(int LED, int BEEP, int delayTime, char tmpChar);

When you instantiate an object from a class and call the constructor you have to pass all the parameters to the constructor (unless they have been given a default value, in which case you can leave them out from the right-most only).

You never provide `()` if there are no parameters needed for the constructor - this is a little idiom of C++ that I have never understood.  To break it down:

    Morse dot();
    Morse dash();

These have no parameters being passed. Lose the () if that  is intentional (and you have a matching constructor with no parameters) or add the four parameters for the constructor.

    Morse dark(int delayTime);
    Morse set(char tmpChar);

In these two you are trying to pass one parameter only, and for some reason you are also trying to give it a type at the same time. I can only think that it may be to try and indicate which parameter you mean. That is not right. You must provide all the parameters. Also you are passing values from variables that haven't been given a value yet, so it is actually completely meaningless.

I am not entirely sure what you are hoping to achieve with those last two there...

A further issue, digging into your actual class, is these odd constructors:

    Morse::Morse(int LED);
    {
    pinMode(LED, OUTPUT);
    _LED = LED;
    }
    Morse::Morse(int BEEP);
    {
    pinMode(BEEP, OUTPUT);
    _BEEP = BEEP;
    }

They have no matching prototype in the class header, and even if they did, the compiler will have no way of differentiating between them. They both have the same type (`int`). Overloading operates on the type, not the name of the variable.

Oh, and the one constructor you do have a prototype for just plain doesn't exist in your code.


body:
I'm designing a custom board with an atmega2560. It will be programmed using ArduinoISP. I want to be sure that i have made no mistakes on my schematic design before I order it. I folloud the schematic for the arduino mega 2560 from the arduino website. For the basic function of uploading a sketch is my design correct?[![][1]][1]

I can upload the full schematic on pdf if you need it but it just contains some ICs for the final board.[![enter image description here][2]][2]

This is the pcb design as asked in the comments!

  [1]: https://i.stack.imgur.com/Y63rs.png
  [2]: https://i.stack.imgur.com/yodqf.png

title: Is my atmega2560 schematic correct?

Answers: 1

body:
***for the basic function of uploading a sketch*** your board schematics is indeed correct and going to work.
I can't say much on the PCB as what you have posted is a partial design, in particular it doesn't show the solder mask expansion and other _details_ which might greatly influence the final result.

Please also note you don't need a `reset` button, a voltage regulator nor an external oscillator ***for the basic function of uploading a sketch***, but I believe you also want to have the ability to run the sketch without the programmer being attached...


body:
I want to avoid global variables when using my own classes in Arduino. Here is a example.

    void setup(){
    /* setup here */
      classA objectA;
    }

    void loop(){
      objectA.someMethod();
    }

I know that my compiler will complain about it (out of scope, etc) but is it possible to do that or just forget it and use globally?

Thanks in advance!

title: Avoid global variables with classes

Answers: 1

body:
If you want a variable to be available within more than one function it has to be global. There is no other possible way of doing it.

If you are only using the variable in the loop() function and nowhere else you can declare it `static` in `loop()`, which has the same effect of making it global, but it is only possible to see it within `loop()`.

You can make a *pointer* global, then create a new object in `setup()` (using `new...`) and assign it to the pointer, but that has the potential of making a mess of your heap and should be avoided unless absolutely necessary. Also it's pointless, because you don't gain anything over having the object statically created in the global scope.