body:
i want to create a somewhat complex structure of classes in an arduino. The short story is: a Device has Presets, and each Preset has a Patterns. For that i created the following structure (i am only posting the important stuff, if something is missing let me know):

**INO file**

    #include "LedDevice.h"

 LedDevice device;

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

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

**LedDevice**

 #if !defined(_LEDDEVICE_H)
 #define _LEDDEVICE_H

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

 class LedDevice {
 public:
   Preset* Presets[];

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

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

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

 #endif  //_LEDDEVICE_H

**Preset**

    #if !defined(_PRESET_H)
 #define _PRESET_H

 #include "Pattern.h"

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

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

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

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

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

 #endif

**Pattern**

 #if !defined(_PATTERN_H)
 #define _PATTERN_H

 class Pattern {
 public:

   Pattern(int numPixels){}

   void Tick(){}
 };

 #endif

The code compiles but when i run the full version (this is a simplified version of the code) i get some strange behavior, so i would like to know if i am doing the initialization of the Presets and Patterns correctly.

Also when i try to print the Preset name in the LedDevice Tick function i get strange characters, so either i am not initializing the string correctly or the pointers to the Presets are wrong.

Can you tell if anything is not being done correctly in the constructors?

title: Initializing pointer to vector of objects inside another object

Answers: 2

body:
This is wrong:

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

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

---

>     Preset* Presets[];

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

---

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

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

---

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

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

---

There is too much dereferencing going on here. Please post a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). For example, make the classes in question do not much. Then make code we can actually work on.

---

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

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

body:
Three things that need to be different:

    Pattern* Patterns[];

should be

    Pattern** Patterns;

It's a pointer to some pointers to patterns, not a pointer to an array (which is basically a pointer itself so same basic idea but an array implies a known size).

and

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

should be

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

*Patterns is the thing pointed to by Patterns which at this point is undefined. You want to set Patterns to the allocated address.
And we only need to allocate space for the pointers not the actual objects.

Your for loops then become

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

You then have the same issues with Presets.

And finally

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

should be

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


body:
I have worked with Arduino before, but not with WiFi modules. I always used RF or other methods.

Now I am working on a project where i need to connect two UNOs, over long distance, but they will have a continuous internet connection.

One board with only send data, and one will only receive.

Will the esp8266 soc suffice for this? They will have fast network connection; at least 4g speeds. So can I send and receive real time data over the internet, and receive it fast? It should feel like there is no delay on the receiving side. Can I do this with the ESP, and if so, can any one point me towards the right material to get started.

thx in advance :)

title: Connecting two arduinos with wifi over the Internet

Answers: 2

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

body:
The ESPs are easy to work with and more than capable, BUT (there's always a "but"): with a public network in the middle, latency, routing, and traffic issues will be beyond your control. Look, for instance, at the variability in page load times when loading over the internet.

If you use an IoT server in the middle, there will be server delays outside your control as well, though connecting to a common server from both ends can make it much easier to get everything talking for the first time. (There may, however, be data-rate limits imposed on you if the server in the middle is a free service.)

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

Define "real fast". Do you mean "really quickly" (short delay from start of transmission to start of reception at the other end)? Or "really high throughput" (moving lots of data in a short time, or continuously without falling behind? Or something else?

Since you're working with an Uno, if you need to use a SoftwareSerial port to talk to the ESP, the SS will be limited to 9600 baud (equivalent to 960 Bytes/sec) and your ability to push data through it to somewhat under that. If you can use the built-in hardware UART your data-rate to/from an ESP can be much higher, at least 115200 baud or 11,520 B/sec (again, gross rate; rate of pushing data will be somewhat lower).

tl;dr: The network will be a much greater limitation than the ESP devices.

Update:

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

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


body:
I'm asking this because I'm using a timer to generate a 38KHZ signal to drive an IR diode, and I also need to use SoftwareSerial to talk to an HC-12 radio using serial communication.

The code I'm using was written by Nick Gammon and is here:

    //Setup Conter/overflow to create 38KHZ drive for IR38KHZ
    //38khz, no interrupts
    #define IR_CLOCK_RATE 38000L
    // toggle on compare, clk/1
    TCCR2A = _BV(WGM21) | _BV(COM2A0);
    TCCR2B = _BV(CS20);
    // 38kHz carrier/timer
    OCR2A = (F_CPU/(IR_CLOCK_RATE*2L)-1);
    pinMode(IR38KHZ, OUTPUT);

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

title: Does SoftwareSerial use hardware timer?

Answers: 1

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


body:
i've got a bit of a problem with my Arduino UNO.

So coming back to my (pretty basic) build after a bathroom break, I go to un-assemble my circuit (on the breadboard) and grabbing the LED causes a static shock.

Since then I haven't been able to get any power to come out of the Arduino to the breadboard circuitry.

**I have tried:**

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

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

Any help would be much appreciated!

title: Arduino 5v output dead?

Answers: 1

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

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

Update:

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

Right - I read right past it. :( So you've done the right things (except no mention of testing other pins) so I'm not sure what your question is. The title asks about the board's 5v supply but that _must_ be up b/c your board uploads and runs Blink. That really leaves only the the pin driver(s) you were using when you zapped it.

You can salvage the board by testing all the pins in their input, output, analog, and other functions, and make a note of what capabilities have been lost. Clearly not all of them - pin 13 still works, for instance, because Blink worked. You can't repair damage internal to the chip without replacing it, and I would always consider it suspect, but it will be fine for many hobby uses if you just avoid the damaged functions.


body:
I am a beginner at Arduino. I want to power the Arduino through the USB cable that is usually plugged in the USB of the laptop, but plugged in the wall instead of the laptop.

Here are my questions:

 - Can I use a phone charger that has a USB (in which the end of the USB
   cable will go instead of the USB of the PC)?

 - What should I look for written on the charger so it is best
   compatible?

 - Is it ok to be done that way?

 - Will it be the same as means of power like when it is plugged in the
   PC (for example when later on I connect LCD display, diodes, etc.)?

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

title: Arduino and USB power, what to choose

Answers: 2

body:
Yes, you can power the Arduino using a USB phone charger.

The Arduino Uno draws less than 100mA when connected by itself. So ideally you would want the USB phone charger to provide at least 100mA. All of the USB chargers I have come across to date provide more than 400mA. Most of the modern USB chargers provide upwards of 1A for fast charging of your phone.

A USB(2) port of a laptop can provide up to 700mA to the Arduino (500mA continuous).

In terms of the overall current draw, it really depends on what you have connected to the Arduino. LEDs generally draw 20mA or less per LED. Some screens can draw anything from <100mA to a couple of amps. Most of the screens I have come across draw less than 1A. It really depends on the devices you want to connect.

For the most part, a USB charger will be sufficient.

body:
As you are still a beginner so I would not go into complex details. Your Arduino can run perfectly on a laptop powered USB but try to avoid connecting the power hungry electronics with your Arduino while powering it from the laptop USB port.

A Laptop USB port can give nearly 700mA that is enough for Arduino to run a couple of sensors easily.

Secondly, most wall chargers give 1A(1000mA) current that is better in my opinion. It can handle some power hungry electronics better then connecting your Arduino with the Laptop USB port.

I personally power my Arduino with either a Wall Charger or a power bank. Hope it helped solve your problem.

The more you dig into Arduino, the more fun it becomes. So have fun and be Creative.


body:
I currently have a camera I am trying to run off an Arduino. I am new to Arduino and I have had trouble figuring out what serial and myserial really do. I also don't understand why, when I have something like `serial.write(0x56)` I will get the output in the serial monitor to be V in hex, but If I have the Arduino also connected to an oscilloscope, I won't be able to see the signal.

Yet if I have `myserial.write(0x56)`, I won't see anything in the serial monitor, but will see the bits on my oscilloscope.

Also, if I send a command to my camera, my camera should send back some hex values if the write command is sent. I understand I can send commands via `myserial.write(0x56)`, but how would I read the hex values the camera would send back?

title: Arduino Serial and myserial clarification. How to print out rx output?

Answers: 1

body:
It seems like you are using both the hardware UART pins and two other pins for [SoftwareSerial](https://www.arduino.cc/en/Reference/softwareSerial) i.e. UART emulated by the arduino.

When you write `Serial.read()` or `Serial.write()`, Arduino knows to use the UART hardware on the chip which is has RX/TX pins 0 and 1 for most Arduinos. So by using these functions you will be able to communicate with any device which is connected on these pins.

Generally, when you have the Arduino connected to your computer, these RX/TX pins internally go to a serial port on your computer via the USB, hence you can send/receive data to the computer and view it on the Serial Monitor. Great for debugging purposes!

Sometimes, like in your case for controlling the camera, you need to have another serial port for communication because UART is point to point i.e. only 2 devices can communicate via it. `SoftwareSerial` helps you do that by using  two other pins on the Arduino into RX/TX pins. If you look at the top of your code file you will see a line like this

    SoftwareSerial mySerial = SoftwareSerial(...);

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

Hence, to be able to receive data from the camera you will use `mySerial.read()`.


body:
how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.

here is my code

    #include <DS3231.h>
    #include <Wire.h>
    #include <avr/sleep.h>

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

     DS3231 clock;
     RTCDAteTime dt;

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

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

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

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

       //check alarm settings
        checkAlarms();
      }

       void checkAlarms()
      {
       RTCAlarmTimea1;
       RTCAlarmTimea2;

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

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

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

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

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

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

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

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

title: sleep and wake up arduino mega according to ds3231 interrupt

Answers: 1

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


body:
Hello everyone I'am new to this site so please bear with me.

I have an **`Arduino Uno`** that I'm using in my simple project using `VS 2008`. I got this error says `The Port COM1 does not exist`. The flow of my project is after inserting a `coin` into the `coin slot` the arduino will pass the data into my project and it will display into a Label or Textbox the value of the inserted coin.

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

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

title: Arduino Serial Port. COM1 does not exist

Answers: 2

body:
Never used Visual Basic but:

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

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

[Arduino]: https://www.arduino.cc/en/Reference/Serial

body:
Probably it is on another COM port. When I checked my IDE (from Arduino) the Arduino was found at COM3.

You probably have to iterate through the (PC) COM ports to find out where the Arduino is connected to.


body:
What is an "Arduino core"?

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

title: Explain what is meant by "Arduino core"

Answers: 4

body:
As far as I know the cores are the different products which can be found at [Products][1]. In this list the Arduino cores can be selected in the IDE: [Cores][2]

LCD display (driver) etc. are mostly referred as shields or modules. A shield is a small 'board' you can stack on top of the Arduino (Core) and a module is normally to be used on a breadboard.

  [1]: https://www.arduino.cc/en/Products/Compare
  [2]: https://www.arduino.cc/en/Guide/Cores

body:
The Core is the software API for a specific group of chips.

For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.

It is the code that provides things like digitalRead(), analogWrite(), millis() etc.

Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.

In your default IDE installation the Arduino AVR core can be found within the `hardware/arduino/avr/cores/arduino` folder.

Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.

body:
The "core" provides the low-level APIs (Application Programmer Interfaces) which are documented in the [Arduino Reference page](https://www.arduino.cc/en/Reference/HomePage). For example, `digitalRead`, `digitalWrite`, `delay` and so on.

The core files usually contain the "include" files from Atmel which provide documented names for the various registers in the chip (eg. `DDRB` for data direction register B).

Since each chip type will have different addresses for the registers you will need a different core for each processor chip. Also in some cases people have assembled the chip onto different boards, and the cores will reflect how the board is wired. For example "edge pin 8" on one board may connect to a different pin on the processor chip compared to another board. Thus if you buy a board from a third-party they may also supply their own core files.

---

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

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

---

## Selecting a core

As Majenko mentions in his answer, selecting a board in the IDE (Integrated Development Environment) usually tells the IDE to select the appropriate core for that board/chip combination.

More recent versions of the IDE allow you to install more cores by providing a link to where the core files are to be found, and then allowing you to choose one or more cores from that site.

body:
The collection of MCU's that are part of the Arduino family have differences from one to another in features like the address in memory-space of the basic processor registers, the I/O pin assignments to the I/O registers, nature and operation of timers, A/Ds, etc. The kinds of things we do with calls like pinMode(), digitalWrite(), or attachInterrupt().

These are considered the basic or "core" functions to be presented to the programmer by using libraries to present a common interface and hide those differences. The core libraries are managed by the Arduino IDE and the proper one(s) are selected when you select a board-type from the Tools | Board menu.

This is different from the user-contributed and other non-core dependent libraries you keep in your workspace 'libraries' folder. Both kinds are code libraries, but the so-called "core-libraries" are specific to the kind of processor you are compiling your sketch to run on.


body:
I bought a Tiny RTC I2C module and it doesn't work.
When i run the TimeRTCSet from TIME library all i get is:

    Unable to sync with the RTC
    0:00:00 0 0 1970
    0:00:01 1 1 1970
    0:00:02 1 1 1970
    0:00:03 1 1 1970
    0:00:04 1 1 1970
    0:00:05 1 1 1970
    0:00:06 1 1 1970
    0:00:07 1 1 1970

The module is connected like this:

Vin -> 5V
Gnd -> Gnd
SCL -> A5
SDA -> A4

I'm using arduino uno.

I tried with a simple i2c scanner, but it returned two devices!

    Scanning...
    I2C device found at address 0x50  !
    I2C device found at address 0x68  !
    done

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

Could you help me?

title: Tiny RTC I2C module not working

Answers: 2

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

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


body:
I was reading a [tutorial][1] on timers. My aim is to generate 16MHz pulse output from the pin 8.

Here is the code I modified from the tutorial (I use Arduino's ATmega328P):

    #include <avr/io.h>
    #include <stdint.h>

    int main (void)
    {
     DDRB |= (1 << 0); // Set LED as output
     TCCR1B &= ~(1 << CS11); // Set up timer
     TCCR1B &= ~(1 << CS12); // Set up timer
     TCCR1B |= (1 << CS10); // Set up timer

     for (;;)
     {
      // Check timer value in if statement
      if (TCNT1 >= 0)
      {
       PORTB ^= (1 << 0); // Toggle the LED
       TCNT1 = 0; // Reset timer value
      }
     }
    }

I use the following formula:

> Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
> Frequency) - 1

So Target Timer Count = 0 in my case.

But I get 615kHz on scope.

My timer setting should output 16MHz since I use no prescaler:

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

What am I doing wrong?

  [1]: http://www.avrfreaks.net/forum/tut-c-newbies-guide-avr-timers?page=all
  [2]: https://i.stack.imgur.com/UlhJ2.jpg

title: A confusion with setting timers

Answers: 1

body:
If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.

The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.

If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.


body:
The serial prints are for troubleshooting. All outputs are LEDs for testing purposes. The running 1 and 2 states are sometimes skipped over, but not always. I think this is from the light sensor being bad and jumping up and down, but using a higher value does nothing. I also tested the light sensor in the example program and got 1s and 2s so that really shouldn't be the problem. When it does work and the second light sensor is covered (the one that measures sugar level) it continuously cycles through and never returns to ready state. If more detail is needed please let me know

    //Digital Inputs
    int measureSwitch = 13; //switch that sets 2 tsp and 1 tsp

    //Digital Outputs
    int motor = 12;
    int buzzer = 11;
    int readyLed = 10;
    int running1Led = 9;
    int running2Led = 8;
    int doneLed = 7;
    int sugarLevelLed = 6;

    //Analog Inputs
    int cupSensor = 20; //the light sensor should read 0 when the cup is resting on it
    int lightSensor = 100; // the sugar should cover up thelight sensor so the light can pass thru, making it zero

    //different run times

    int running1Time = 100; //1 tsp tentative times
    int running2Time = 250; //2 tsp tentative times
    int buzzerTimer = 200; // how long the buzzer will go off for

    void setup() {
      Serial.begin(9600);
      pinMode(measureSwitch, INPUT);
      pinMode(motor, OUTPUT);
      pinMode(buzzer, OUTPUT);
      pinMode(readyLed, OUTPUT);
      pinMode(running1Led, OUTPUT);
      pinMode(running2Led, OUTPUT);
      pinMode(doneLed, OUTPUT);
      pinMode(sugarLevelLed, OUTPUT);
    }

    //Ready State

    void readyState(){
      digitalWrite(readyLed, HIGH);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, LOW);
    }

    //Running 1 State

    void running1State(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, HIGH);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, HIGH);
    }

    //Running 2 State
    void running2State(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, HIGH);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, HIGH);
    }

    //Done State
    void doneState(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, HIGH);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, HIGH);
      digitalWrite(motor, LOW);
    }

    //Waiting State
    void waitingState(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, HIGH);
      digitalWrite(sugarLevelLed, LOW);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, LOW);
    }

    //Sugar Level State
    void sugarLevelState(){
      digitalWrite(readyLed, LOW);
      digitalWrite(running1Led, LOW);
      digitalWrite(running2Led, LOW);
      digitalWrite(doneLed, LOW);
      digitalWrite(sugarLevelLed, HIGH);
      digitalWrite(buzzer, LOW);
      digitalWrite(motor, LOW);
    }

    void loop() {
      while(analogRead(A0) > lightSensor){ //when there is no cup placed on the
    sensor, be in ready state
        readyState();
        Serial.println("READY STATE");
      }

    //when the cup is on the sensor and the switch is set to 1 tsp
        for(int time1 = 0; ((time1 < running1Time) &&
                            (analogRead(A0) < cupSensor) &&
                            (digitalRead(measureSwitch) == HIGH)) ; time1++){
        //run the running 1 state for 4 seconds
          running1State();
          delay(1);

          Serial.println("RUNNING STATE 1");
          Serial.println(time1);

      }

        //when the cup is on the sensor and the switch is set to 2 tsp

        for(int time2 = 0; ((time2 < running2Time) && (analogRead(A0) < cupSensor)

    && (digitalRead(measureSwitch) == LOW)); time2++){

    //run the running 2 state for 8 seconds

          running2State();
          delay(1);
          Serial.println("RUNNING STATE 2");
          Serial.println(time2);
          Serial.println(analogRead(A0));

      }

      for(int buzzerTime = 0; buzzerTime < buzzerTimer; buzzerTime++){

        doneState();
        Serial.println("DONE STATE");
        Serial.println(buzzerTime);
        delay(1);
      }

      while(analogRead(A0) < cupSensor){
        waitingState();
        Serial.println("WAITING STATE");
      }

      while(analogRead(A1) > lightSensor){
        sugarLevelState();
        Serial.println("SUGAR LEVEL STATE");
      }
    }

title: The program keeps skipping over the running 1 and 2 states even though the prereqs are met

Answers: 1

body:
Try pulling the output of the light sensor to ground via a 10k resistor, that should calm the values.

Note that you are going to need to completely change the value of the variable `lightSensor`. This is because it will now be outputting different values due to the extra resistor to ground.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/xip2t.png)

<!-- End schematic -->


body:
I am having a problem measuring the voltage with a multimeter. I am not sure if arduino is even sending out a voltage from the Pin.

I will try to create a really basic circuit drawing for reference. (Drawing attached).

[![Basic Ciruit Diagram][1]][1]

What I am trying to do is to measure with a Multimeter the Voltage (or current) across the alligator clips.

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

I will attach the code below:

    //Code Section Start//

    int ledPin = 13;                 // LED connected to digital pin 13

    void setup()
    {
      pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
      delay(10000);                  // waits for a second
    }

    //Code Section End//

Typically the digital write I believe will out put 5 volts and with a 1k Ohm resistor that is only 5mA current. I have heard Arduino can take up to 40mA currents so I don't think I am frying something.

There are two weird things I have noticed. When I try other Pins like "int ledPin = 10;" The green light on the Arduino does not light up. It only lights up when I use pin 13. However, even using Pin 13 or any other pin, I cannot find a voltage or current with the Multimeter. I am using an Arduino Micro.

Can someone please help me identify what I am doing wrong or some method of how to check what is wrong? So that I can have a complete circuit with a voltage I can measure.

title: Arduino DigitalWrite() Super Basic Circuit measure voltage with multimeter

Answers: 3

body:
As you have drawn it, the alligator clips are clamped together (shorted togther).  You reading the voltage "across" a shorted element in the circuit should yield ~0V (shorts by definition have no to very little resistance, meaning there should be no voltage across them).  In order to get your proper voltage reading, you should place the multimeter positive clip above the resistor (where the voltage drop is occuring).

Remember.

Measure current THROUGH.

Measure voltage ACROSS.

p.s. if you're trying to alternate the pin, you should do something like DigitalWrite(pin10, digitalRead(pin10)!=HIGH); (if it's low, then the statement evaluates to true, setting the pin high, if it's high, then the statement evaluates to false, setting the pin low)

body:
As you connected the alligator clips (from the image it seems that they are touching each other) you won't be able to measure anything.

This is how to connect a multimeter to read the current (A) and the voltage (V). You can consider the `+` of E as the pin 13 and the `-` as the ground

 [![][1]][1]

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

Remember that your code will not change the state of pin 13, it will be always high.
If you want to make the signal change try this on your `void loop` :

      digitalWrite(ledPin, HIGH);
      delay(10000);
      digitalWrite(ledPin, LOW);
      delay(10000);

body:
you are telling that you are not getting any current or voltage on your multimeter
right......
i suggest you to use the following code:-

    int ledPin = 13;                 // LED connected to digital pin 13

    void setup()
    {
      pinMode(ledPin, OUTPUT);      // sets the digital pin as output
    }

    void loop()
    {
      digitalWrite(ledPin, HIGH);   // sets the LED on
    }
this will stay your arduino pin 13 always high then you can measure the voltage on that pin........


body:
I would like to get my Arduino to print milliseconds as decimals of seconds.  For example, instead of printing 10456, printing 10.456

I have tried to set a float value or millis, and dividing by 1000 but that gives me a whole number "0" to "1" which is not ideal

The code I use is:

    float ourtime = (millis() / 1000);
    dataFile.print (ourtime);

What would be the easiest, and least taxing (for the processor) way of getting a script to return milliseconds as seconds while taxing the unit as little as possible ?

title: Converting `millis()` to decimal seconds?

Answers: 2

body:
Dividing an integer by an integer (1000) yields an integer, regardless of what you cast that result to.

Instead you need to divide the integer by a float, or cast the integer to a float first. The simplest way is:

    Serial.println(millis() / 1000.0, 3);

The `3` as the second parameter tells `Serial.println()` how many decimal places to print. The `.0` at the end of `1000.0` forces the compiler to see `1000` as a float value (you can also use `1000f` if you prefer).

Since floating point can be quite expensive it's possible to emulate it using integer division and modulus (although they are still quite expensive):

    uint32_t now = millis();
    uint32_t secs = now / 1000;
    uint32_t ms = now % 1000;

    Serial.print(now / 1000);
    Serial.print(".");
    if (ms < 100) Serial.print("0");
    if (ms < 10) Serial.print("0");
    Serial.println(ms);

You could replace the `%` with a x1000 and a subtraction too if you like:

    uint32_t now = millis();
    uint32_t secs = now / 1000;
    uint32_t ms = now - (secs * 1000);

    Serial.print(now / 1000);
    Serial.print(".");
    if (ms < 100) Serial.print("0");
    if (ms < 10) Serial.print("0");
    Serial.println(ms);

A further method would be to first "print" the milliseconds to a string, then split it into two chunks. Print the first chunk, then a decimal point, and finally the second chunk. This avoids the use of any division or multiplication, but does use expensive string operations:

    char num[10];
    snprintf(num, 10, "%lu", millis());
    uint8_t nlen = strlen(num);

    for (uint8_t i = 0; i < nlen - 3; i++) {
        Serial.write(num[i]);
    }
    Serial.write('.');
    for (uint8_t i = nlen-3; i < nlen; i++) {
        Serial.write(num[i]);
    }
    Serial.println();

So really there is no "perfect" method for converting milliseconds into seconds that uses hardly any CPU cycles. All base 10 operations tend to be a bit expensive on a small microcontroller without hardware support for integer MUL/DIV instructions, or a Floating Point Unit.

body:
Division is quite expensive.

Division can be done with subtraction, or shifting - right shift 10 (= /1024) and then compensate for that 24....

You may need too benchmark to see if on your chip this will yield any gaiin.

edit:

I did some quick benchmarking against the brutal force approach by Majenko (division followed by the mod operation), for full range 16-bit types, dividing by 1000, on a PIC16, XC8 free mode:

for 16-bit types
 1. Majenko's approach (1000 divisor + mod): 45.9M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 36.9M ticks;
 3. My approach (1024 divisor, no mod): 20.8M ticks.

[edit 2]for 32-bit types
 1. Majenko's approach (1000 divisor + mod): 101.6M ticks;
 2. revised Majenko's approach (1000 divisor, no mod): 63.0M ticks;
 3. My approach (1024 divisor, no mod): 19.3M ticks.

the same trend applies under the pro mode.

the same trend applies for AVR, with the speed gain being bigger.

edit 2: 32-bit benchmarking added.

I also revised my approach for 32-bit types to speed up the execution a little.

lessons learned:

1) mod ops shall be avoided as much as you can;

2) divisions shall be avoided as much as you can.

3) algorithm rules!

however, be cautious to extrapolate the data here. on a chip with hardware multiplier + divider (STM8, my favorite chip), this trend may not apply and you should benchmark on the target chip to be safe.


body:
I am trying to upload a sketch and getting below error:

    error: failed reading byte
    warning: espcomm_send_command: cant receive slip payload data
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed.

Connections:

    TX - TX
    CH_PD - 3.3 V
    RX - RX
    VCC - 3.3
    GPIO GND
    GND - GND

Before uploading the sketch I have reset the arduino and ESP and selected board as ESP8266 and baud rate as 115200 but still getting the same error.

title: ESP8266 and Arduino integration

Answers: 1

body:
You don't say what you're using to program it (an FTDI board? the USB adapter on an Arduino?) but you probably want to connect

    TX - RX
    RX - TX


body:
I am currently implementing the following setup:

Arduino Mega 2650 -- [DRV8834](https://www.pololu.com/product/2134) -- Stepper motor

Everything works fine, however since it can provide a higher torque I want to run the stepper in half step mode. Each step is triggered by a single pulse coming from the Arduino to the driver. If one uses the Digital Pins for this purpose as done by [AccelStepper](http://www.airspayce.com/mikem/arduino/AccelStepper/), the maximum frequency is around 1000 pps (points per second). This is a third of what I want to achieve. The second option would be to use the PWM of the Arduino which naturally runs at 16 MHz (way to high). There is a way to downgrade this frequency, however the steps are only [discrete](https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM) and not accurate enough for a nice speed control.

Therefore I want to do the following

Arduino Mega 2650 -- Controller -- DRV8834 -- Stepper motor

whereby the Controller is creating a PWM with a frequency (100 to 3000 Hz) depending on some signal coming from the Arduino (I2C, voltage level or something else). I was now searching two days for a component and have no clue what I could use.

How can I create a PWM from 100 to 3000Hz with an arduino?

----------

Edit 1: I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM

    void loop(){
    digitalWrite(pinSTEP, HIGH);
    delayMicroseconds(T/2);
    digitalWrite(pinSTEP, LOW);
    delayMicroseconds(T/2);
    }

where T = 1 / f is not feasible since I have to read out a sensor in the loop which destroys the motor timing.

----------

Edit 2: There is a method to change the register of the timers. One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM. However with only seven discrete steps this leads to the following freuquencies:

    prescalar = 1 ---> PWM frequency is 31000 Hz
    prescalar = 2 ---> PWM frequency is 4000 Hz
    prescalar = 3 ---> PWM frequency is 490 Hz (default value)
    prescalar = 4 ---> PWM frequency is 120 Hz
    prescalar = 5 ---> PWM frequency is 30 Hz
    prescalar = 6 ---> PWM frequency is <20 Hz

which is not sufficient for my application.

For more about this method:

 - http://usethearduino.blogspot.ch/2008/11/changing-pwm-frequency-on-arduino.html
 - http://forum.arduino.cc/index.php?topic=72092.0

----------

Sometimes a solution is so easy that it hurts ;) Based on the input of this wonderful community I found my solution. Code:

    #include <TimerThree.h>
    // TimerThree PWM Pins 2, 3, 5

    #define pinPWM       2
    #define pinM0        22
    #define pinM1        24
    #define pinSleepnot  28
    #define pinDir       30

    void setup(void){

      // Define output pins
      pinMode(pinM0, OUTPUT);
      digitalWrite(pinM0, HIGH);
      pinMode(pinM1, OUTPUT);
      digitalWrite(pinM1, LOW);
      pinMode(pinSleepnot, OUTPUT);
      digitalWrite(pinSleepnot, HIGH);
      pinMode(pinDir, OUTPUT);

      // Initialize serial communication
      Serial.begin(9600);

    }

    void loop(void){

      for (float frequency = 500; frequency < 3000; frequency = frequency + 1) {
        float T = 1 / frequency * 1000000;
        Serial.print("Frequency: ");
        Serial.println(frequency);
        Timer3.initialize(T);
        Timer3.pwm(pinPWM, 100);
        delay(5);
      }
    }

title: Contoller for a stepper motor

Answers: 3

body:
> the maximum frequency is around 1000 pps

Arduino pin operations takes about 100 ticks. Or 400 ticks for four pins. No more than another 100 ticks for processing and logic ops. So I would expect 500 ticks or 30k on a 16mhz Arduino.

Much faster if you use direct pin ops.

So maybe the code you used isn't well written or your Arduino is doing lots of other things?

edit:

> I found my solution. Code:

there is no reason for you to repeatedly initialize the module. this thing is simple, and others have laid out the thought process for you. write a set of routines that spin the motor - spin it left, spin it right. and then call those routines in a timer isr. nothing fancy here.

body: You might need to move away from the AccelStepper library, and 'roll your own', but as others have pointed out, the MCU certainly has the bandwidth to do this directly.  I understand that PWM resolution may not give smooth ramping, but I would probably look into using a timer interrupt.  The timer ISR would count steps and you would only need to adjust the timer compare register to change the step frequency.

body:
> How can I create a PWM from 100 to 3000Hz with an arduino?

Your question is really "How can I create a PWM from 100 to 3000Hz with an Atmega2560"?

The Atmega has various timers which can be configured in many ways. You can alter the prescaler (ratio of processor clocks to timer ticks) and the amount it counts up to. Certainly you can change the frequency and duty cycle.

I have a [page about timers](http://www.gammon.com.au/timers) which may help you.

---

> I have to read out sensors while the motor is running. Therefore, the so called "bit banging" PWM ... is not feasible

Yes, don't do "bit banging" when you have 5 hardware timers.

---

> One can adapt a so called prescalar values (from 0 to 7) which will define the frequency of our PWM.

Adapt the prescaler **and** the timer configuration. Between them you have very fine control.


body:
I have a problem with the shift register 74HC595.

The sketch I use is able to enable a specific led (8 are connected).

When I enable led 0 to 7 it behaves like normally (they switch on when I enter the numbers).

However, for the led connected to pin 15 (other side of the ic, see [layout][1]) it behaves differently.
 When I switch this led on, ALL leds go off. When I retry, nothing happens. When I enable another led, after a short time (but can be seconds) the led for pin 15 is emitting light together with all others which where already enabled.

This seems like a malfunction in the IC (I checked already another led, another cable, another resistor). The only think I haven't checked is moving the IC to another position of the breadboard (that would take a lot of time since I have to rewrite everything). Is it possible I missed something or is the shift register broken?

The code to switch on a led:

    void updateShiftRegister()
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, LSBFIRST, leds);
      digitalWrite(latchPin, HIGH);
    }

where leds are the indices of the leds (0..7).

  [1]: http://2.bp.blogspot.com/-cIb_uYGrRk4/U1fxdfGhy-I/AAAAAAAAADg/kcuUjMcpzD0/s1600/Region+Capture.png

title: Problem with shift register

Answers: 1

body:
You cannot directly give an index (0..7) to a shift register if you want the index to represent the LED number to be switched on.
You have to build a table similar to the following:

    byte led[8] = {
    0b00000001,
    0b00000010,
    0b00000100,
    0b00001000,
    0b00010000,
    0b00100000,
    0b01000000,
    0b10000000
    };

and later . . .

    shiftOut(dataPin, clockPin, LSBFIRST, led[leds]);

where leds is a number 0..7


body:
I am writing a timer function that uses the micros() function which generates a unsigned long value.  To compensate for a roll over condition, I would like to use the maximum value for that variable type.  I have a number, 4,294,967,295, but was expecting that to be a constant somewhere.

Is there a MAX_UNSIGNED_LONG constant in the Arduino compiler files somewhere?

I have tried that name and know it probably isn't that.  Still poking around.

title: Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?

Answers: 3

body:
Various `limits.h` files in the `avr-gcc` hierarchy define `ULONG_MAX`, which may be the value you want.  For example, on my system such files have paths ending with `hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h` or with `hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h` and contain definitions like the following.

    /* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
    #undef ULONG_MAX
    #define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, `LONG_MAX` also is defined in `limits.h`.

Note, arithmetic done in a form like

    timeDelta = micros() - prevTime;

will be correct (regardless of whether `micros()` overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.

body:
You don't need "to compensate for a roll over condition".

See my answer: https://arduino.stackexchange.com/a/33577/10794

---

> in an Arduino compiler?

The "Arduino" compiler is a C++ compiler. That is the starting point for most questions. If you Google for:

    maximum unsigned long in c++

You will find the first link leads to:

http://www.cplusplus.com/reference/climits/

In that it says:

    ULONG_MAX Maximum value for an object of type unsigned long int

body:
Did you try to do this?:

    unsigned long maxUnsignedLong = 0UL - 1UL;

or:

    const unsigned long ULONG_MAX = 0UL - 1UL;


body:
I encountered a strange behavior while running 2 way transmission tests  between 2 Arduino Zero (ATSAMD21G), one master and one slave. Wrong data is being continuously transferred both ways. The expected data is also being transferred in between. I have to filter out the received data to catch it (line 41 in Master's code and 33 in slave).

I'm using the stock wire libraries (being different for the 2 boards), along with Nick Gammon's "I2C_readAnything".

[Master's code][1]

[Slave's code][2]

I think this continuous flow doesn't allow the bus to be released. It might be what's making it impossible to communicate with a second master (and maybe causing my [previous problem][3])

I also tried my code between a Mega 2560 (slave) and a Zero (master). Fake data is, this time, only being sent one way (from the Zero to the Mega only).

Is there some specific code to add to send data properly from ATSAMD boards? Is it a bug in the SAMD Wire library?

I also had to add a 1ms delay after sending data from the Master. It wouldn't go through otherwise. Shouldn't it be handled by the ATSAMD or the Wire library?

  [1]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/master/Master_test_i2c_data/Master_test_i2c_data.ino
  [2]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/master/Slave_test_i2c_data/Slave_test_i2c_data.ino
  [3]: https://arduino.stackexchange.com/questions/34944/two-way-communication-on-multimaster-i2c-bus

title: Arduino Zero (ATSAMD21G) - I2C - continuous wrong data flow

Answers: 2

body:
Start with a single byte, with a very small sketch, with both the Master and the Slave at 100kHz. When that is working 100% reliable, then you can try to transfer a struct.

The Slave RequestEvent function should always return valid data, not once every two seconds. The global variables that are used in receiveEvent or requestEvent **and** in the loop() should be made 'volatile'. Disable the interrupts in the loop() when reading or writing the global volatile struct.

With your sketch, you have to open the serial monitor for both the Master and Slave.

You could add more tests, for example testing the return value of Wire.endTransmissing, testing the 'howMany' parameter, testing the actual number that Wire.request returns.

body:
The code had several issues.

`receiveEvent`, on the slave side, contained a `millis` `if` condition timer that made it time out. I moved the timer to the master side before calling `Wire.requestFrom`.

`receiveEvent`, on the slave side, was also confusing real data with incoming `requestEvent`. I added an `if` statement to compare the `receiveEvent` data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the `Wire` library)

I set the global variables used in events as `volatile`. The code is working too without this tho.

[fixed Master code][1]

[fixed Slave code][2]

[1]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/f781617142bd0198ea9d41a78125e3cb52f5399c/Master_test_i2c_data/Master_test_i2c_data.ino
[2]: https://github.com/kb-/Arduino-I2C-2way-anydata/blob/f781617142bd0198ea9d41a78125e3cb52f5399c/Slave_test_i2c_data/Slave_test_i2c_data.ino


body:
I am currently using a Particle Photon to control a relay that turns a lamp on and off. I would like to power the Photon and the lamp from the same power cord.

Currently, I have a power cord for the lamp and I am also using a usb cable to power the Photon.

I found [this (Enclosed AC DC Converter)][1] and I am wondering if this will work if I split the 120V power cord to go to the relay and the converter. Will I need anything else? Are there any other concerns I should worry about? Do I need to worry about polarity?

Thanks for your help in advance.

  [1]: https://www.digikey.com/product-detail/en/rohm-semiconductor/BP5038A1/BP5038A1-ND/756609

title: Right way to convert 120VAC to 5V?

Answers: 1

body:
I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.

**Short Answer, No**

If you read the [datasheet for the Particle Photon][1], it recommends no less than a 1A power supply. Unfortunately, the [datasheet for the AC/DC Converter][2] you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.

**How to Make This Work**

Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!

Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like [this one][3] may be right for you (not to plug for Adafruit, though they are a great learning resource).

Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.

**Bonus Points**

You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.

EDIT:

**Easiest Solution**
Just install one of [these][4] at the receptacle you intend to use.

  [1]: https://docs.particle.io/datasheets/photon-datasheet/
  [2]: http://rohmfs.rohm.com/en/products/databook/datasheet/module/power_module/acdc_converter/bp5038a1.pdf
  [3]: https://www.adafruit.com/products/501?gclid=Cj0KEQiA0L_FBRDMmaCTw5nxm-ABEiQABn-VqbbpG3K3rVPtn01mbKr3J9tlkb8CP5K8yCYrUjuRFNMaAv_T8P8HAQ
  [4]: https://images-na.ssl-images-amazon.com/images/G/01/aplusautomation/vendorimages/bf5475b0-12da-4b13-a9e2-94a9fc27e1ce.jpg._CB311932683__SL300__.jpg


body:
I am fairly new to Arduino. I was working on a project where I use a GSM SIM900a modem interfaced with an Arduino. The AT commands are sent via the Arduino to the GSM Modem. The problem, however, is that the commands are only sent when I open the Serial Monitor. I have an IR proximity sensor and I would like the AT commands to be sent when the sensor detects an object. I am putting the code for the GSM modem below (I have not yet put in the code for the IR sensor).I want to know how to send the AT commands when the Arduino is hooked up to a battery and not to a PC

    #include <SoftwareSerial.h>
    SoftwareSerial myGsm(7,8);
    float temp;
    int tempPin = 0;
    void setup()
    {
     myGsm.begin(9600);
     Serial.begin(9600);
     delay(500);

    myGsm.println("AT+CIPSHUT");
     delay(1000);
     printSerialData();

     myGsm.println("AT+CIPMUX=0");
     delay(2000);
     printSerialData();

     myGsm.println("AT+CGATT=1");
     delay(1000);
     printSerialData();

     myGsm.println("AT+CSTT=\"bsnlnet\",\"\",\"\"");//setting the APN,2nd parameter empty works for all networks
     delay(5000);
     printSerialData();

     myGsm.println();
     myGsm.println("AT+CIICR");
     delay(6000);
     printSerialData();

     myGsm.println("AT+CIFSR"); //init the HTTP request
     delay(2000);
     printSerialData();

     myGsm.println("AT+CIPSTART=\"TCP\",\"122.178.80.228\",\"350\"");
     delay(5000);
     printSerialData();
     delay(5000);

     myGsm.println("AT+CIPSEND");
     delay(2000);
     printSerialData();

    sendtemp();
    delay(3000);
    myGsm.println("AT+CIPCLOSE");
    printSerialData();

    myGsm.println("AT+CIPSHUT");
    delay(1000);
    printSerialData();
    }

    void loop()
    {
    }

    void printSerialData()
    {
     while(myGsm.available()!=0)
     Serial.write(myGsm.read());
    }

    void sendtemp()
    {
      temp = analogRead(tempPin);
      temp = temp * 0.48828125;
      Serial.print("TEMPERATURE = ");
      Serial.print(temp);
      Serial.print("*C");
      Serial.println();
      delay(5000);
     myGsm.println(temp);
     delay(3000);
     printSerialData();
     myGsm.write(0x1A);
     delay(3000);
       printSerialData();

    }

title: How to communicate with GPS SIM900a without Serial Monitor

Answers: 1

body: Well, I too had the same problem until now. The simple way to fix is just to delay the void setup() before Serial communication begins. Add delay(15000); //15 Seconds so that GSM module boots up and connects to the network. And there is no need of changing any part of code. Hope this helps someone out there like me. :)


body:
I am new to ESP programming on Arduino, as before I was developing on eLua. There were some memory problems in Lua, so I decided to move to Arduino.

After looking at some examples, I found a library called AsyncTCP and I was very glad because it provides callbacks for events just like Lua. But I was very disappointed when I found no example of an async TCP server. Instead there is an AsyncWeb Server but I don't want to use an HTTP server: I want a simple telnet server. Does someone have a working example?

title: ESP8266 ASyncTCP class example

Answers: 2

body:
If there are no examples provided with the library then you will have to make do with the example you have :(

If you think about what a web server does it is really just a glorified Telnet server without proper security.  When the web server comes up it creates a waiting socket on port 80, you want port ?? (too long ago).  It sits there waiting for text messages from clients, which is what you want to do.  Every time it receives a message it sends it to a handler.

I don't know how experienced a programmer you are, but you should be able to pick up enough from the webserver code to write your own telnet server.  However with you being new to Arduino you may be much better doing it as a synchronous application to start with.

Another approach is to find a the source for a telnet server and see if you can port that to the ESP.

body:
There are examples in the ESP8266 library

https://github.com/me-no-dev/ESPAsyncTCP/tree/master/examples


body:
The error message, generated from Sublime, in its entirety...

 Compiling KCT_Swimv4l...

 Creating C:\Users\ken\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...

 '"avr-g++"' is not recognized as an internal or external command,
operable program or batch file.

 [Stino - Error 1]
__________
This is initial install of "Arduino-like IDE".

I used the following installation procedure:

   - Install Sublime Text 3
   - From Sublime, View --> Show Console
   - From a web browser, open  https://sublime.wbond.net/installation and choose Sublime Text 3 version.
   - Copy the code there to the Sublime-Console and press enter.
   - From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
   - Enter "Arduino" and choose "Arduino-like IDE"
   - from Arduino --> Preferences --> Select Arduino Application Folder.

Same problem with any sketch.

System Configuration:

-Windows 10 x64, current level
-Sublime Text 3 x64, build 3126
-Arduino IDE 1.8.0

github info on Stino was not helpful.
Has anyone encountered this problem and found a solution for it?
If not, I can open an issue there.
___________________________________________

I have now done the following:
Uninstalled Sublime
Searched System drive and removed any remaining Sublime content
Searched System drive and removed any Stino content
Download WinAVR from http://winavr.sourceforge.net/download.html, selecting PATH option
Reinstalled Sublime Text 3 x64
Close & Reopen Sublime
From Sublime, View --> Show Console
From web browser, open https://sublime.wbond.net/installation and choose Sublime Text 3 version.
Copy the code there to the Sublime-Console and press enter
Close & Reopen Sublime
From Sublime, CTRL + Shift + P --> Type "Install" and choose "Install package"
Enter "Arduino" and choose "Arduino-like IDE"
Close & Reopen Sublime
From Arduino --> Preferences --> Select Arduino Application Folder

On Compile, error msg is now different:
  Compiling KCT_Swimv4l...
  Creating C:\Users\kct\Documents\Arduino_Build\KCT_Swimv4l\KCT_Swimv4l.ino.cpp.o...
  cc1plus.exe: error: unrecognized command line option "-std=gnu++11"
  cc1plus.exe: error: unrecognized command line option "-flto"
  [Stino - Error 1]

title: Sublime as external editor, error on Arduino compile dropdown: "avr-g++ is not recognized...", from Stino

Answers: 1

body:
Download WinAVR from http://winavr.sourceforge.net/download.html, install it, add(in my case, its: C:\WinAVR-20100110\bin) to PATH variable of your system(If it was left unchecked while installing), And then try to build. I hope your problem will be solved.

**Update**

I have installed the latest version and found no board selection option. If you want to use it, you can download an older version. from here: https://drive.google.com/file/d/0B4zy7eqONHnuajk2aXlzOTJtaDQ/view it works on older version of arduino(probably 1.5 series)


body:
I've seen some similar questions here for using MOSFET to control 12V LEDs
But apparently the only MOSFET currently available to us is a 2-MOSFET high power trigger module, details in the link below.

https://www.elecrow.com/high-power-mosfet-trigger-switch-drive-module.html

How do we connect this to the Arduino to send the PWM trigger (I get confused by the three holes) and how do we connect the DC power to this??? I get confused with the power connections.

title: Using a MOSFET module to control DC LED PWM

Answers: 2

body:
it seems to be a typical low-side switch (dual switches). the load goes into DC+ and DC- --> ask the manufactuer to be sure.

whether it works for you will depend on the load, driving signal and the mosfet used -> you should ask the seller for a schematic, or buy one and reverse engineer it.

body:
The three TRIG/PWM pins are connected to the same electrical point. The same goes for the three GND pins.

You can either solder:

1. A **2-pin 0.2 inch screw terminal** (the very same kind of those blue connectors already in the board) to the pair of big holes closer to the edge, or
2. A **2-pin 0.1 inch header** to the 2 holes in the centre of the 4-hole row (the smaller ones).
[![2-pin header][1]][1]

These will be the control input you should be connecting your Arduino to.

The DC power supply for the load that will be switched by the MOSFETS has to be connected between the VIN+ and VIN- terminals. Note that VIN- is connected internally to GND.

Your load has to be connected between the OUT+ and OUT- terminals.

That's all you need to know. In case you're in doubt, I've drawn this schematic for you (see below)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/J7Otl.png)

<!-- End schematic -->

**IMPORTANT ADDITIONAL NOTES:**

 1. **No flyback diodes are present in the board**. If you try to switch an inductive load (a motor, a solenoid, etc.) with this board you have a high risk of damaging the MOSFETs and rend it useless.

 2. **You need at least a 5V control signal** for switching high current loads with this board. Although a 3.3V control may seem able to switch the MOSFET, its internal RdsON at 3.3V could easily be high enough to produce excessive power dissipation and blow up the MOSFET. See these curves from the [AOD4184 datasheet][2]:

[![ON-region characteristics][4]][4]
[![ON-resistance vs. Vgs][5]][5]

  [1]: https://i.stack.imgur.com/dmKu0m.jpg
  [2]: http://www.aosmd.com/pdfs/datasheet/AOI4184.pdf
  [4]: https://i.stack.imgur.com/3L1SOm.png
  [5]: https://i.stack.imgur.com/j4Zl0m.png


body:
I am currently working with two Arduinos and I'm trying to synchronize them. I want to get data from four LIS3DH accelerometers. The LIS3DH accelerometers are connected to the Arduino using I2C interface. I have managed to get the Arduinos to synchronize using SPI but when I get the third set of data it keeps on showing OVF rather than the values. My code is below can someone please help me out?

Thanks

    // SPI Master
    #include <Wire.h>
    #include <SPI.h>
    #include "SPI_anything.h"
    #include <Adafruit_LIS3DH.h>
    #include <Adafruit_Sensor.h>

    //#define LIS3DH_CLK 13
    //#define LIS3DH_MISO 12
    //#define LIS3DH_MOSI 11
    //#define LIS3DH_CS  10

    // I2C
    Adafruit_LIS3DH lisch1 = Adafruit_LIS3DH();
    Adafruit_LIS3DH lisch2 = Adafruit_LIS3DH();
    // Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();
    struct event3;

    #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

    void setup() {
    #ifndef ESP8266
      while (!Serial)
        ; // will pause Zero, Leonardo, etc until serial console opens
    #endif

      Serial.begin(9600);

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);

      // turn on SPI in slave mode
      SPCR |= _BV(SPE);

      Serial.println("LIS3DH test!");

      if (!lisch1.begin(0x19)) { // change this to 0x19 for alternative i2c address
                                 // - Voltage SDO

        Serial.println("Couldnt start");
        while (1)
          ;
      }
      Serial.println("LIS3DH1 found!");
      if (!lisch2.begin(0x18)) { // change this to 0x18 for alternative i2c address
                                 // - Ground SDO
        Serial.println("Couldnt start");
        while (1)
          ;
      }
      Serial.println("LIS3DH2 found!");

      lisch1.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!
      lisch2.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

      Serial.print("Range = ");
      Serial.print(2 << lisch1.getRange());
      Serial.print("Range = ");
      Serial.print(2 << lisch2.getRange());
      Serial.println("G");
    }

    void loop() {

      lisch1.read(); // get X Y and Z data at once

      /* Or....get a new sensor event, normalized */
      sensors_event_t event;

      lisch1.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print(" \t ");
      Serial.print(event.acceleration.x);
      Serial.print(" \t ");
      Serial.print(event.acceleration.y);
      Serial.print(" \t ");
      Serial.print(event.acceleration.z);

      lisch2.read(); // get X Y and Z data at once
      lisch2.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print(" \t ");
      Serial.print(event.acceleration.x);
      Serial.print(" \t ");
      Serial.print(event.acceleration.y);
      Serial.print(" \t ");
      Serial.print(event.acceleration.z);

      struct event;

      SPI_readAnything(event);
      //  sensors_event_t event;

      //  lisch3.getEvent(&event);
      Serial.print(" \t "); Serial.print(float2s(event.acceleration.x,6);
      Serial.print(" \t "); Serial.print(event.acceleration.y);
      Serial.print(" \t "); Serial.print(event.acceleration.z);
      Serial.println ();

      delay(500);
    }

    / SPI Slave

    #include <Wire.h>
    #include <SPI.h>
    #include "SPI_anything.h"
    #include <Adafruit_LIS3DH.h>
    #include <Adafruit_Sensor.h>

    #define LIS3DH_CLK 13
    #define LIS3DH_MISO 12
    #define LIS3DH_MOSI 11
    #define LIS3DH_CS 10

        // I2C
        Adafruit_LIS3DH lisch3 = Adafruit_LIS3DH();

    #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

    void setup() {
    #ifndef ESP8266
      while (!Serial)
        ; // will pause Zero, Leonardo, etc until serial console opens
    #endif

      Serial.begin(9600); // start serial for output

      SPI.begin();

      // Slow down the master a bit
      SPI.setClockDivider(SPI_CLOCK_DIV8);

      Serial.println("LIS3DH3 test!");

      if (!lisch3.begin(0x19)) { // change this to 0x19 for alternative i2c address
                                 // - Voltage SDO

        Serial.println("Couldnt start");
        while (1)
          ;
      }
      Serial.println("LIS3DH3 found!");

      lisch3.setRange(LIS3DH_RANGE_16_G); // 2, 4, 8 or 16 G!

      Serial.print("Range = ");
      Serial.print(2 << lisch3.getRange());

      Serial.println("G");
    }

    void loop() {

      lisch3.read(); // get X Y and Z data at once

      /* Or....get a new sensor event, normalized */
      sensors_event_t event;

      lisch3.getEvent(&event);

      /* Display the results (acceleration is measured in m/s^2) */
      Serial.print(" \t ");
      Serial.print(event.acceleration.x);
      Serial.print(" \t ");
      Serial.print(event.acceleration.y);
      Serial.print(" \t ");
      Serial.print(event.acceleration.z);
      Serial.println();

      digitalWrite(SS, LOW); // SS is pin 10
      SPI_writeAnything(event);
      digitalWrite(SS, HIGH);
      //  delay (1000);  // for testing

      delay(100);
    }

title: OVF in serial monitor instead of data

Answers: 1

body: OVF means overflow, you probably exceeded the range of the data type you're using. Try /1000; /10000000000 etc to your variable until you don't get the OVF or use a datatype with a bigger range.


body:
I'm successfully running AT commands via the Serial Monitor. But now I'm issuing AT commands via Arduino code and facing problems getting the correct response.

**Goal:** After issuing AT commands programatically, knowing whether these run successfully or not.

**Microcontroller:** Arduino Uno

    #include<string.h>
    #include<SoftwareSerial.h>

    #define OK "OK"
    #define SERVER_PORT 1234
    #define RX_PIN 2
    #define TX_PIN 3

    SoftwareSerial ESP(RX_PIN, TX_PIN);

    void setup() {
      Serial.begin(115200);
      Serial.println("First serial");
      while(!Serial);
      ESP.begin(115200);
      Serial.println("Second serial");
      while(!ESP);
      //Enabling multiple connections
      ESP.println("AT+CIPMUX=1\r\n");
      while (!ESP.available());
      String muxResponse = ESP.readString();
      Serial.print("muxR:");
      Serial.println(muxResponse);
    }

    void loop() {
      if (ESP.available()) {
        String val = ESP.readString();
        Serial.println(val);
      }
    }

After running the above code I get the response in the Serial Monitor like:

    muxR:AT+CIPMUX=1

    busy p../

    OK

I'm getting special characters too.

title: How to get response of issued AT command for ES266 on Arduino programatically?

Answers: 1

body:
change

    AT+CIPMUX=1\r\n

to

    AT+CIPMUX=1


body:
I want to turn my ESP8266 into an access point so that I can connect directly to it.

I use the following sketch, but when I select
GENERIC module ESP8266 from menu, the libraries `ESP8266WiFi.h` and `ESP8266WebServer.h` become available but I was unable to upload the sketch.

Also when I select board as Arduino Uno (Which i have really) and then what to upload then the above two files becomes unavailable and says fatal error no such file... no idea what to do next.

    #include <ESP8266wifi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include<WiFi.h>
    #include<SoftwareSerial.h>
    SoftwareSerial esp(2,3);
    IPAddress local_IP(192,168,4,22);
    IPAddress gateway(192,168,4,9);
    IPAddress subnet(255,255,255,0);
     String ssid="Wisal";
     String pass="12345678";
     ESP8266WebServer server(80);
     boolean isAccessPointCreated=false;
    void setup(){
      esp.begin(115200);
      Serial.begin(115200);

      WiFi.mode(WIFI_AP);
      Serial.print("Setting soft-AP configuration ... ");
      Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");

      Serial.print("Setting soft-AP ... ");
      Serial.println(WiFi.softAP("ESPsoftAP_01") ? "Ready" : "Failed!");
      Serial.print("Soft-AP IP address = ");
      Serial.println(WiFi.softAPIP());

    }

    void loop(){
      while(esp.available()>0){
        char a = esp.read();
          if(a == '\0')
            continue;
          if(a != '\r' && a != '\n' && (a < 32))
            continue;
          Serial.print(a);
       }
    }

title: fatal error ESP8266WiFi.h: No such file or directory

Answers: 3

body:
The [ESP8266 core for Arduino](https://github.com/esp8266/Arduino) that you're trying to use is for programming ESP8266 directly. You are trying to program an Uno with an ESP8266 connected to it for use as a WiFi module. For that application the ESP8266 core is of no use. For your application it's most common to run the AT firmware on the ESP8266 and communicate via serial. If you're doing that I recommend the WiFiEsp library:

https://github.com/bportaluri/WiFiEsp

Since you're uploading to the Uno you should have Arduino/Genuino Uno selected in the **Tools > Board** menu.

body:
There are two ways to use an ESP8266.

Method 1

You seem to say you are using it as a slave to your UNO.  You program you Uno from the IDE.  The program will have code in it to send 'AT' commands to the ESP and this will make the ESP handle all the WIFI stuff.

Method 2

You remove you Uno and use the ESP as the main processor.  This means you get to program the ESP with C++ like code through the IDE, just as if it was an UNO.  HOWEVER you will need to install the ESP package from the board manager and there are certain limitations.  You also have access to less IO ports, but you can connect the Uno (over serial or I2C) and use it as a slave (which you program through the IDE separately).

body: You have imported `ESP8266wifi.h` and not `ESP8266WiFi.h`


body:
I am trying to implement arduino101 and my application needs to read data from the Arduino without a USB connection to my laptop. I appreciate you if you know any beginner-level tutorial for this.

Please let me know if you can't understand my question.

title: Any resources you know with regards to remotely reading data from arduino?

Answers: 1

body:
You can use the Bluetooth on the board, a Bluetooth dongle for your laptop if the laptop does not have bluetooth or you can buy a wifi shield.

The 101 has Bluetooth LE on the board.

You will find there is a Bluetooth -> Serial USB software, so the application on the laptop can still work the same way as when using the usb.

Here are the Bluetooth examples for the 101 on arduino.cc

https://www.arduino.cc/en/Reference/CurieBLE

and the user guide for the 101

https://www.arduino.cc/en/Guide/Arduino101


body: What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

title: Max current of Vin and 5V pin on Arduino Nano

Answers: 2

body:
It's hard to say. The maximum [the on-board regulator](http://www.ti.com/lit/ds/symlink/lm1117.pdf) can provide is 800mA. However the actual amount it can provide at any time depends on other external factors - most notably:

* The voltage of your supply
* The ambient temperature around the board
* The thermal mass of the copper the tab is soldered to

The higher your input voltage the more excess voltage has to be converted to heat. When it gets too hot it overheats and (theoretically) shuts down.

Also the board itself will take some of the maximum 800mA quota, say 50mA (guestimate), so that leaves 750mA theoretical maximum for the 5V pin - but only when powered from not much more than 6.2V (5V + 1.2V regulator dropout voltage).

However, if you are powering from the USB port then it is limited to whatever the USB port can provide (100mA for a passive hub, 500mA for a normal USB port, 2A for a CDP).

The VIN current will be the same as the 5V pin current + the board current.

body:
> What is the max current of the Arduino Nano's Vin (30) and 5V (27) pins?

it depends on the power dissipation limits (and to a less extent the current limit) on the regulator. the power dissipation is determined by the load your arduino and its loads draw, and the voltage dropout on the regulator.

the other part of the thermal limit is the thermal resistance of the package and ambient temperature.

Most of them use el cheapo 1117 regulators in sot223 that has a limit of 1amp + a thermal limit of 100c/w. so max power dissipation should be less than 1w. That means a practical limit of 0.5amp under the most aggressive conditions (2v dropout, or 7v input).

at 9v input, max of 0.25amp.
at 12v input, a max of 0.15amp.
...


body:
I am working through [this tutorial](https://www.allaboutcircuits.com/projects/introduction-to-the-rfm69hw-transceiver/) on using the RF69HW. The RF69HW datasheet can be found [here](http://www.hoperf.com/upload/rf/RFM69W-V1.3.pdf). I am using an Eegoo Uno R3 and yes I am aware that the Arduino is a 5v and the RF69HW is a 3.3v board. I am using some voltage dividers to get the voltage to 3.3v [via the circuit shown below, at end of question](https://i.stack.imgur.com/sreQq.png).

I would use a level shifter but I only realized this mistake today and I am trying to get this working ASAP. The radio does not appear to be working. In fact the program seems to get caught on it. I introduced:

    radio.sendACK();
    Serial.print(" - ACK sent");

After the button has been pressed. This is the output I get:

    Listening at 915 Mhz...
    Button pressed!

So it gets to the line before it where the button is pressed but then gets stuck attempting to sendACK. I don't know what to make of this. Any help getting these two to communicate is appreciated. Code and pictures below.

 Here is the code I am using as the sender:

    #include <SPIFlash.h>
    #include <SPI.h>
    #include <LowPower.h>
    #include <RFM69.h>
    #include <RFM69_ATC.h>
    #include <RFM69_OTA.h>
    #include <RFM69registers.h>

    //*********************************************************************************************
    // *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
    //*********************************************************
    //This part of the code simply sets up the parameters we want the chip to use
    // these parameters allow you to have multiple networks, channels, and encryption keys
    #define NETWORKID     100  //the same on all nodes that talk to each other
    #define RECEIVER      1    //unique ID of the gateway/receiver
    #define SENDER        2    // you could for example, have multiple senders
    #define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
    //Select your frequency by uncommenting
    #define FREQUENCY     RF69_915MHZ
    #define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
    #define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
    //*********************************************************************************************
    #define SERIAL_BAUD   9600

    //This part defines the LED pin and button pin
    #define LED             9 //LED on D9
    #define BUTTON_INT      1 //user button on interrupt 1 (D3)
    #define BUTTON_PIN      3 //user button on interrupt 1 (D3)
    #define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

    RFM69 radio;

    // the setup contains the start-up procedure and some useful serial data
    void setup() {
      Serial.begin(SERIAL_BAUD);
      radio.initialize(FREQUENCY,NODEID,NETWORKID);
    #ifdef IS_RFM69HW
      radio.setHighPower(); //only for RFM69HW!
    #endif
      radio.encrypt(ENCRYPTKEY);
      char buff[50];
      sprintf(buff, "\nListening at %d Mhz...", FREQUENCY==RF69_433MHZ ? 433 : FREQUENCY==RF69_868MHZ ? 868 : 915);
      Serial.println(buff);
      Serial.flush();
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      pinMode(LED, OUTPUT);
      attachInterrupt(BUTTON_INT, handleButton, FALLING);
      pinMode(RX_TOGGLE_PIN, OUTPUT);
    }

    //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
    #define FLAG_INTERRUPT 0x01
    volatile int mainEventFlags = 0;
    boolean buttonPressed = false;
    void handleButton() {
      mainEventFlags |= FLAG_INTERRUPT;
    }

    byte LEDSTATE=LOW; //LOW=0

    void loop() {
      //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
      if (mainEventFlags & FLAG_INTERRUPT) {
        LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
        mainEventFlags &= ~FLAG_INTERRUPT;
        if (!digitalRead(BUTTON_PIN)) {
          buttonPressed=true;
        }
      }
      if (buttonPressed) {
        Serial.println("Button pressed!");
        buttonPressed = false;
        radio.sendACK();
        Serial.print(" - ACK sent");
        if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
          delay(100);
      }
      //check if something was received (could be an interrupt from the radio)
      if (radio.receiveDone()) {
        //print message received to serial
        Serial.print('[');Serial.print(radio.SENDERID);Serial.print("] ");
        Serial.print((char*)radio.DATA);
        Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
        Serial.println();
        if(LEDSTATE==LOW) LEDSTATE=HIGH;
        else LEDSTATE=LOW;
        digitalWrite(LED, LEDSTATE);
        digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
        //check if sender wanted an ACK
        if (radio.ACKRequested()) {
          radio.sendACK();
          Serial.print(" - ACK sent");
        }
      }
      radio.receiveDone(); //put radio in RX mode
      Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
    }

And the receiver:

    #include <SPIFlash.h>
    #include <SPI.h>
    #include <LowPower.h>
    #include <RFM69.h>
    #include <RFM69_ATC.h>
    #include <RFM69_OTA.h>
    #include <RFM69registers.h>

    //*********************************************************************************************
    // *********** IMPORTANT SETTINGS - YOU MUST CHANGE/CONFIGURE TO FIT YOUR HARDWARE *************
    //*********************************************************
    //This part of the code simply sets up the parameters we want the chip to use
    // these parameters allow you to have multiple networks, channels, and encryption keys
    #define NETWORKID     100  //the same on all nodes that talk to each other
    #define RECEIVER      1    //unique ID of the gateway/receiver
    #define SENDER        2    // you could for example, have multiple senders
    #define NODEID        SENDER  //change to "SENDER" if this is the sender node (the one with the button)
    //Select your frequency by uncommenting
    #define FREQUENCY     RF69_915MHZ
    #define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
    #define IS_RFM69HW    //uncomment only for RFM69HW! Remove/comment if you have RFM69W!
    //*********************************************************************************************
    #define SERIAL_BAUD   9600

    //This part defines the LED pin and button pin
    #define LED             9 //LED on D9
    #define BUTTON_INT      1 //user button on interrupt 1 (D3)
    #define BUTTON_PIN      3 //user button on interrupt 1 (D3)
    #define RX_TOGGLE_PIN   7 //GPIO to toggle on the RECEIVER

    RFM69 radio;

    // the setup contains the start-up procedure and some useful serial data
    void setup() {
      Serial.begin(SERIAL_BAUD);
      radio.initialize(FREQUENCY, NODEID, NETWORKID);
    #ifdef IS_RFM69HW
      radio.setHighPower(); //only for RFM69HW!
    #endif
      radio.encrypt(ENCRYPTKEY);
      char buff[50];
      sprintf(buff, "\nListening at %d Mhz...", FREQUENCY == RF69_433MHZ ? 433 : FREQUENCY == RF69_868MHZ ? 868 : 915);
      Serial.println(buff);
      Serial.flush();
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      pinMode(LED, OUTPUT);
      attachInterrupt(BUTTON_INT, handleButton, FALLING);
      pinMode(RX_TOGGLE_PIN, OUTPUT);
    }

    //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
    #define FLAG_INTERRUPT 0x01
    volatile int mainEventFlags = 0;
    boolean buttonPressed = false;

    void handleButton() {
      mainEventFlags |= FLAG_INTERRUPT;
    }

    byte LEDSTATE = LOW; //LOW=0

    void loop() {
      //******** THIS IS INTERRUPT BASED DEBOUNCING FOR BUTTON ATTACHED TO D3 (INTERRUPT 1)
      if (mainEventFlags & FLAG_INTERRUPT) {
        LowPower.powerDown(SLEEP_120MS, ADC_OFF, BOD_ON);
        mainEventFlags &= ~FLAG_INTERRUPT;
        if (!digitalRead(BUTTON_PIN)) {
          buttonPressed = true;
        }
      }
      if (buttonPressed) {
        Serial.println("Button pressed!");
        buttonPressed = false;
        radio.sendACK();
        Serial.print(" - ACK sent");
        if (radio.sendWithRetry(RECEIVER, "All About Circuits", 18)) //target node Id, message as string or byte array, message length
          delay(100);
      }
      //check if something was received (could be an interrupt from the radio)
      if (radio.receiveDone()) {
        //print message received to serial
        Serial.print('['); Serial.print(radio.SENDERID); Serial.print("] ");
        Serial.print((char*)radio.DATA);
        Serial.print("   [RX_RSSI:"); Serial.print(radio.RSSI); Serial.print("]");
        Serial.println();
        if (LEDSTATE == LOW) LEDSTATE = HIGH;
        else LEDSTATE = LOW;
        digitalWrite(LED, LEDSTATE);
        digitalWrite(RX_TOGGLE_PIN, LEDSTATE);
        //check if sender wanted an ACK
        if (radio.ACKRequested()) {
          radio.sendACK();
          Serial.print(" - ACK sent");
        }
      }
      radio.receiveDone(); //put radio in RX mode
      Serial.flush(); //make sure all serial data is clocked out before sleeping the MCU
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_ON); //sleep Arduino in low power mode (to save battery)
    }

Here is a link to project pictures: [imgur.com/a/sFW88](https://i.stack.imgur.com/Dc0Z9.jpg)

Here is [my circuit diagram](https://i.stack.imgur.com/sreQq.png): ![circuit diagram](https://i.stack.imgur.com/sreQq.png)

title: Radio Issues with RF69HW

Answers: 1

body:
The circuit diagram shows several resistive voltage divider circuits, each made up of a 1KΩ in series with 2KΩ.

When 5 V goes into the top of such a divider, about 3.3 V appears at the resistor junction.  (And 0 V in gives 0 V out.) This is suitable for a 5 V output pin connected to a 3.3 V input pin.

For connecting RF69HW 3.3 outputs (eg MISO) to 5 V Uno inputs, ideally one would step up 3.3 V to 5 V.  Instead, MISO goes to the resistor junction of what *resembles* a resistive voltage divider but in fact is not.

Consider a low output on MISO; then the 1K-2K junction goes to zero; so the Uno reads 0 on D12, as it should.

Now consider a high output on MISO.  The 1K-2K junction goes to 3.3 V, driving about 1.65 mA to ground through the 2KΩ resistor.  Presumably the SPI library uses pin 12, MISO, as an input, so current through the 1KΩ resistor is specified to be at most 10 μA (per Table 29-14 in ATmega328 datasheet) and is quite likely to be at most a few nanoAmps.  In any case, the voltage at pin 12 will be quite close to 3.3 V, which will register as a high input.  (Figure 31-72 in ATmega328 datasheet shows a 2.6 V threshold when Vcc is 5 V.)

This is more of a long comment than an answer, because although the MISO circuitry is problematic, it appears that it should work anyway.


body:
So I recently purchased:

DFRobot Wheel Encoders

DFRobot 3PA and 4WD Rovers (2pk)

Romeo V2 Arduino Controller

I was doing a bit of research online and I'm trying to figure out how to use the encoders to control the PWM applied to the motors which will make precise turns. This seems like a popular method to use. Here is some of my code. I have nothing for the encoders yet. I only have the sensors working the PWM control for the motors. All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn. Does anyone have some sample code or tips on how to do this? Thanks in advanced!
<!-- language-all: lang-cpp -->

      void stop(void)
        {
          digitalWrite(5,LOW);
          digitalWrite(6,LOW);

        }
        void forward(char a,char b)
        {
          analogWrite(5,a);
          digitalWrite(4,HIGH);
          analogWrite(6,b);
          digitalWrite(7,HIGH);

        }
        void back(char a,char b)
        {
          analogWrite(5,a);
          digitalWrite(4,LOW);
          analogWrite(6,b);
          digitalWrite(7,LOW);

        }
        void Left(char a,char b)
        {
          analogWrite (5,a);
          digitalWrite(4,LOW);
          analogWrite (6,b);
          digitalWrite(7,HIGH);

        }
        void Right(char a,char b)
        {
          analogWrite (5,a);
          digitalWrite(4,HIGH);
          analogWrite (6,b);
          digitalWrite(7,LOW);

        }
        void setup(void)
        {

          pinMode(buttonPin2, INPUT);
          pinMode(buttonPin3, INPUT);
          for(int i =4;i<=7;i++)
            pinMode(i, OUTPUT);
          pinMode(LED_BUILTIN, OUTPUT);
         forward(100,100);

          Serial.begin(9600);

        }
    void GetSensor()
    {

      Sen_Val_B = SenAvg(Sensor_Back);
      Sen_Val_F = SenAvg(Sensor_Front);
      Sen_Val_R = SenAvg(Sensor_Right);
      Sen_Val_L = SenAvg(Sensor_Left);

    }

    int SenAvg(int SensorNumber)
    {

      Arr[100]= 0;
      avg = 0;

      for(int i = 0; i<100; i++)
      {
        Arr[i] = analogRead(SensorNumber);
        avg = avg + Arr[i];
      }
        avg = avg/100;
        return avg;
    }
    void loop(void)
    {

       GetSensor();
      if(Sen_Val_F > 200)
      {
       stop();
      }

    }

title: Encoders for precise robot turns

Answers: 2

body:
> All my code does is stop the motors when the front sensor detects a wall. My next step is to implement the encoders to give the robot a 90 degree turn.

would this work?

      if (wall_sensed()) turn_90right(); //if wall is sensed, turn 90 degrees to the right

You may also consider change

      digitalWrite(5,LOW);
      digitalWrite(6,LOW);

to:

      digitalWrite(MOTOR_LF,STOP);   //stop left front motor
      digitalWrite(MOTOR_LR,STOP);   //stop left right motor

so that

1. it is a lot more readable; and
2. if you were to change pin assignment, it is done consistently throughout your code.

body:
What encoders do is give you clocked feedback on motor rotation, which you can count to get an idea of position and speed. So in order to turn by a specified amount, you will need to know how much your wheel has to turn for the given angle. You can then turn the wheel precisely by dividing your wheel circumference with the maximum encoder ticks per revolution.

Say we get 600 ticks per revolution and our wheel has a circumference of 10cm.
We would then turn the wheel by `100mm / 600 = 0,16mm` per encoder tick!

You could even write a function taking more parameters into account (robot diameter/distance between wheels) that calculates these values.
A faster/more empirical approach than gathering all these values is to just drive your robot for x (i.e. 100) ticks and measure the angle it drove to get a direct relation between encoder ticks and robot angle.

Another, much more precise solution would be to utilize a compass or gyroscope to measure the robot's orientation and rely on that instead of the encoders.


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

My code:

    // Pin 13 has a LED connected on most Arduino boards.
    // give it a name:
    int led = 13;
    const int buttonPin = 2; // pushbutton connected to pin 2.

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
      pinMode(buttonPin, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop()
    {
      bool buttonState = digitalRead(buttonPin);
      while (buttonState == HIGH) // check while the button is pressed
      {
       digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
       delay(1000);               // wait for a second
       digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
       delay(1000);               // wait for a second
      }
    }

What I wish to do is that when I press the button, the Led's start flashing and when I press them again, they stop blinking (like a fire alarm). Right now they do nothing and I dont know why. Is it something with the circuit or the code?
  [1]: https://i.stack.imgur.com/OAODo.jpg

title: Led and button simulation of a blink

Answers: 1

body:
The volatage level on the IO pin needs to change (from low to high and vice versa), only then can the microcontroller detect a button press. Without another connection to the button, IO2 is simply floating (unconnected).

There are two methods to implement this: external pull-up or external pull-down resistors and internal pull-up resistors (both methods are described for example in [this tutorial](https://electrosome.com/switch-arduino-uno)).

I prefer the internal pull-up resitor method. You need to connect the second pin of the button to GND. Then change your setup code to

    pinMode(buttonPin, INPUT_PULLUP);

If the button is not pressed, the internal pull up resistor inside the microcontroller pulls IO2 to +5V and a `digitalRead(buttonPin)` returns `HIGH`. When you press the button, IO2 is pulled to GND and `digitalRead(buttonPin)` returns `LOW`.

So in your case you need to check for a `LOW` reading, because you want the LEDs to blink when the button is pressed.

(Btw. you can replace the while loop with an if, since the `loop()` function is already executed in an infinite loop.)