body:
I have recklessly bought the [Baite Pro Mini][1] and I find it difficult to upload any program. I use Ubuntu Linux, but out of frustration I am ready to install Windows, if it is necessary.

I've read the information from the blog http://nerdralph.blogspot.ca/2014/01/baite-pro-mini-review.html . Too bad, that the blog owner didn't put much details. Can anyone here fill some blanks for me?

1. How exactly should I connect the Arduino device to the computer?
I have a converter USB to serial pl2303HX: ![PL2303HX][2] which I tried to connect with the Baite Pro Mini in almost any plausible permutation of the wires, but never got any result.

-------

edit:

Here is the description of pins of the pl2303HX: [![Pin layout of PL2303HX device][3]][3]
<sub>(source: [fasttechcdn.com](https://img.fasttechcdn.com/123/1230400/1230400-3.jpg))</sub>

I did connect it the following way:

    Baite Pro Mini      pl2303HX
    GND
    GND  <------------> GND
    VCC  <------------> +5V
    RXI  <------------> TXD
    TXC  <------------> RXD
    DTR

I also tried the permutation with different `GND` pin. I also tried pressing the `reset` button on the Baite Pro Mini around the time of hitting the "Upload" button on the Arduino standard compiler.

I believe my failure might have something to do with the absence of `DTR` pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

2. Which exactly [Arduino bootloader][4] do I need?

3. How to connect USBASP to the Beite Pro Mini?

  [1]: https://www.aliexpress.com/item/1432585134.html
  [2]: https://i.stack.imgur.com/zARZh.jpg
  [3]: https://i.stack.imgur.com/FL8Xr.jpg
  [4]: https://docs.arduino.cc/hacking/software/Bootloader

title: How to get Baite Pro Mini working?

Answers: 2

body:
I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).

I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.

I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.

Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!

You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)

body:
Your connections are incorrect if you are "straight through" connecting.
Gnd & Vcc are adjacent on the processor board and separated by 2 pins on your converter.

If you find Gnd, Vcc, TX, RX on USB module and processor then you should

 - Connect Gnd to Gnd

 - Connect Vcc to Vcc

 - Connect ........TXD to RXD and
     ........................RXD to TXD

 - Ensure that you have the correct USB converter drivers loaded.

A reset does not seem to be needed when using the Baite processor AND Baite USB module.

_______________

I have a number of Baite Pro Minis working perfectly.
In my experience (3 or 4 sales so far) Baite's products are usually of acceptable quality .

Connecting "almost any plausible permutation of the wires" is a fine way to attempt to destroy the converter and/or the BPM. Logical connection should work - if you have not damaged something.

Connect as Ignacio says.
Note that you connect **BPM-TX to USB-converter-RX**, and RX to TX and **NOT RX to RX). The BPM has connections shown on the PCB.

![enter image description here][1]

Baite provide this diagram

![enter image description here][2]

Your converter module has a different pinout which needs to be allowed for.

![enter image description here][3]

You must also have drivers on your system for the USB to serial bridge IC used on your converter. The Baite converter uses a CH340G IC. Your may or may not.

  [1]: https://i.stack.imgur.com/XWl8i.jpg
  [2]: https://i.stack.imgur.com/Acic3.jpg
  [3]: https://i.stack.imgur.com/BsLyx.jpg


body:
I'm new to Arduino/C development (coming from a JavaScript/Ruby environment), but I was wondering if it was possible to include a library from a custom folder within a sketch?

So this is my situation;

    project.ino
    libs/
      MyNewLib/
        MyNewLib.h
        MyNewLib.ccp

Now my question is: how can I include my custom library? I've tried several variations on this;

    # project.ino

    #include <libs/MyNewLib/MyNewLib.h>
    #include "libs/MyNewLib/MyNewLib.h"
    #include <./libs/MyNewLib/MyNewLib.h>
    #include "./libs/MyNewLib/MyNewLib.h"

But none of them works. Can anyone tell me if this is possible? I've looked into this question around the web, but I can't find any satisfying answer. Hopefully you guys can help.

Cheers.

**UPDATE**

I'm aware you can put your libraries in your global libraries folder, but I want them in my local project folder. I want to share them through git with my team.

title: Loading local libraries

Answers: 7

body:
I am just back to using the arduino after some time away and am somewhat bewildered
by similar issues and confused by different info from different sites and for different
versions of the ide.

What I have found is that if you have a sketch in a directory, then shut down the Ide you can drop .h, .cpp... files in the directory and the ide, when restarted, will open them with the sketch.

Include them by using simple quotes on the file names, no path, no angle brackets.

I am sure this is only part of the full answer, but it has gotten me started.

body:
The Arduino plugin for Visual Studio supports local libraries you can find the plugin [here][1]

  [1]: http://www.visualmicro.com

body:
As far as I know, you can include your libraries from a custom location by using their absolute path.

Since absolute paths could be boring from a code-portability point of view, you could define some macros to get the absolute path from a given relative one. In this way, you would just have to fix the 'project root' path when passing from a device to another.

Define your project's root folder :

        #define PROJECT_ROOT C:\path\to\your\project\folder

Define a relative-to-absolute macro 'transformation' :

        #define TO_STRING(s) #s
        #define ABSOLUTE_PATH(root, relative_path) TO_STRING(root\relative_path)
        #define RELATIVE_PATH(library) ABSOLUTE_PATH(PROJECT_ROOT, library)

Include your files using the relative path :

        #include RELATIVE_PATH(some\file\relative\path.h)
        #include RELATIVE_PATH(another\file\relative\path.h)

I hope it will be useful.

body:
The simplest way I've found to do this is store the libraries in your local sketch directory and create a symbolic link in the [HOME]/Arduino/libraries directory.  Then you can check them in to Git easily with your sketch/project and Arduino's still happy because the libraries are accessible in the global folder.

Maybe even create an install script that creates these links automatically and check that into Git too.

body:
I recently tested this local library structure. It works with:

    #include "libs/MyNewLib/MyNewLib.h"

The Arduino IDE 1.6.7 build pre-processing will even pick up the source code for the library.

Cheers!

body:
Another really bad fix - create a file called `libraries.cpp`, which contains:

    // force the linker to build the libraries
    #include "libraries/LIB1/src/FILE1.cpp"
    #include "libraries/LIB1/src/FILE2.cpp"
    #include "libraries/LIB2/src/FILE1.cpp"

Of course, this only works if the library does not itself contain any includes...

body:
Okay, here is how it works, and I checked it to make sure.

Sure you can use hard paths, but every programmer _hates_ using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.

You will find the conclusion is NOT intuitive at all. Cutting to the chase: *relative paths **don't** work correctly.* Now, why?

But first, let me explain why anyone would want to place program files _outside_ the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.

As of 1.6.13 (Teensy does not yet support 1.8.*), relative includes start from the *library*, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.

In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does *not* start in your project directory. Instead it starts in "./libraries"! So the resulting path is:

`#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp`

In conclusion there is no clean way of making your own tree of tools in  a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.


body:
I am having an issue with removing temporarily files I am creating under the /www directory. I have a subdir, "/www/csv",  where csv formatted files are being written based on sensor data. The files are created on-demand on the YUN, placed in the /www/csv dir, with the whole process driven by a REST call and an AJAX implementation in a browser.  The files are created with no problem with a Filesystem.open(path, FILE_WRITE); call. I can also use the Process calls from the bridge library to rename the file after it is full written. However, if I try to use Process calls (i.e. p.begin("rm");, etc, etc) to remove the files after use, the files are never deleted. I also tried the "mv" the files to /tmp so they would get cleaned up by the OS eventually, but that fails also. I have the rights to /www and /www/csv set to "777". I am assuming this is an access rights issue, however I am unsure what user my REST calls are running as (it would be whatever the default is for a YUN as I have created no additional users on the system).

Thanks in advance,
Pete

title: Issue with removing files progrmatically created under "/www/..."

Answers: 0


body: I am using the RX LED pin as CS for my SPI connection and experiencing problems while debugging and communicating via SPI. Is it possible somehow to disable the RX blinking while using the serial monitor?

title: How to disable RX led on Arduino Micro

Answers: 0


body:
So I have a Duemilanove board and am utilizing 7 output pins, I power a Pixy camera and pan/tilt servos from the ICSP header, i also power an HC-SR04 sonar snsor directly from the board.

Of those 7 output pins, 4 are PWMs for the motors (don't ask why), 3 are for servo control (tower pro mg-995)

when I try to output these 7 pins simultaneously things don't work, i get "components at a time" behavior. Like servos turn first, then the motors spin (servos stopped).

Initially we thought it must be a power supply problem (8 1.2v NiMh bat series) which powers the l298n h bridges (two of them) and also powers the board and servos. But now im starting to fear that it's the board itself and that it can't handle simultaneous outputs.

I've read from [here (method #10)][1] that taxing the board more than 200mA is a problem. But what exactly happens if you do just that? And is my case exactly like this one? If so, how to fix it?

+ Edit +

Here's how the circuit looks.
![enter image description here][2]

**Edit:**

Yes i do think there is a need for decoupling capacitors but im not sure where to put them. They dont seem to work. The bounty goes to the best answer on the proper decoupling of this circuit.

**Edit:**

Here's some images on the Pixy camera

![enter image description here][3]
![enter image description here][4]

**Edit:**

Actually from the original problem I noted when I posted this question, things don't work as expected. WHen the big servos move, the pan/tilt camera don't move when they are supposed to, or the motors briefly stop. I'm wondering if is also an Arduino idiosyncrasy because when I don't run the `servo.attach(servo_pin)`  code everything works fine.

  [1]: http://www.ruggedcircuits.com/10-ways-to-destroy-an-arduino/
  [2]: https://i.stack.imgur.com/ccwHt.jpg
  [3]: https://i.stack.imgur.com/DznXd.jpg
  [4]: https://i.stack.imgur.com/Vhond.jpg

title: Measure total microcontroller current?

Answers: 5

body:
When power goes through a wire, it heats up the wire. The more current you draw, the more it heats up. The "wires" inside a chip such as the one that adjusts the power aresmall, which means it heats up more, and also it takes less to burn it out.

A fuse is essentially a very thin wire. If you draw too much current (amps) through it, it will burn out (melt the wire). Wires inside a chip or on a PCB are much the same, It may recover when it cools down, or not. Some devices have protection, some do not - you may find the arduino shuts itself off to protect itself, to restart after a period. Or it may not.

As has been suggested, you can bypass the board to power the h-bridge - there should be one or two pins to power the h-bridge separate from the signalling, specifically for this reason.

Also, if the board is powered by batteries, the batteries may not be able to supply the current, causing one or more parts not getting enough power.

If you do bypass the voltage regulator and use power directly from the power source, remember that you are using a different voltage - the voltage from the power source, not +5v.

If you are powering your board from USB, then be aware that there are limitations to the power able to be supplied via USB - the USB specs say 150milliamps; any higher power has to be negotiated with the host (PC), so you may get different answers for a laptop vs. a desktop vs. a mains power adapter.

body:
My experience of high power draw from an Arduino is that it endlessly re-boots so maybe not the issue for you.

The Servo library and PWM pins are probably sharing the same timer therefore motors stop while servos are running.

You could try a different Servo library.

This [article][1] is useful to understand the timer/pwm/pin relationships

  [1]: https://stackoverflow.com/questions/18705363/arduino-uno-pwm-pins-conflict

body:
Here are a few suggestions that might help:

1. **Provide its own power supply to Arduino UNO**, so that no voltage drop can occur on the board itself due to high energy consumers as servos and DC motors. As someone suggested in an answer, a voltage drop on Arduino MCU may trigger the Brown-Out Detection (BOD) which will stop the MCU until voltage rises up again, above a given threshold. You could for instance power the UNO with a 9V battery (or the equivalent 7.2V rechargeable pack). Those batteries don't have much energy but it should be OK as long as they are not used for powering motors. Of course, then you'll have to remove the `Vin` wire to your 8-batteries pack.

2. **Add decoupling caps** (between **V+** and **GND**) as near as possible to every energy consumer: that means adding decoupling for each **motor driver** power-in pins, for each **servo** power pins, and ALSO for the **HC-SR04** sonar sensor (in my experience, it can drop voltage a lot, more than you could expect); note that you may also need decoupling for the **camera**, but I'm not sure on this one, because I have never used one yet.

**Note on decoupling caps**:

The value of caps to use depend on many factors, which would be too long to explain here (and I admit that I don't necessarily understand each of these); but typically, you would use **a small cap (100nF)** when you expect **fast (and short) voltage drops**, and **a bigger cap (>=10uF)** when you expect **longer voltage drops**.

When you don't know, you can just experiment and see what works best.

Using both kinds of caps at the same time (in parallel) does no harm (I have done this in several situations).

For higher caps, you will have to use an **electrolytic cap**, which is polarized: **do make sure that you wire them correctly (+/+, -/-) otherwise they may blow up**.

Also, choose a **breakdown voltage** for the cap that is much above (I'd say 50% above is fine) your power voltage; **16V** is a common value that would fit your needs; of course, you can use higher breakdown voltages as well.

body:
From the [Servo library documentation](http://arduino.cc/en/reference/servo):

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

This is, as has been suggested, because of conflicting usage of the timers. You should just move your DC motors to other PWM-capable pins.

body:
I know this is after the fact but "Back EMF " is more than likely the issue with the starting and stopping of the servo's and most likely the DC motors.
The power supply could receive a pulse 4 to 5 times its supply voltage. The cpu could be scrambled or reset. Or pulses sent to servos corrupted. Divert the energy of a motor's collapsing magnetic field back into itself with a diode, cathode to the positive supply rail. Basically any time you stop or start a motor its magnetic field has to go somewhere.Digital hates that.


body: Can you use `clang`, with `--mpu=arm`, etc. and `avrdude` to program an Arduino Due (Arm Cortex M3)?

title: Programming arduino with Objective-C

Answers: 3

body:
Theoretically, many things are possible. There is an easy way to code Arduino on Xcode with EmbedXCode (http://playground.arduino.cc/Main/EmbedXcode), but in C and CPP.

You need a compiler that will compile your Objective-C to for the AVR (if you are using an AVR-based Arduino), this may be difficult to find. Once your code is compiled, then you need to upload it to the Arduino.

So in any reasonable means, it is at least very challenging.

body:
Simple version: No, you cannot program Arduino using Objective-C.

Long version:
The Arduino IDE uses avr-gcc as it's compiler, and avr-gcc is a C/C++ compiler, not an Object-C compiler. The Arduino libraries are written in C/C++.

There are other compilers that exist for _AVR_ processors, and so it is possible to use other languages for the _AVR_.

However, if you switch to a different compiler for your code, you will not be able to use the Arduino libraries with it, because they are written in C/C++ for the avr-gcc compiler. (It may be possible to compile the Arduino libraries with avr-gcc, and then link them to your code using external language linking methods, but that could be a significant challenge.)

Also, I do not know of any existing Objective-C compilers for AVR; it's possible one may exist, but after a quick web search, I didn't find any.

body:
It can be done, however, it is inadvisable. In order to implement this, one must implement the Objective-C runtime, which, though not insurmountable, is very near insurmountable as far as difficulty is concerned. Perhaps someday some brave soul will see fit to grace the world with their custom Arduino Objective-C runtime, but until that day, the rest of us mere mortals have naught to do but wait for the coming of the Objective-C prophet.

If there are any brave souls in the audience who wish to take on this ultimate challenge, then let them. But otherwise, keep the code in C and hold your peace.


body: I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?

title: How Do I Send An Email WITHOUT An Ethernet or WiFi Shield

Answers: 1

body:
If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.

You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.

Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.


body:
I am trying to implement a function queue scheduling system. INT1 is connected to a button and int1task causes an LED to flash.

    typedef void (*funcptr)(void);
    TPrioQueue *queue = NULL;

    void int1ISR() {
      if (debounce(&int1time)) // Checks if the interrupt is caused by switch bouncing
        enq(queue, (void*) int1task, 1);
    }

Next, I execute the function in loop() by:

    typedef void (*funcptr)(void);

    void loop(){
      funcptr func = (funcptr) deq(queue);
      if (func != NULL)
        (*func)(); // Stuck in a loop
    }

For some reason, the LED keeps flashing even though I have not pressed the button. Why does this happen?

When I remove the line below, the ISR works properly.

    enq(queue, (void*) int1task, 1)

The relevant sections of the code:

    int debounce(unsigned long *debTimer) {
      unsigned long tmp = *debTimer;
      unsigned long currTime = millis();

      if ((currTime-tmp) > 500){
        *debTimer = currTime;
        return 1;
      }
      else
        return 0;
    }

    // Flashes LED at pin 6 five times at 2 Hz
    void int1task(){
      for(int i=0; i<5; i++){
        digitalWrite(6, HIGH);
        delay(250);
        digitalWrite(6, LOW);
        delay(250);
      }
    }

    void setup() {
      pinMode(6, OUTPUT);
      attachInterrupt(1, int1ISR, RISING);
      Serial.begin(115200);
    }

[Code I used for the queue](https://www.dropbox.com/sh/l6byqdd4r32rapd/AAD8Pxj7iiSoRjQvksr_U3o8a?dl=0)

Here is the [schematic][1] I am using:

![Enter image description here][2]

  [1]: https://www.dropbox.com/s/51f8174815zycrg/schematic.pdf?dl=0
  [2]: https://i.stack.imgur.com/WJRhr.png

title: ISR executes even though an interrupt is not triggered

Answers: 3

body:
ISRs have flags, typically an enable flag and a pending flag.

The enable flag needs to be set true for the interrupt to occur at all.

The pending flag is set when the interrupt event occurs.

Within the interrupt function, the pending flag must be cleared,

otherwise the the interrupt function will immediately be executed again (and again and again and ...)

body:
After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the `enq` and `deq` functions, which is a **must-have** if you use any of these functions from **within an ISR**.

I would suggest the simplest changes to these functions as follows:

    void enq(TPrioQueue *queue, void *item, int priority)
    {
        TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

        if(newEntry != NULL)
        {
            newEntry->item=item;
            newEntry->prio=priority;
            newEntry->prev=NULL;
            newEntry->next=NULL;

            // Protect against concurrent accesses starting here
            uint8_t sreg = SREG;
            cli();
            if(queue->head==NULL)
                queue->head=newEntry;
            else
            {
                // Find insertion point.

                // First special case: Item at head has lower priority
                if(queue->head->prio > newEntry->prio)
                {
                    // Insert item at the start of the queue.
                    newEntry->next=queue->head;
                    queue->head->prev=newEntry;
                    queue->head=newEntry;
                }
                else
                {
                    // Find your insertion point
                    TPrioQEntry *trav= queue->head;

                    while(trav->next!=NULL && trav->prio < newEntry->prio)
                        trav=trav->next;

                    newEntry->prev=trav;
                    newEntry->next=trav->next;
                    if(trav->next != NULL)
                        trav->next->prev=newEntry;

                    trav->next=newEntry;
                }
            }

            queue->itemCount++;
            // Protect against concurrent accesses stops here
            SREG = sreg;
        }
    }

    void *deq(TPrioQueue *queue)
    {
        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        // Return NULL if queue is empty
        if(queue->head == NULL)
        {
            // Protect against concurrent accesses stops here
            SREG = sreg;
            return NULL;
        }

        void *ret=queue->head->item;
        TPrioQEntry *tmp=queue->head;

        if(queue->head->next!=NULL)
            queue->head->next->prev=NULL;

        queue->head=queue->head->next;
        free(tmp);

        queue->itemCount--;

        // Protect against concurrent accesses stops here
        SREG = sreg;

        return ret;
    }

body:
Although you did not clearly mention nor show your wiring, it is possible the problem comes from here.

Barring **real concurrency issues** with your queue implementation, which I already mentioned in another answer, for which fixes have to be implemented anyway, there are two potential wiring problems in your circuit:

1. You use **INT1** interrupt; that means you must connect your button to **PIN 3** for a UNO, any other pin won't work.
2. You did not specify `pinMode(3, INPUT_PULLUP)` in your `setup()`, which means **you MUST use an external pullup resistor** to force a `HIGH` value, and connect the other pin of the button to `GND` (or conversely: put a pulldown resistor and wire the other pin to `5V`); otherwise, while the button is left unpressed, you will have a **floating input**, which means its value will vary randomly between HIGH and LOW, triggering your `int1ISR` many times when you don't expect it.

The simplest way to solve point 2 (floating input) is to use internal pullup resistors:

    void setup() {
      pinMode(3, INPUT_PULLUP);
      pinMode(6, OUTPUT);
      attachInterrupt(1, int1ISR, RISING);
      Serial.begin(115200);
    }

and connect one button pin to Arduino PIN 3, and the other button pin to `GND`.

That will remove floating input and its consequences.


body:
I'm trying to work out the best way to generate a stable frequency with my Uno R3

I'm using interrupts to generate an approximately 40KHz frequency which drives some ICs/MOSFETs to effectively generate 40KHz AC which powers a transducer.

I need to receive the frequency at a second transducer and calculate any frequency shifts.

 - The problem is that the generated frequency drifts a little bit off of 40KHz. Is there a way to lock it in at 40KHz via software? I'm receiving approximately 40KHz output (as measured using PicoScope software) with this code:

        #define LEDPIN 13
        void setup()
        {
        pinMode(LEDPIN, OUTPUT);
        // initialize Timer1
        cli();          // disable global interrupts
        TCCR1A = 0;     // set entire TCCR1A register to 0
        TCCR1B = 0;     // same for TCCR1B
        // set compare match register to desired timer count:
        OCR1A = 24;
        // turn on CTC mode:
        TCCR1B |= (1 << WGM12);
        // Set CS11 for 8-bit prescaler:
        TCCR1B |= (1 << CS11);
        // enable timer compare interrupt:
        TIMSK1 |= (1 << OCIE1A);
        // enable global interrupts:
        sei();
        }

        void loop()
        {
        // main program
        }

         ISR(TIMER1_COMPA_vect)
        {
        digitalWrite(LEDPIN, !digitalRead(LEDPIN));
        }

 - If there isn't a way to lock it in, is there atleast a way for the Uno to accurately display/store the frequency of the signal it generated at a given time?

   Or is this not plausible because the Uno would "think" it is generating 40KHz?

Thanks for  any hints or suggestions.

**EDIT:** @RussellMcMahon pointed me in the right direction for this, so I accepted his answer. However, I wanted to share my final code and my misconceptions I encountered. Hopefully this will assist someone else in the future. I'm obviously by no means an expert, and I will try to not give any misleading information here.

My original goal was, although poorly stated, to generate as clean a 40KHz PWM with 50% duty cycle as possible.

Problems with my original code above were:

 - Using an 8-bit pre-scaler
 - Using an interrupt
 - Using digitalWrite()

**8-Bit Pre-Scaler**

      The problem here was that the counter only ticked over once every 8 clock cycles. *16MHz clock / 8 (pre-scaler) = 2MHz clock* When I asked one of my professors about this he stated something along the lines of "a cycle could be missed due to an interrupt, and would cause it to wait 7 more cycles to 'tick'". Indeed I was originally using interrupts, and when we did the calculations it seemed like it could plausibly cause up to a a 1KHz swing at 40KHz.

      To rectify this I took out the pre-scaler, and ran straight at the base clock speed to increase resolution.

**Using an interrupt**

      Essentially the interrupt could cause clock cycles to not be counted, further complicated by using an 8-bit pre-scaler. If one clock cycle was missed, with a 2MHz clock (after pre-scale), you add 5E-7 seconds to the counter, changing the output frequency.

**Using digitalWrite()**

      The digitalWrite function is pretty slow. I'm not a guru, but I read this in multiple places and there seems to be a good comparison of methods here: [Digital Pin Oscillation][1] To get around this problem it had been suggested I toggle a single bit, which is what I set out to do in my final code. (It is worth noting, now that I've completed this project, that the previous link also makes reference to a [library addition][2] for faster digitalWrite/Read/etc....)

I went through a few variations and scrounged code from all over, and made a couple working examples but they didn't do it the way I wished. I believe part of the project I based this version off of was a melding between a previous version I had working and a class example I found online.

Without further ado, I present the code that took me an embarrassing amount of time to write from numerous sources... I really should tinker with this stuff more often:

    #include <avr/io.h>
    #include <avr/interrupt.h>
    void setup()
    {
    //Disable interrupts
    cli();
    // Clear Timer1 registers
    TCCR1A = 0;
    TCCR1B = 0;
    // Set OCR1A (TOP): 16MHz/40KHz /2 = 200 steps.
    // Divide 200 by 2 = 100 because waveforms are centered around OCR1A (because toggle)
    OCR1A = 100;
    // Configure Timer/Counter 1
    // Select P & F Correct PWM Mode, and OCR1A as TOP. Use WGM Bits 10 and 13.
    // WGM Bits are in TCCR1A and TCCR1B. Any previous settings are cleared.

    // Enable COM1A0 to toggle OC1A on compare match
    TCCR1A = _BV(WGM10) | _BV(COM1A0);
    // CS10 to enable base clock without pre-scale
    TCCR1B = _BV(WGM13) | _BV(CS10);

    //Set OC1A (Digital Pin 9 / Port B Pin 1) to output
    DDRB |= _BV(1);
    }

    void loop()
    {
    }

 For reference, here is the clock frequency formula. In this instance, I had to divide the result by 2 again since I am toggling.

![Clock frequency formula](https://i.stack.imgur.com/g1u6n.png)

Resultant output verified by PicoScope:
![Picoscope Oscilloscope Trace](https://i.stack.imgur.com/NdgbK.png)

In closing, you will notice that it isn't exactly 40KHz. Research turned up that the Arduino Uno makes use of a less accurate ceramic resonator to clock the ATMEGA328P (although a 16MHz crystal oscillator is onboard to clock the USB). To further increase accuracy in a generated signal will require the Arduino to be driven with an external clock source.

  [1]: http://www.billporter.info/2010/08/18/ready-set-oscillate-the-fastest-way-to-change-arduino-pins/
  [2]: http://forum.arduino.cc/index.php/topic,46896.0.html

title: Stable frequency generation

Answers: 3

body:
You can use a timer/counter to output a square wave signal of your choosing without processor intervention or use of interrupts.

In data sheet
[**"ATmega48A/PA/88A/PA/168A/PA/328/P"Atmel-8271I-AVR- ATmega-Datasheet_10/2014**](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf)

page 142  it says

 - The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the Timer/Counter value at all times. **The result of the compare can be used by the Waveform Generator to generate a** PWM or **variable frequency output on the Output Compare pins (OC2A and OC2B).** See ”Output Compare Unit” on page 143 for details. The compare match event will also set the Compare Flag (OCF2A or OCF2B) which **can** be used to generate an Output Compare interrupt request.

The interrupt CAN be generated and used but is optional.
It looks like relevant material extends as far as page 159.

body:
I know this thread may be dead but if it happens to somebody, the aformentioned method works perfectly fine. You just need to disable timer0 (power_timer0_disable();) and then your 40kHz signal will not fluctuate (in frequency).

In any case, yeah try to avoid digitalWrite if you want speed.

body:
PWM is the solution.

Russel's answer is proper. My contribution here is a simplification and to relay my observations. I made a [QA about PWM][1] recently and can affirm that "bit banging" and interrupts are not going to be stable. I observed digital writes to be roughly 1 microsecond, so toggling a pin is 2 µsec. This did not affect my project, so no further tests performed about the `digitalWrite()` function. Writing changes to the port macro as a whole is much faster than using `digitalWrite()`, however this still will not have the inherent stability setting up the PWM and its output pin will provide. *Anecdotally, analogRead() is roughly 100 µsec.*

I set up my timer with a prescaler and then applied a count to `OCRxA`. Via my prescaler and `WGM` bits, it turns out that the `OCR` registers were 1:1 for microseconds. `OCRxB` perfectly set the pulse width I was seeking.

Observing the period on an o'scope, it might have been off from the exact integer in `OCRxA` but did not drift. The error I observed was in the tens of microseconds and the values in `OCRxB` were between 6300 and 63000. Code examples are in aforementioned link to my QA. From researching my own solution, I learned this error is likely within tolerance of the crystal providing CPU freq.

  [1]: https://arduino.stackexchange.com/questions/68106/set-pwm-by-period-and-have-it-variable


body:
I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following [these instructions (the hardware setup I have is like in the schematic)](https://learn.sparkfun.com/tutorials/lsm9ds0-hookup-guide#basic-arduino-example) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from [this page](http://www.gammon.com.au/i2c-summary) it seems something basic with I2C must be wrong. The code from there I am using is:

    // I2C Scanner
    // Written by Nick Gammon
    // Date: 20th April 2011

    #include <Wire.h>

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

      // Leonardo: wait for serial port to connect
      while (!Serial)
        {
        }

      Serial.println ();
      Serial.println ("I2C scanner. Scanning ...");
      byte count = 0;

      Wire.begin();
      for (byte i = 8; i < 120; i++)
      {
        Wire.beginTransmission (i);
        if (Wire.endTransmission () == 0)
          {
          Serial.print ("Found address: ");
          Serial.print (i, DEC);
          Serial.print (" (0x");
          Serial.print (i, HEX);
          Serial.println (")");
          count++;
          delay (1);  // maybe unneeded?
          } // end of good response
      } // end of for loop
      Serial.println ("Done.");
      Serial.print ("Found ");
      Serial.print (count, DEC);
      Serial.println (" device(s).");
    }  // end of setup

    void loop() {}

Instead of this suggested sample output:

    I2C scanner. Scanning ...
    Found address: 42 (0x2A)
    Done.
    Found 1 device(s).

The output I am getting is in Serial monitor on the correct baud rate is:

    ù
    I2C s

With other examples I have tried I have similar results. As soon as something calls `Wire.endTransmission()` things start to crash and burn.

Any ideas what this could be or how to debug it?

title: I2C hookup - sketch just crashes

Answers: 1

body:
`Wire.endTransmission()` is where the action is. Nothing is actually sent until that point. `Wire.beginTransmission` just gets ready for sending and `Wire.write` (if used) adds stuff to an internal buffer.

If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).

Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.

I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.


body:
I've bought one of those cheap 2.4" TFT LCD resistive touchscreens, one of these: ![2.4" TFT LCD resistive touchscreens.][1]

It works great on my Arduino Uno, using the code from [this github repository][2].  Now I'm trying to get this to work on my Arduino Mega.

On the Arduino Uno, the LCD controller data lines are configured as:

    data[0:7] = PORTB[0:1] | PORTD[2:7]

ie. data pins 8, 9, 2, 3, 4, 5, 6, 7 make up the LCD controller data lines.

On the Mega, the pin numbers are the same but the ports are configured differently, so that:

    data[0:7] = ((PORTH >> 5) & 0x03)
       | ((PORTH << 3) & 0xc0)
       | ((PORTG >> 1) & 0x10)
       | ((PORTE >> 2) & 0x0C)
       | ((PORTE << 2) & 0x20)

I've rewritten the `TFTLCD::read8` and `TFTLCD::write8` functions accordingly.

The screen doesn't work, though.  I've cut example code down to just resetting the LCD controller and reading the chip ID register, ie:

    Tft.writeData(0);
    Tft.writeData(0);
    Tft.writeData(0);
    Tft.writeData(0);

    Tft.writeCommand(0);
    unsigned id = Tft.readData();

Now, 9 times out of ten, this obtains the correct device ID, `0x9325`.  But the other time, it obtains the device ID of `0`.

I initially suspected that this was due to the Mega running somewhat faster, but liberally sprinkling `delayMicroseconds(10)` through the `writeData`, `writeCommand` and `readData` functions doesn't seem to make any difference.

Is there something that I'm missing that is messing with the use of the PWM lines on the Arduino Mega as ordinary digital port pins?

  [1]: https://i.stack.imgur.com/aBGLH.jpg
  [2]: https://github.com/johnmccombs/arduino-libraries

title: PWM pins weird on Arduino Mega, works on Arduino Uno

Answers: 1

body:
Never mind; this was me making a mess of the bit masking.

See [this github repository][1] for working code with Arduino Mega.

  [1]: https://github.com/tomkcook/arduino-libraries


body:
I have an arduino web server running from a mega 2560 and a wiznet ethernet shield.

It serves the single page just fine (and very fast) to the LAN (192.168.1.50), but serves the same page very, very, slowly when accessed from the  WAN/Internet.

I have port forwarding set-up on the modem router so that the Arduino web page  can be accessed from the outside world, and it does work, I can see the page from anywhere, but it's page serve rate is impractically slow. The page takes 30 - 45 seconds to load up.

(I have the RaspPi with Apache set-up, also in the house, using the exact same port forwarding settings - with a different port - and it serves pages to the WAN/Internet very fast).

Has anyone any ideas what might be wrong ?

Thank you

title: arduino webserver serves single web page to WAN/Internet very very slowly

Answers: 3

body:
I haven't used the ethernet library for a while, but I remember that it served up tiny packets - basically each write call went in its own TCP packet. It sounds like you may have latency issues across the WAN.

You could try using your Apache instance to proxy the Arduino pages. Details are at http://httpd.apache.org/docs/current/mod/mod_proxy.html I have this running but all my pages are small so I'm not sure how it would behave on larger pages.

body:
The answer is :

I combined all my

    client.println("Some text here
");

html statements into much longer statements eg

    client.println("Some text here
All On   All Off
Socket 1 On   Socket 1 Off
");

This reduced the number of client.println("  ");  statements by about one third, which resolved the issue.

body: This would be a good place to get out tcpdump or WireShark (or any other tool that will let you observe network traffic). If you watch the traffic while you're making the a request that goes to the Arduino (perhaps use a phone to make the request so that it comes from outside) you will be able to observe the TCP/IP transactions and see where the delays are.


body:
I am really new to Arduino so please bear with me.

I am running an Arduino Uno with several sensors to capture some data related to a fish tank. Here is basically what it does:

 - Capture data (light, temperature, etc.)
 - Display data on an LCD screen when a button is pressed
 - Upload data to thingspeak every 5 minutes, using a ESP8266
 - Feed the fish every 4 hours through a servo
 - An RGB led blinks at various colors to let me see what's happening (e.g. red when connecting to wifi).

Everything is working reasonably well. That being said, my code is super messy and I am not sure I have the right approach. With the code I have:
 - Nothing can be done while the Arduino uploads the wifi
 - Nothing can be done when the fish are fed.

This is not so much about the servo, it is more about the wifi problem. How would you suggest that I rewrite my code so that (1) I can run the wifi more than once every 5 minutes and (2) it does not block my sensors and LCD display while I am doing it.

Sorry for the poor quality of the code. Newbie here.
<!-- language-all: lang-cpp -->

    //Include LCD Libraries
     #include <Wire.h>
     #include <LiquidCrystal_I2C.h>
     #include <stdlib.h>

    //Include Water Probe library
     #include <OneWire.h>

    //Include DHT11 Libraries
     #include <dht11.h>

    //Include Servo Libraries
     #include <Servo.h>

    //Set Peripherals
     dht11 DHT11;
     LiquidCrystal_I2C lcd(0x27,16,2);  // set the LCD address to 0x27 for a 16 chars and 2 line display
     Servo myservo;  // create servo object to control a servo

    //Pins for LCD are SDA=A4 and SCL=A5

    //Variables for sensors
        String sunlight;
        String watertemp;
     float airtemp;
        float airhumid;
        OneWire  ds(10); //water temperature, pin 10

    //Variables for LCD button
     #define BUTTON_PIN A3    // Set pin Buttons for Backlight LCD.
     unsigned int currentLcdLightOnTime = 0; // For calculating the lcd light on time.
     unsigned long lcdLightOn_StartMillis;
     boolean isLcdLightOn;
     int buttonState = 0;// For checking push-button state.

    // Variables for Status LED
     int ledState = LOW;             // ledState used to set the LED
     long previousMillis = 0;
     long interval = 1000;           // interval at which to blink (milliseconds)

    //Variables to display LCD Numbers
     char bufferhours[5]; //Output of the itoa function for hours
     char bufferminutes[5]; //Output of the itoa function for minutes
     // We don't care for seconds. It's irrelevant.
     int moisture;

    //Variables for Wifi Update
     //long DELAYWIFI = 10000; //For test purposes
     long DELAYWIFI = 300000; //Every 5 minutes
     long endtimewifi;
     long nowwifi;

    //Variables for Servo
     long FEEDINGDELAY = 14400000; // Feed every 4 hours
     //long FEEDINGDELAY = 30000; //For test purposes
     int pos = 0;    // variable to store the servo position
     long endtime;
     long now;
     long timeuntilfeeding;

    //Variables for Sunlight
     float percent; //transform number above into a percent

    // Variables for Wifi Updates

     #include <SoftwareSerial.h>

     //Hardware Serial
     #define _baudrate 9600

     //Software Serial
     #define _rxpin      0
     #define _txpin      1
     SoftwareSerial esp8266( _rxpin, _txpin ); // RX, TX

     //Thingspeak and Wifi Information
     #define SSID "xxx"
     #define PASS "yyy"
     #define IP "zzz" // ThingSpeak IP Address: 184.106.153.149

     // GET /update?key=[THINGSPEAK_KEY]&field1=[data 1]&filed2=[data 2]...;
     String GET = "GET /update?key=www";

    // Initiates special characters. http://omerk.github.io/lcdchargen/

    byte thermometer[8] = //icon for thermometer
    {
        B00100,
        B01010,
        B01010,
        B01110,
        B01110,
        B11111,
        B11111,
        B01110
    };

    byte droplet[8] = //icon for water droplet
    {
        B00100,
        B00100,
        B01010,
        B01010,
        B10001,
        B10001,
        B10001,
        B01110,
    };

    byte degree[8] = { // degree centigrade
      B01000,
      B10100,
      B01000,
      B00011,
      B00100,
      B00100,
      B00011,
      B00000
    };

    byte sun[8] = {
     0b00100,
     0b10001,
     0b01110,
     0b11111,
     0b11111,
     0b01110,
     0b10001,
     0b00100
    };

    void setup()
    {
      lcd.init();// initialize the lcd

    //Initialize DHT/
     DHT11.attach(2);

    // set the digital pin as output for LED:
     pinMode(13, OUTPUT);
     pinMode(12, OUTPUT);
     pinMode(11, OUTPUT);

    //Connect to Wifi
     Serial.begin(9600);
       esp8266.begin(9600);
       boolean wifi_connected=false; //not connected yet...

       sendesp8266("AT");
       delay(2000);
     for(int i=0;i<5;i++) //attempt 5 times to connect to wifi - this is a good idea
     {
     if(connectWiFi()) //are we connected?
     {
     wifi_connected = true; //yes
     break; //get outta here!
     }
     }

    //Initiate characters
        lcd.createChar(0, thermometer);
      lcd.createChar(1, droplet);
      lcd.createChar(2, degree);
      lcd.createChar(3, sun);

    }

    void loop(){
     now = millis();
     endtime = now + FEEDINGDELAY;

     while(now < endtime) {   // While loop for the feeding
     timeuntilfeeding = endtime - millis();
     now = millis();

        nowwifi = millis();
     endtimewifi = nowwifi + DELAYWIFI;

        while(nowwifi < endtimewifi) {   // While loop for wifi update
     nowwifi = millis();

    //We capture sensors

        //Sunlight
        float value_sunlight = analogRead(A2);
        percent = value_sunlight / 1024.0 * 100;  //Convert dryness score into moisture percentage
        String sunlight =String(percent);// turn integer to string

        //Water Temperature
        float value_watertemp = getTemp();
       String watertemp= String(value_watertemp);// turn integer to string

     //Air Temperature and Humidity
     int chk = DHT11.read(); //Read DHT11 Sensor
      float airtemp=float(DHT11.temperature);// turn integer to string
       float airhumid=float(DHT11.humidity);// turn integer to string

        // LED Blinking
     unsigned long currentMillis = millis();
     if(currentLcdLightOnTime == 0){ //We only blink when LCD is not on
       if(currentMillis - previousMillis > interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;
        // if the LED is off turn it on and vice-versa:
        if (ledState == LOW)
          ledState = HIGH;
        else
          ledState = LOW;
        // set the LED with the ledState of the variable:
        digitalWrite(11, ledState);
       }}

      buttonState = digitalRead(BUTTON_PIN);// Check the state of the push-button.

      if (buttonState == HIGH){// Button pressed.

          digitalWrite(11, LOW);

        lcdLightOn_StartMillis = millis();
        currentLcdLightOnTime = 0;
        isLcdLightOn = true;
        lcd.setBacklight(1); // switch on the backlight

        //Screen 0 Presentation

        lcd.setCursor(0, 0);
        lcd.print(" Aquaponics Bot ");

        lcd.setCursor(0, 1);
        lcd.print("  Version 1.0      ");
      }

      else{
        // Button not pressed.

        //Serial.println("Button not pressed - LOW");

        if(isLcdLightOn){
          currentLcdLightOnTime = millis() - lcdLightOn_StartMillis;

      //Screen 2
            if(currentLcdLightOnTime > 3000 && currentLcdLightOnTime <= 6000){

        //Screen 2 - Air Temperature & Humidity

        //Line 1
        lcd.setCursor(0, 0);
        lcd.print("  Air Sensors  ");

        //Line 2
        lcd.setCursor(0, 1);
        lcd.write(0);
     lcd.print(": ");
        lcd.println(airtemp);
        lcd.setCursor(5, 1);
        lcd.write(2);

        lcd.print(" - ");
        lcd.write(1);
        lcd.print(": ");
        lcd.print(airhumid);
     lcd.setCursor(14, 1);
        lcd.print("%   ");

           }

      //Screen 3
            if(currentLcdLightOnTime > 6000 && currentLcdLightOnTime < 9000){

         //Screen 3 - Water Data

        //Line 1
        lcd.setCursor(0, 0);
        lcd.print(" Water Sensors ");

        //Line 2
        lcd.setCursor(0, 1);
        lcd.write(0);
     lcd.print(": ");
        lcd.println(watertemp);
        lcd.setCursor(5, 1);
        lcd.write(2);

        lcd.print(" -  soon   ");

       }

        //Screen 4

            if(currentLcdLightOnTime > 9000 && currentLcdLightOnTime < 12000){

       //Screen 4 - Light Sensors

        //Line 1
        lcd.setCursor(0, 0);
        lcd.print(" Light Sensors  ");

        //Line 2
        lcd.setCursor(0, 1);
        lcd.write(3);
     lcd.print(": ");
        lcd.println(sunlight);
        lcd.setCursor(5, 1);
        lcd.print("% - soon   ");

          }

                if(currentLcdLightOnTime > 12000 && currentLcdLightOnTime < 15000){

         //Screen 5 - Next Feeding

        long hours=0;
         long mins=0;
         long secs=0;

         secs = timeuntilfeeding/1000; //convect milliseconds to seconds
         mins=secs/60; //convert seconds to minutes
         hours=mins/60; //convert minutes to hours
         secs=secs-(mins*60); //subtract the coverted seconds to minutes in order to display 59 secs max
        mins=mins-(hours*60); //subtract the coverted minutes to hours in order to display 59 minutes max
         //Display results
         itoa(hours, bufferhours, 10);//Convert the number of hours into readable by LCD
         itoa(mins, bufferminutes, 10);//Convert the number of minutes into readable by LCD
        lcd.setCursor(0, 0);
        lcd.print("Fish Feeding: ");
        lcd.setCursor(0, 1);
        lcd.print(bufferhours);
        lcd.print(" hours ");
         lcd.print(bufferminutes);
         lcd.print(" min.   ");

       }

      // Turn Off the Screen
          if(currentLcdLightOnTime > 15000){
            lcd.clear();
            isLcdLightOn = false;
            lcd.setBacklight(0); // switch off the backlight

            currentLcdLightOnTime = 0; //So that the blinking can start again.
            ledState = LOW;
          }
        }
      }

        } // End of the while wifi loop

     // Make sure we are still connected to the internet

       esp8266.begin(9600);
       boolean wifi_connected=false; //not connected yet...

       sendesp8266("AT");
       delay(2000);
     for(int i=0;i<5;i++) //attempt 5 times to connect to wifi - this is a good idea
     {
     if(connectWiFi()) //are we connected?
     {
     wifi_connected = true; //yes
     break; //get outta here!
     }
     }

        digitalWrite(13, HIGH);

        //We capture sensors again to send the value

        //Sunlight
        float value_sunlight = analogRead(A2);
        percent = value_sunlight / 1024.0 * 100;  //Convert dryness score into moisture percentage
        String sunlight =String(percent);// turn integer to string

        //Water Temperature
        float value_watertemp = getTemp();
       String watertemp= String(value_watertemp);// turn integer to string

     //Air Temperature and Humidity
     int chk = DHT11.read(); //Read DHT11 Sensor
      String airtemp=String(DHT11.temperature);// turn integer to string
       String airhumid=String(DHT11.humidity);// turn integer to string

       updateTS(sunlight,watertemp, airtemp, airhumid);
       delay(3000); //
        digitalWrite(13, LOW);

      } // End of the while feeding loop

      // Double Swipe to Feed the Fish

     //Intialize Servo
     myservo.attach(3);  // attaches the servo on pin 3 to the servo object
     //Display that the fish is being fed.
        digitalWrite(13, HIGH);

        for(pos = 0; pos < 180; pos += 5)  // goes from 0 degrees to 180 degrees
          {                                  // in steps of 1 degree
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(15);                       // waits 15ms for the servo to reach the position
           }

        for(pos = 180; pos>=0; pos-=5)     // goes from 180 degrees to 0 degrees
           {
             myservo.write(pos);              // tell servo to go to position in variable 'pos'
             delay(15);                       // waits 15ms for the servo to reach the position
           }

     myservo.detach();  // detattaches the servo from pin 3
        //Clears display
        digitalWrite(13, LOW);

        // SEND AN EMAIL OR UPDATE A DATABASE..

        }

        //----- update the  Thingspeak string with 4 values
        void updateTS( String L, String W , String T, String H)
        {
        // ESP8266 Client
        String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
        cmd += IP;
         cmd += "\",80";
        sendesp8266(cmd);
          delay(2000);
        if( Serial.find( "Error" ) )
        {
          esp8266.print( "RECEIVED: Error\nExit1" );
        return;
        }

         cmd = GET + "&field1=" + L +"&field2="+ W + "&field3=" + T + "&field4=" + H +"\r\n";
         Serial.print( "AT+CIPSEND=" );
         Serial.println( cmd.length() );
         if(Serial.find( ">" ) )
         {
         esp8266.print(">");
         esp8266.print(cmd);
         Serial.print(cmd);
         }
         else
         {
         sendesp8266( "AT+CIPCLOSE" );//close TCP connection
         }
         if( Serial.find("OK") )
         {
         esp8266.println( "RECEIVED: OK" );
        }
        else
        {
        esp8266.println( "RECEIVED: Error\nExit2" );
         }
         }

        void sendesp8266(String cmd) //Send info to esp8266
         {
        esp8266.print("SEND: ");
         esp8266.println(cmd);
         Serial.println(cmd);
         }

         boolean connectWiFi()
          {
         digitalWrite(11, LOW);
         digitalWrite(12, HIGH);
         Serial.println("AT+CWMODE=1");//WiFi STA mode - if '3' it is both client and AP
         delay(5000);
         //Connect to Router with AT+CWJAP="SSID","Password";
         // Check if connected with AT+CWJAP?
         String cmd="AT+CWJAP=\""; // Join accespoint
         cmd+=SSID;
         cmd+="\",\"";
         cmd+=PASS;
         cmd+="\"";
         sendesp8266(cmd);
         delay(15000);

         digitalWrite(12, LOW);

         if(Serial.find("OK"))
         {
          esp8266.println("RECEIVED: OK");
          return true;
         }
         else
         {
           esp8266.println("RECEIVED: Error");
           return false;
         }

         cmd = "AT+CIPMUX=0";// Set Single connection
         sendesp8266( cmd );
         if( Serial.find( "Error") )
         {
         esp8266.print( "RECEIVED: Error" );
          return false;
         }
       }

       float getTemp(){ //Get the water temperature
        //returns the temperature from one DS18S20 in DEG Celsius

        byte data[12];
        byte addr[8];

         if ( !ds.search(addr)) {
          //no more sensors on chain, reset search
          ds.reset_search();
          return -1000;
         }

        if ( OneWire::crc8( addr, 7) != addr[7]) {
         Serial.println("CRC is not valid!");
         return -1000;
        }

        if ( addr[0] != 0x10 && addr[0] != 0x28) {
         Serial.print("Device is not recognized");
          return -1000;
        }

        ds.reset();
        ds.select(addr);
        ds.write(0x44,1); // start conversion, with parasite power on at the end

         byte present = ds.reset();
        ds.select(addr);
        ds.write(0xBE); // Read Scratchpad

        for (int i = 0; i < 9; i++) { // we need 9 bytes
         data[i] = ds.read();
        }

        ds.reset_search();

        byte MSB = data[1];
        byte LSB = data[0];

        float tempRead = ((MSB << 8) | LSB); //using two's compliment
        float TemperatureSum = tempRead / 16;

        return TemperatureSum;

        }

title: Wifi Data Logger without Delay

Answers: 3

body:
Instead of using a delay, you may use some variable (maybe a struct or an object) to keep the status of your transmission or reading; every things that need a delay became a new state in this state-machine, every loop, based on witch status you have, you check if there are the information to execute the next step.

You may have multiple thing with status, but if they share a resource you'll need to add an abstraction layer on that resource to take care of that. (Like an event system or a message router or an output buffer)

Also you may have a status in witch you wait for a status in another state machine.

body:
As already pointed out,

You can use a while loop for your purposes:

    while(adc/send/recive_flag == 1){
    // do stuff
    }

instead of the very bad habit of using delay. (You don't need to wait any longer than you have to)

As for LCD and RGB leds, use them inside an interrupt. Make interrupt timer something like 50 ms. This way, whatever main code you are running, ISR will timout and LCD and RGB will be updated.

> Capture data (light, temperature, etc.)

Use dedicated atmega registers to read ADC. AnalogRead is **SLOW**. I think you can find information about this all over google.

> Upload data to thingspeak every 5 minutes

This should be fine. Increase transmission BAUD RATE if necessary.

To me the way it looks, you have to wait for data capture, theres no solution for that so make it faster.

As for Wifi, disable ISR, send a single message, enable ISR and wait for a bit and so on. Something like this could work.

As for feeding the fish, all you do is send PWM to servo, right? Use dedicated PWM registers on atmega for faster execution but it doesn't matter anyway for the LCD and RGB LED because they are in interrupt routine so they will be updated anyways.

body:
You can use several approaches.

Lesto already pointed out the finite state machine, but this approach will run the code as fast as possible and this might not be the behaviour you want. It's a good approach to manage, for instance, wifi connections and other communications but it won't let you schedule a task in a fixed pace.

Other options:

1) In the arduino default examples there's "Blink without delay" (\examples\digital), [here][1] you can read the code explanation. It's different from what you used

(`while(now < endtime)`)

because your code execution is kept inside the while.

If you otherwise use an

`if (currentMillis - previousMillis >= interval)`

the code will do the check but it  continues to run other instructions until the right time has come.

2) Use a [scheduler][2]!
This is handy if you have several different tasks that should run at a constant (and relatively slow for the MCU) pace.

For instance:

    #include "leOS.h"
    leOS myOS

    void setup() {
      myOS.begin();
    }
    void setup() {
      myOS.begin();
      myOS.addTask(updateTS, scheduleTime[30000, SCHEDULED]);
    }

With this code you'll run the updateTS function every 5 min, without blocking the execution of other tasks.

  [1]: https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
  [2]: https://github.com/leomil72/leOS


body:
I am making a project that requires bluetooth communication between a Raspberry Pi(equipped with a bluetooth dongle) and a standalone atmega168 circuit.

I want to be able to transfer information serially between the two devices over bluetooth.

I have selected the hc-06 for the arduino and some usb bluetooth dongle for the PI.

I would like to know if connecting the hc-06's TX and RX pins to the RX and TX (respectively) pins of my atmega will work or not. If not, I would like to know how to achieve that (bluetooth on a standalone arduino-powered microcontroller)

title: Bluetooth hc-06 and Standalone Atmega168(possible?)

Answers: 1

body:
The HC-0x Bluetooth transceivers are a drop-in replacement for a serial connection. Once the transceiver is configured (with baud-rate, device name, and pairing PIN #) you can plug it in in place of a serial line and expect to communicate. The device will take care of pairing and accepting a connection from the master device with no need for any code support from the AVR.

I use a separate program on an Arduino or a breadboarded AVR to configure my HC-06es. They retain their configuration across a power-down, and in fact, there is no hardware support for resetting them to a standard configuration; you need a program that figures out their current baud-rate in order to reconfigure them. It can save a bunch of hassle if you write down their configurations whenever you change them.


body:
I have the following line of code in my Arduino sketch:

    static double *temps = new double[arraySize];  //Declare array to hold tempratures, place the array on the heap where it will not be deleted and keep the pointer as a static
    //double temps[arraySize];

When I compile with the Arduino IDE on Ubuntu it compiles just fine. However, when I compile on the Raspberry Pi, it throws up the following error:

    xxx.cpp.o: In function `last Function in file()':
    xxx.cpp:[last line in file]: undefined referance to `operator new[] (unsigned int)'
    collect2: error: ld returned 1 exit status

Is this a bug? If so, how do I report it? If not, why is it throwing this error or how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)?

title: Compile problem when using keyword 'new' on Raspberry Pi

Answers: 2

body:
The Arduino uses [AVR libc](http://www.nongnu.org/avr-libc/) which does not provide a complete C++ environment.

Among other things AVR libc does not support `new` and `delete`. See the [FAQ](http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_cplusplus) for more information.

Some versions of the Arduino libraries may provide new and delete but they are just wrappers around `malloc` and `free`. I suggest not using new and delete on arduino because they do not have the same behavior as C++. For example destructors will not be called on the arduino when delete is called.

body:
> how else can I declare a static array of doubles (needs to be static,
> I calculate an average of some incoming data over several function
> calls)

When you find a bug in the Arduino software, please do report it to the appropriate place -- http://arduino.cc/en/Main/ContactUs has the contact details.

One way to declare a static array of doubles is like this:

    double boxcar_average(double new_sample) {
      const int arraySize = 3;
      static double old_sample[ arraySize ] = {0};
      double sum = new_sample;
      for(int i=0; i<arraySize; i++){
        sum += old_sample[i];
      }
      old_sample[0] = old_sample[1];
      old_sample[1] = old_sample[2];
      old_sample[2] = new_sample;
      return( sum / 4 );
    }


body:
Going through the "timeouts" example of the elapsedMillis library (https://github.com/pfeerick/elapsedMillis) I found the following statement:

digitalWrite(LEDPIN, flashPattern[ledIndex++] ? ledBrightness : !ledBrightness);

   - flashpattern is an array of boolean variables  (boolean flashPattern[] = { 1,1,1,1,1,1,1,0,1,1,0 };)
   - ledBrightness is a boolean as well.

What does the "?" and the ":" do there? are these boolean operators?

title: What do these operators do?

Answers: 2

body: They are the conditional operator. If the expression before the `?` is true then the result is the expression before the `:`, otherwise it is the expression after.

body:
    A ? B : C;

is shorthand for

    if(A) {
        B;
    } else {
        C;
    }


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

I'm trying to understand and adapt this tutorial:

https://learn.adafruit.com/rgb-led-strips/current-draw

to my own use. I am doing essentially the same thing, except I have this [single color LED strip][2], and I don't fully understand how to power both the arduino and the led strip from the same power source.

I tried to wire it using the diagram above, and something started smoking (I think the IR transmitter). I don't know much about circuits, but I'm pretty sure that's not good.

In this diagram, the 9v represents DC power, the IR sensor on the left represents the transmitter, the IR on the right is the receiver, and the white LED is the LED strip, with two outputs (+ - )

In the fritzing diagram for that tutorial, they have the + from the LED strip going straight in to Vin on the uno, but they don't show how either the LED strip or the uno themselves are being powered.

Do I need two power sources?

Do I need a mosfet considering I'm only using a one color LED strip?

I've got the IR sensors working, so I don't need help with that, and I can connect one of these [12V switching power supplies][3] to one of these [DC power screw terminals][4] to power the lights without any arduino control, so all I'm missing is how to turn the lights on and off with arduino, IE, how to go from the power supply to the arduino to the LED strip.

I don't need to PWM the LED strip - just shut it off and on.

If anyone can help me correct the fritzing diagram or explain what I'm doing wrong / what I should be doing instead, I'd greatly appreciate it.

  [1]: https://i.stack.imgur.com/kjlvF.png
  [2]: https://www.adafruit.com/products/887
  [3]: https://www.adafruit.com/products/352
  [4]: https://www.adafruit.com/products/368
  [5]: https://i.stack.imgur.com/XWzyY.gif

title: How to power both arduino and 1 color led strip from single power source

Answers: 2

body:
![enter image description here][1]Note that VIN pin and the 2.5mm DC Jack are connected. So in the tutorial one of these is getting power from a +12Vdc source and the other is supplying +12V to the +12v labeled pin on the LED string. Where the R G and B pins of the strip should be connected to Collectors of NPN's. Each of the NPN's bases are driven by Arduino Output pin and all the Emitters are connected to Ground.

So +12V supplies the DC Jack (aka Vin) the Arduino's local regulator converts that to Ground. The +12V via Vin supplies the LED's. And the Digital Outputs drive the base's of the NPN's. Which in turn act like a relay closing the perspective LED's to Ground, so they can illuminate. Where a Digital ONE or HIGH or TRUE on the BASE results in 5V above ground, which causes it to have low resistance.

![enter image description here][2]

  [1]: https://i.stack.imgur.com/KcJSH.png
  [2]: https://i.stack.imgur.com/y5hCW.png

body:
You asked: "Do I need a mosfet considering I'm only using a one color LED strip?"

Yes, absolutely. An Arduino logic line can only put out about 20 mA of power at 5V. That's not an unreasonable amount of power for a single low-power LED. An LED strip is likely to draw a lot more current than that, and it's pretty common for LED strips to use 12V, not 5V.

What LED strip are you using, and what input voltage and current requirements does it have?

You should be able to use a single power 12V power supply for your project. (assuming your LED strip needs 12V.) You'd feed it into the barrel jack of the Arduino. The Arduino's voltage regulator would use that to generate its 5V power. You'd also feed 12V into the power for your LED strip. You'd use a logic-level MOSFET to switch the power to the LED strip on and off. A logic level MOSFET is able to use a low current 5V signal from the Arduino to switch higher voltage, higher current loads like your LED strip with very little resistance, and thus with very little waste heat generated.


body:
I have an Arduino Megs 2560 board and using Serial 2 for communication with SIM9000A GSM Modem. I send over a HTTP get request by using appropriate AT command strings.

The GSM modem TX/RX pins are crossed with Arduino's Serial 2 port while the GSM modem card which also has DB9 pins is connected to a Hyper terminal - to see what it is receiving / rendering.

My issue is when I have to read after I get a response for my HTTP Get request.

Below is my code:

    int Read(String message)
    {
          char temp = '\0';
          int i=0;
          numbytes = 0;
          message= "";
          int endCnt = 0;
          debug_println("Reading Data!");
          Serial2.println("AT+HTTPREAD");
          delay(200);
          while(endCnt < 4) {
          while((Serial2.available())>0) {
              temp = Serial2.read();
              Serial.print(temp);
              switch(temp) {
                case '\r' : endCnt = 1; break;
                case '\n' : if(endCnt == 1) endCnt = 2; else endCnt = 0; break;
                case 'O'  : if(endCnt == 2) endCnt = 3; else endCnt = 0; break;
                case 'K'  : if(endCnt == 3) endCnt = 4; else endCnt = 0; break;
                default   : endCnt = 0; break;
              }
              if(endCnt == 4) break;

            }
         }
         debug_println("Read Data Ret: ");
         return i;
    }

Note the Terminal shows me correctly when a HTTPREAD command is passed to GSM modem:

    +HTTPACTION: 0,200,286

    +HTTPREAD: 286

    {"first_name":"dddddddddddddd","last_name":"dddddddddddddddd","start_date":"2000-12-31","chargeamt":"09.80","status":"ok","id":"68"}

    <!-- Hosting24 Analytics Code -->

    <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>

    <!-- End Of Analytics Code -->

    OK

But Serial port printing shows me :

    Reading Data!

    +HTTPREAD: 286
    {"first_name":"dddddddddddddd","last_name":"ds Code -->
    <script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
    <!-- End Of Analytics Code -->

    OK

So after reading 45-46 th character at Serial2 port I am loosing data. I have tried all ways but unable to understand why my data at serial port is lost / overwritten?

Please let me know how can I resolve this?

**====UPDATE====**

After struggling a lot I was able to resolve the issue.

The code **"delay(200);"** after Serial2.println("AT+HTTPREAD"); was causing the issue. When I reduced the time I got the response as required.

title: Data Loss over Serial Communication thru GSM SIM9000A Modem

Answers: 0


body:
I am building my first 4wd vehicle with Adafruit motor shield with one Ultrasonic sensor and one small servo to move sensor.

I am facing some problems.

1. Bought 4 motors (2 GM9 and 2 GM3), found the difference when start running and GM9 were running double the speed of GM3. Tried to slow down th eGM9 with speed in code but now one of the motor stop many times while other run.
2. Running spearate power for Arduino (now USB) and 9v batteries for motorshield. Should I remove the jumper on motor shield as found that after removing 9v battery, its getting some volts from Arduino and motors running very slowly.
3. Servo motor is not running at all. While its pins are according to the circuit.
4. Should 9v batteries will be OK to run 4 GM9/GM3 motors + 1 small Servo? if not please recommend any other.
5. When running I feel small smell from boards, nothing is hot, is it a problem?

Too many questions but tried to put in one place.

Thanks

title: Motor Shield with 4 DC motors + small servo, which battery is suitable?

Answers: 0


body: I'm trying to add some additional example files to the Arduino IDE in Ubuntu 14.04. However, I can't for the life of me find where the examples are stored in my system. I checked the Arduino website, but can't find any information there. Does anyone know where I need to put my additional files?

title: Location of examples folder in Ubuntu

Answers: 3

body: After some more searching I found it in /usr/share/arduino/examples.

body: I found mine in Linux Mint 17.3 under `opt/arduino/examples`

body:
In Ubuntu I found arduino library on
/home/MYUSERNAME/snap/arduino

where MYUSERNAME is user name


body:
I would like the sensor values to be updated each 10ms(100Hz) and then run the algorithm and repeat the same process. However, after timing the algorithm it is taking only 2ms, I think the data_ready interrupt is not working as expected. Physical hardware connection is from INT1 of ADXL345 to pin2 of the UNO.

edit:

I have configured the accelerometer to have a data rate of 100Hz. I have set up an interrupt with data_ready to run the algorithm present in the loop each time a new sample comes that is each 10ms. However each sample is coming every 2ms which shows the interrupt is not working and I would like to know why. I have timed the interrupt with the millis(); function before and after calling the interrupt, also I have stored the samples in an array and printed it on the serial interface and the samples were repeated as it was updated every 2ms instead of 10ms. The algorithm I have developed needs the sampling rate to be 100Hz.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_ADXL345_U.h>
    #include <avr/io.h>
    #include <avr/power.h>

    #define F_CPU 16000000UL

    volatile int sensor_update=0;

    //-----------------------------------------------------------------------------------     -----------
    //Write to ADXL345 registers
    void writeTo(int device, byte address, byte val) {
    Wire.beginTransmission(device); //start transmission to device
    Wire.write(address);        // send register address
    Wire.write(val);        // send value to write
    Wire.endTransmission(); //end transmission
    }

    //----------------------------------------------------------------------------------------------

    /////////////////////////////////////////////////////////////////////////////////////////////

    //ISR function

    void interrupt(void){
    sensor_update=1;

    }

    //////////////////////////////////////////////////////////////////////////////////////////////////

    void buzz(int targetPin, long frequency, long length) {
    long delayValue = 1000000/frequency/2; // calculate the delay value between     transitions
    //// 1 second's worth of microseconds, divided by the frequency, then split in half since

      //// there are two phases to each cycle
      //// calculate the number of cycles for proper timing
      long numCycles = frequency * length/ 1000;

      //// multiply frequency, which is really cycles per second, by
      //// the number of seconds to get the total number of cycles to produce
      for (long i=0; i < numCycles; i++){ // for the calculated length of time...
        digitalWrite(targetPin,HIGH); // write the buzzer pin high to push out the diaphram
        delayMicroseconds(delayValue); // wait for the calculated delay value
        digitalWrite(targetPin,LOW); // write the buzzer pin low to pull back the diaphram
        delayMicroseconds(delayValue); // wait againf or the calculated delay value
      }
    }

    /* Assign a unique ID to this sensor at the same time */
    Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12345);

    void setup(void)
    {
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
      Serial.begin(9600);
      //Serial.println("Accelerometer Test"); Serial.println("");

      pinMode(4, OUTPUT);// buzzer output pin

      /* Initialise the sensor */
      if(!accel.begin())
      {
        /* There was a problem detecting the ADXL345 ... check your connections */
        //Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
        while(1);
      }

      /* Set the range to whatever is appropriate for your project */
      accel.setRange(ADXL345_RANGE_16_G);
      accel.setDataRate(ADXL345_DATARATE_100_HZ);
      // displaySetRange(ADXL345_RANGE_8_G);
      // displaySetRange(ADXL345_RANGE_4_G);
      // displaySetRange(ADXL345_RANGE_2_G);

      //Create an interrupt that will trigger when a tap is detected.
      attachInterrupt(0, interrupt, RISING);

      writeTo(0x1D, 0x2E, 0);
      writeTo(0x1D, 0x2F, 0);
      writeTo(0x1D, 0x2E, 128);
      writeTo(0x1D, 0x2F, 127);
    }

    void loop(void)
    {

      if(sensor_update==1 ){
        //When sensor_update is set to 1 in the ISR,the algorithm process the data from the accelerometer being updated every 10ms(100Hz)
         sensor_update=0;//reset
      }
    }

title: ADXL345 Arduino UNO data_ready interrupt

Answers: 2

body:
According to the [data-sheet](https://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf):

> The interrupt functions are latched and cleared by either reading the
> data registers (Address 0x32 to Address 0x37) until the interrupt
> condition is no longer valid for the data-related interrupts or by
> reading the INT_SOURCE register (Address 0x30) for the
> remaining interrupts.

Therefore, an ISR that just sets a flag will not be called a second time. At the very least, you need to read the INT_SOURCE register. If you are using the SparkFun ADXL345 library, then this would be a call of the form:

```c
ADXL345 adxl = ADXL345();
void setup() {
  adxl.powerOn();
  adxl.setInterruptBitLevel(true); // active low
  attachInterrupt(digitalPinToInterrupt(interruptPin), isr, LOW);
  pinMode(interruptPin, INPUT);
  adxl.singleTapINT(1);
  ...
}

void isr(void) {
  detachInterrupt(digitalPinToInterrupt(interruptPin));
  interrupts();
  byte source = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(interruptPin), isr, LOW);
}
```

Note that I use a level-triggered interrupt here and re-enable interrupts before calling `adxl.getInterruptSource()`. The issue is that this call may take some time to talk over the I2C bus. To ensure that there are no reentrant calls, I detach the interrupt first. Without this, the level-triggered mode causes an interrupt loop.

The use of a level-triggered interrupt makes sense because the ADXL won't produce another interrupt until you read from `INT_SOURCE`. It also avoids the problem of missing an edge detection, which tends to cause subtle bugs that are hard to find.

I was unsure about the soundness of turning on interrupts within the ISR and so asked a question about this - https://arduino.stackexchange.com/questions/66742/what-is-the-right-way-to-query-an-i2c-device-from-an-interrupt-service-routine

body:
Been bashing my head with this one. And have searched the internet for a solution And tried for hours to program a solution.
From my tests the problem seems to be the Register 0x30—INT_SOURCE is populated with triggers. But the INT pin is only triggered when the  Register 0x30—INT_SOURCE is read.
This means that firstly the Arduino can't be woken from sleep by the INT1 or INT2 pins because they don't change unless the Arduino is already awake and reading the Register 0x30—INT_SOURCE
Second problem is to trigger an interrupt INT pin to jump to the ISR interrupt service routine you have to read Register 0x30—INT_SOURCE. And if you are going to do that then you might as well forget the interrupt and just jump into the ISR() and check registers in that. Which is how the example in the Sparkfun_ADXL345_Example for arduino ended up with the  ADXL_ISR(); call in the main loop. To sum up. Unless some one knows away to get the ADXL345 to change state on its INT pins without the need to read Register 0x30—INT_SOURCE, then the device is useless for use with the INT pins. I have given up on it and looking for another device to wake my ESP32 from sleep. Such as the BMI160 - Bosch which looks like a contender and has a arduino library for.


body:
I've written up this very simply code to control transistors in an inverter circuit. The editor is flagging up errors which I can't see myself. I'm pretty new to Arduino programming but it's very simple code and can't see why it's being shown as having errors.

At first glance, what am I missing? I've pasted a section below:

    int Phase1pos = 13;
    int Phase2pos = 12;
    int Phase3pos = 11;
    int Phase1neg = 10;
    int Phase2neg = 9;
    int Phase3neg = 8;

    void setup() {
    pinMode(Phase1pos, OUTPUT);
    pinMode(Phase2pos, OUTPUT);
    pinMode(Phase3pos, OUTPUT);
    pinMode(Phase1neg, OUTPUT);
    pinMode(Phase2neg, OUTPUT);
    pinMode(Phase3neg, OUTPUT);
    }

    void loop() {
        delayMicroseconds(16);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase2pos, HIGH);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase1pos, LOW);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase3neg, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3neg, LOW);

        delayMicroseconds(7);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3neg, LOW);
        digitalWrite(16);

        delayMicroseconds(28);
        digitalWrite(Phase3neg, HIGH);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase1pos, LOW);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase2neg, HIGH);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase3neg, LOW);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase1pos, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase1pos, HIGH);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase2neg, LOW);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase1pos, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase2neg, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase1pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase2neg, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase1neg, HIGH);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase2neg, LOW);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase3pos, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase1neg, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(7);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(2);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(2);

        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(104);
        digitalWrite(Phase2pos, HIGH);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(208);
        digitalWrite(Phase3pos, LOW);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(104);
        digitalWrite(Phase1neg, LOW);

        delayMicroseconds(2);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(80);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(47);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(159);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(47);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(80);
        digitalWrite(Phase2neg, LOW);
        delayMicroseconds(2);

        delayMicroseconds(7);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(93);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(108);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(93);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(54);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(7);

        delayMicroseconds(16);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3pos, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3pos, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(16);

        delayMicroseconds(28);
        digitalWrite(Phase1neg, HIGH);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(180);
        delayMicroseconds(180);
        digitalWrite(Phase2pos, LOW);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(28);

        delayMicroseconds(16);
        digitalWrite(Phase2pos, HIGH);
        delayMicroseconds(27);
        digitalWrite(Phase1neg, HIGH);
        delayMicroseconds(138);
        digitalWrite(Phase3neg, HIGH);
        delayMicroseconds(54);
        digitalWrite(Phase3neg, LOW);
        delayMicroseconds(138);
        digitalWrite(Phase1neg, LOW);
        delayMicroseconds(27);
        digitalWrite(Phase2pos, LOW);
        delayMicroseconds(16);
    }

title: Can't figure out the error to this code

Answers: 1

body:
Here's line 109:

     digitalWrite(16);

As the error message says, there aren't enough arguments. It looks like you meant to call `delayMicroseconds()` there instead of `digitalWrite()`.