message:
Manual Arduino Due Installation

Not sure if this is the right place to post this.

I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but it just says there is an error downloading the files.

Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

---

UPDATE

When I open the Boards Manager, I get :

`Error downloading http://downloads.arduino.cc/packages/package_index.json`

and when I try to install Due support, I get :

`Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2`

I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.

I have manually downloaded _sam-1.6.4.tar.bz2_ and extracted the contents to _C:\Arduino\arduino-1.6.5\hardware\arduino\sam_ (I had to manually create the _sam_ folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :

`Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified`

Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.

---

UPDATE 2

Question has been answered:
https://github.com/arduino/Arduino/issues/3358

Many thanks to Federico Fissore!

body:
I had the same problem described above.
Error downloading http://downloads.arduino.cc/packages/package_index.json

I solved the problem, just deleting the temporary file: "package_index.json.tmp"


sender: user

message:
Increase PWM bit resolution

I would like to increase the PWM bit resolution of the Arduino Uno.
At this moment it is 8-bit which I consider too low.
Is this possible without losing the ability of interrupts and delays?

Koen

EDIT
This setup delivers a 16-bit resultion

    void setupPWM16() {
        DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
        TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
            | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
        TCCR1B = _BV(WGM13) | _BV(WGM12)
            | _BV(CS11);                    /* prescaler: clock / 8 */
        ICR1 = 0xffff;                      /* TOP counter value (freeing OCR1A*/
    }
    /* Comments about the setup
    Changing ICR1 will effect the amount of bits of resolution.
    ICR1 = 0xffff; (65535) 16-bit resolution
    ICR1 = 0x7FFF; (32767) 15-bit resolution
    ICR1 = 0x3FFF; (16383) 14-bit resolution etc....

    Changing the prescaler will effect the frequency of the PWM signal.
    Frequency[Hz}=CPU/(ICR1+1) where in this case CPU=16 MHz
    16-bit PWM will be>>> (16000000/8)/(65535+1)=30.5175Hz
    */

    /* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
    void analogWrite16(uint8_t pin, uint16_t val)
    {
        switch (pin) {
            case  9: OCR1A = val; break;
            case 10: OCR1B = val; break;
        }
    }

sender: assistant

body:
The Arduino Uno is based on an ATmega382P microcontroller. This chip has
two 8-bit timers, driving two PWM channels each, and one 16-bit timer,
driving the last two channels.

You cannot increase the resolution of the 8-bit timers. You can,
however, put the 16-bit timer in 16-bit mode, instead of the 8-bit mode
used by the Arduino core library. This will give you two 16-bit PWM
channels, with a reduced frequency of 244 Hz (maximum). You will
probably have to configure the timer yourself, and will not benefit from
the easy to use `analogWrite()` function. For details, see the section
on Timer 1 in in the [ATmega328P
datasheet](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf).

**Update**: Here is an implementation of a 16-bit `analogWrite()`. It
only works on pins 9 and 10, as these are the only pins connected to the
16-bit timer.

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

    /* Configure digital pins 9 and 10 as 16-bit PWM outputs. */
    void setupPWM16() {
        DDRB |= _BV(PB1) | _BV(PB2);        /* set pins as outputs */
        TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
            | _BV(WGM11);                   /* mode 14: fast PWM, TOP=ICR1 */
        TCCR1B = _BV(WGM13) | _BV(WGM12)
            | _BV(CS10);                    /* no prescaling */
        ICR1 = 0xffff;                      /* TOP counter value */
    }

    /* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
    void analogWrite16(uint8_t pin, uint16_t val)
    {
        switch (pin) {
            case  9: OCR1A = val; break;
            case 10: OCR1B = val; break;
        }
    }

You may notice that the top of the counter sequence is configured
explicitly. You can change this to a smaller value to make the PWM
faster, at the cost of decreased resolution.

And here is an example sketch illustrating its use:

    void setup() {
        setupPWM16();
    }

    /* Test: send very slow sawtooth waves. */
    void loop() {
        static uint16_t i;
        analogWrite16(9, i);
        analogWrite16(10, 0xffff - i);
        i++;
        delay(1);
    }


body:
With some calibration you could sum the outputs of two PWM channels with differing weighting resistors. At the extreme you could notionally use one output to provide 8 bits of resolution and scale the other to 1/256th the level and add them so the 2nd channel covers one bit of range and you (again notionally) get 16 bits of resolution. Without immense care and adjustment all you'd get would be a mess.
However by dividing the 2nd channel by 16 or 32 you could add several extra bits of PWM resolution. Just by adding 2 PWM channels analog filtered outputs you add an extra bit (as potential range is doubled for unchanged mV/bit).
Notionally (again) for every additional divide by 2  you get an extra bit of resolution, but this can only be carried out for maybe 4 or 5 or 6 extra bits, with increasing accuracy requirements of scaling resistors and more difficult calibration and proneness to errors.

Brief example.
If one PWM is scaled down to give say 0 - 255 mV in 1 mV step, then summing two PWMs with equal amplitude would give a 0 - 510 mV range in 1 mV steps.
If one PWM is scaled down by a factor of 32 then instead of adding 255 mV to the initial PWMs range it would add only 8 mV to the top end (0.256.32 = 8 mV, but resolution would be in 0.03125 (1/32nd) mV steps.

While this could perhaps be achieved purely with resistor summing and RC filtering, use of an op amp summer would greatly improve results.

Also PWM ripple could be filtered with a simple RC filter but use of one opamp as a buffer (or even just a single transistor as an emitter follower) would give you 3 or 5 poles of low pass filtering and much better chance of achieving extra PWM resolution. I have not inspected the "phase coherence" of the PWM outputs but expect that they move in relative lockstep so you don't get the smoothing advantage of adding two uncorrelated waveforms.

More comment can be made if needed. Ask if interested.


message:
Can't detect I2C displays with Arduino Nano

All cables tested and work:

    SCL - A5
    SDA - A4
    VCC - 5V
    GND - GND

I'm using an Arduino Nano board and an I2C display - I've tried everything to get it to work and I'm now convinced it's a hardware fault. Using the Arduino I2C address scanner, it is unable to find a device, even though it is wired correctly (I've checked multiple times).

[![Nano and I2C display][1]][1]

This is the code I used, [i2c_scanner][2], and this output:

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

    Scanning...
    No I2C devices found

... is all I get.

Any suggestions, or is my board output fried?

  [1]: https://i.stack.imgur.com/6qAFF.jpg "Nano and I2C display"
  [2]: http://playground.arduino.cc/Main/I2cScanner

body:
You seem to have two issues here:

 - As already pointed out, you have the white wire connected to the wrong pin on the Arduino
 - Also, **you need to solder the headers on the Arduino.** There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers


body: Check the solder jumper on the display. Note the example code is for one address, but two addresses are supported. Try the other address in code, or solder the LCD address pads to select the address to match the code. I had the same problem, the printed address on the LCD solder pads is just the last address bits that make the difference.


message:
How to slow ADC clock speed to 1MHz on Arduino Due?

I know that the ADC on the Arduino Due has a clock speed from 1 MHz to 20 MHz. I have two questions: 1. What is the default clock speed when I run a sketch, and 2. How can I change it? (I am using Arduino 1.6.4.)

The reason why I want to slow down the ADC as much as possible is to obtain the maximum source impedance. Is this logic correct? (i.e., if I slow down the ADC in the arduino code to kHz values, then the source impedance will reach MΩ values?)
![enter image description here][1]

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

body:
You can change the prescaler (`ADCSR` register). Lowest scaler is 2, so it can never run at 20mHz. Also Atmel recommends a max ADC clock of 1MHz.

Arduino sets the ADC clock to 125 KHz (prescaler of 128)

So to match Arduino, you should select a prescaler of 8 ( set bits `ADPS1` and `ADPS0`)


body:
The atod clock is set in the mode register. The clock is 42MHz/(PRESCAL#+1). One way of setting it is the use ADC->ADCMR = ADC_MR_PRESCAL(PRESCAL#), where PRESCAL# is some integer.  These symbols are defined in component_adc.h in the Arduino source code.
 In the AVR data sheet, the recommended clock is MIN=1MHz, MAX=20 MHZ, corresponding to numbers between 41 and 1. Look in the data sheet, section 43.


message:
Relationship between baud rate and the frequency of vibration read using ADXL

I am doing a project using Arduino Uno and ADXL 345.
I am quite new to this and I came across this post  in the link" : https://www.sparkfun.com/tutorials/240. Here, a user had posted the below question in the forum.

"Im trying to use this accelerometer to test various frequencies of vibration on a cantilevered beam and I wanted to know what the maximum vibration frequency I could find with using this accelerometer, connected to a 16MHz processor, connected to my laptop. I’m mainly a mechanical person, but after doing some research I found the following: Accelerometer has a maximum of 3200Hz output data rate (so maximum frequency would be 1600Hz) Processor can execute 16,000,000 instructions/sec so this probably is okay Communication rate is 9600 bits/sec so in the program above we read at a minimum 6 bytes for each axis, so that’s 24 bits, leaving you able to read 9600/24 = 400 reads/sec resulting in a one to be capable of reading vibrations at 200Hz. If I bump up the baud rate to 115200, I should be able to then read 4800 times a second, thus measuring 2400Hz vibrations?"

But I do not see any replies to this question. I feel the above analysis mostly makes sense. It would be helpful if someone could confirm that the above analysis is right. If not right , then why isn't it right?

Thanks

body:
Firstly, the datasheet for the accelerometer suggests using >=2Mhz SPI communication rate with 3200 or 1600 Hz output data rate operation.

Since the Arduino SPI library default clock is 4Mhz, the Arduino can handle 3200 Hz sampling, so the maximum frequency you could distinguish would be 1600 Hz.

So the Arduino and accelerometer can detect vibrations up to 1600Hz.

Next, you send the data to your laptop. At 9600 BAUD, you are correct in saying that since the data is 24 bits, it will only update your laptop with the Arduino's measured frequency at 9600/24 = 400 Hz. So 400 times a second the Arduino could tell the laptop what frequency it measures, the measurement having a maximum frequency of 1600 Hz.

For the Arduino to simply pass the raw data to the laptop at 3200 Hz, you would need 24 bits * 3200 Hz = 76800 BAUD minimum.

The measurement data is in any case limited by the accelerometer sampling rate of 3200Hz.


message:
Can I power a LilyPad with an iPhone lightning port?

I want to make a toy car that follows a black line on the ground by using two sensor on the left and right sides of the car both pointing down. The sensor converts the light into a voltage that I will use to make the car turn left or right. I know that I can use batteries, but I am still very curious to find out if I could use my iPhone to power an Arduino because I also want to make a case with different sensors in it, and it would be thinner if I didn't have to put a 9V battery in the case.

body:
If the phone has an accessible battery you could conceivably use the battery terminals to power a device such as Arduino. However, I think current smartphone batteries have complex monitoring circuits so this wont work.

If it doesn't, you'd be looking at using the USB/charger port on the phone.If your phone supports USB On-The-Go, I know that it allows phones to act as USB hosts, and according to USB-OTG specifications, the host must be able to supply at least 8mA of current between 4.4V and 5.25V.

If that's enough for you it could work.


body:
Try to look at the pinout of the lightning port and create your own breakout. Then you can try taking power from the iPhone. ![Apple's Lighting port pinout][1]

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


body:
For those coming here from Google.

**The short answer is:**

Yes you technically can, but it wont be dirt cheap or very pretty depending on your wallet and tastes/requirements.

**Longer answer:**

I was researching the same thing. The problem is that Lightning connector is fairly complicated, and before it will start giving you power it requires software authentication by a chip that is built into the cable. That said you can use the USB camera connection kit or you can buy one of the IK Multimedia mini usb cables:

http://www.ikmultimedia.com/products/cat-view.php?C=spareparts

I have had success trying to tap into their cable for iRig Pro cause I happen to have one, and it gives out solid 3.3V on one of the pins which is good enough for my Arduino Mini Pro. But I would vouch that their full blown mini usb cable should be supplying regular 5V.


message:
Connecting an Arduino to a telephone line?

I would like to connect my Arduino Uno to a telephone line in order to answer a call, record a sequence of [DTMF tones](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling), generate a DTMF tone in response, and hang up.

The telephone line uses a standard [RJ11 connector](https://en.wikipedia.org/wiki/Modular_connector#RJ11_wiring). When a [touch-tone phone](https://en.wikipedia.org/wiki/Push-button_telephone#Touch-Tone) is connected to the line, it receives one of two rings:

 - a standard ring, which signals an incoming call
 - a shorter "two-ring" sequence which signals a call from a local intercom

I would like my Arduino to listen for the "two-ring" sequence and only answer those calls.

How would I go about connecting my Arduino to the telephone line? Is there a shield designed for this purpose? I know I can use the [`tone()` function](http://www.arduino.cc/en/Tutorial/Tone) to generate the DTMF tones, but I'm assuming I would need to perform some form of [Discrete Fourier transformation](https://en.wikipedia.org/wiki/Discrete_Fourier_transform) in order to "read" the DMTF tones from the other end of the line.

Any suggestions would be appreciated.

body:
You'll need some hardware assistance for the DTMF detection and generation; I doubt many Arduinos (you didn't say which, but maybe ARM?) have the horsepower to run an FFT (and deliver the results while anyone still cares....)* `tone()`may not be precise enough in frequency for DTMF detection by the calling device; you'll have to check that out. A quick search finds a number of articles on building or buying tone detectors and generators.

Ringing pattern detection is a little easier but you'll still probably want to sense the ringing and convert it to a level in hardware, rather than tracking the instantaneous line voltage and trying to distinguish in software between noise, ringing, noisy ringing, and various degrees of quiet.

<sub>* But maybe [this Hackaday project][1] can give you some alternate and computationally feasible ideas.</sub>

  [1]: http://hackaday.com/2011/10/20/detecting-dtmf-tones-from-scratch/


body:
You can interface arduino to telephone line using MT8870D chip. This IC can decode DTMF tones. Below is a reference schematic from the datasheet.

![Ref Design][1]

Another popular design floating on the internet is below:

![popular design][2]

There are pre-build modules available from [futurelec][3] :

![module][4]

You can use Holtek HT9200 IC to encode DTMF that can be interfaced with Arduino. Below is the reference schematic from its datasheet.

![encoder][5]

  [1]: https://i.stack.imgur.com/PcIHu.png
  [2]: https://i.stack.imgur.com/8uwXd.gif
  [3]: http://www.futurlec.com/Mini_MT8870.shtml
  [4]: https://i.stack.imgur.com/ZGJcL.jpg
  [5]: https://i.stack.imgur.com/xhE7V.png


message:
Can do I make an Arduino program that can decipher telephone touch tones?

I have an old land line phone that I want to connect to my Arduino.  Then I would like to write a program that can decipher the touch-tone button presses (which are a combination of two tones) so that the Arduino can react to specific key presses and numeric sequences.  My final goal is to make the Arduino play specific messages when the user enters in codes.  I am really not sure even where to begin.

Thanks for the hardwares fixes for this problem, but if possible, I am looking for a softwares solution.

This will be used to make a telephone (with an attached Arduino) that will play a series of conversations when specific codes are dialed.

body:
It is possible to decode DTMF tones with only a few common external components. The trick is to turn the analog audio into a digital signal, and then check the timing between the leading and trailing edges in order to figure out which tone is present.

First, create a 1.1V bias using a voltage divider. This bias will connect to both a capacitor that is coupling the audio, as well as one of the analog inputs. **Note that phone lines have high voltages on them at times, and you must have both isolation and voltage clamping in place before connecting a device to one.**

Second, enable the analog comparator in the MCU. See the "Analog Comparator" section of the MCU datasheet for details. Configure the non-inverting input to connect to the internal bandgap reference, the inverting input to connect to the analog input chosen earlier, and the output to connect to the input capture facility.

Third, configure the input capture facility in the MCU. See the "16-bit Timer/Counter1 with PWM" section of the datasheet, with particular emphasis on the "Input Capture Unit" subsection. Note that there is no way to trigger the input capture on "any" edge, therefore you will need to either flip the capture edge select bit each time, or you will need to detect the tone from only one set of edges. Also note that you will need to use the overflow interrupt to increment your explicit "high bytes" counter in case the edges to be detected appear on opposite sides of the overflow.

Now that all that is done, all that remains is to compare the timing detected by the input capture with your internal table of timings and select the appropriate tone from that. But that's the easy part.


body:
DTMF is actually two non-harmonically related frequencies transmitted at the same time as opposed to a single frequency tone that can be measured with the above process, hence Dual-Tone-Multi-Frequency:

![DTMF Frequency to Code table][1]

You can use the Rohm BU8872 series devices which decodes the 4 x 4 multi tone combinations directly into a 4 bit digital result per the grid above.  This also works the same way in the Mitel MT8870 series devices (I think they were bought by Microsemi).  These have digital filtering which pick out the two signals and some devices can even do single tone detection.

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


body:
As John Taylor said, DTMF is not a single tone but two tones transmitted simultaneously, which select the digit from a two-dimensional grid. (*Dual* tone multi-frequency). This allow 16 possible combinations from only 8 distinct tones.

There are chips available specifically for the task of decoding DTMF, but it's always nice to try and find a one-chip solution.

There are two solutions that I can think of:

 - [ArduinoFFT][1] - a **Fourier transform** is an operation that splits a time-based signal into its frequency components. If you control the ADC directly instead of via the Arduino library, it is easily fast enough to sample a DTMF signal. Once you've done the FFT you just need to find the peaks in the output, which will tell you the tones that are present.
 - If you put the signal through the analog comparator and **count the rate of zero-crossings** (use an interrupt with a routine that increments a number, you may miss some if you just poll the pin), the rate of crossings should be **unique for each tone combination**. Counting for e.g. 10 ms and looking up the closest match from a table you've pre-measured should give reliable decoding, and is a slightly less brute-force approach than an FFT.

That said, you won't be able to beat a dedicated chip (although I personally think this way is much more fun.)

Happy hacking!

 [1]: http://wiki.openmusiclabs.com/wiki/ArduinoFFT


message:
Using Multiple Serial Ports with arduino nano

I am using a arduino nano to control a adafruit ultimate gps and a xbee wireless controller. However I recently ran into a problem using both at the same time (before I was using each separately until now) and read that I cannot listen to 2 software serials at the same time with a arduino. The biggest problem I see is that since I can only listen to one at a time, if I open a port, will cached data from the xbee and/or gps instantly start transferring in? Or or it more luck based that I will catch it as it comes? How should I go about coding around this? Should I just close and reopen the ports as needed(assuming there is no luck factor involved)? Any help is greatly appreciated. I will explain more if necessary.

body:
You might be able to use the GPS's EN pin to enable and disable the communication to it, and also try to use the RTS/CTS pins of the XBee to control the flow, since that's their actual purpose there :)

I hope that helped.


body: The Mega and the Due have 4 UARTs. It seems like those should work, but they are much larger. I'm embarking on a project that needs to be small and use two serial ports. I'm looking at the Teensy, which has three UARTs.


body:
You can use [SoftwareSerial][1] library in order to instantiate a second (soft) serial port.

By looking at the [example][2], it seems that you can use any two digital pins to use SoftwareSerial library and instantiate a second serial port along with the hardware serial port.

  [1]: http://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: http://www.arduino.cc/en/Reference/SoftwareSerial#Example


message:
How can I add some additional 5 volt power

I have an Arduino which is being powered by a 9v, 2 amp power supply.  I have about 20 relays which are powered by 5 volts each.  I do not want to over work the voltage regulator on the board, so I would like to add another (possible 2) 5 volt regulator that I bought on amazon.  I am planning to:

 1. Connect the regulators VIN to the Arduino's vcc (9 volt)
 2. Connect the regulator's GND to the Arduino's GND.
 3. Connect the regulator's VOUT to the Relay's VCC

At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

body:
> At this point, can I also connect the regulator's VOUT to the Arduino's 5volt out?

Absolutely. But don't daisy-chain the regulator to each supply input in turn, connect each one separately directly from the regulator.

> Also, is it possible (or advisable) to add second voltage regulator to the first in a parallel configuration?

It is not advisable. Small manufacturing differences between regulators can result in them outputting slightly different voltages, which will lead to destruction of hardware.


message:
Is there a way to play sounds from an Arduino without using a sound shield?

I would like to play a wav file (spoken words) from my Arduino.  I do not want to add a sound shield.  Is there a way to play a sound through an output pin?  The quality does not have to be great.

body: The PCMAudio example shows how to play audio data via PWM. Note that you will need to access the MCU at a low level in order to do this; the Arduino libraries don't provide enough control over the hardware.


body:
Yes, you can - see http://www.instructables.com/id/Simple-Wav-Player-Using-Arduino/

Space is quite limited, unless you use an SD card.


body: I helped someone with a similar question. The results are in my github repo at https://github.com/linhartr22/count. This example uses the PWM library and includes a reference to the article I used to learn how to convert audio files to MP3 with proper settings for the PWM libary. It plays audio through an 8 ohm speaker or a piezo buzzer connected directly to the Arduino.


body:
Yes, I did a project yesterday to play recorded voice.
You don't need a speaker module.

Just connect the speaker via a resistor to one of Arduino PWM output. Then Connect a micro-sd card module. Format your micro-sd card with FAT32 Option.

Use Sample wave converter to convert your sound files and select the options as 16,000Hz Mono 8Bit. You are all done. Use [tmrpcm][1] library. It's all easy.

  [1]: https://github.com/TMRh20/TMRpcm/wiki


body:
old post but still a good question...

Here is a tutorial for playing 8 bit 33khz audio using the Adafruit M0 Express. You can play ~60 seconds of audio from the 2MB onboard flash through the 10bit Analog out pin.
https://github.com/hydronics2/SamdAudio

two other audio board solutions that offer near 16bit quality...

 - Adafruit's circuit python boards [itsbyitsyM0][1], [M4][2], feather M0. Same as above but using the circuit python interface instead of Arduino.

 - [teensy3.2][3], teensy3.5, teensy3.6 (you can play out using the Analog pin without the audio shield but the audio shield has a nice 1/8" jack

[Teensy Tutorial][4]

[Adafruit tutorial][5]

  [1]: https://www.adafruit.com/product/3727
  [2]: https://www.adafruit.com/product/3800
  [3]: https://www.adafruit.com/product/2756
  [4]: https://www.pjrc.com/teensy/td_libs_Audio.html
  [5]: https://learn.adafruit.com/circuitpython-essentials/circuitpython-audio-out


body: @Hoytman i think this arduino library can help you a lot https://sensorium.github.io/Mozzi/


message:
Find number of RX and TX-pin on ArduiMu

I've got an [Arduino V3+][1] and need to find the correct PIN number for its RX and TX-pin on the FTDI-connector.

How can I find out the correct number of them to use them with the SoftwareSerial-library?

**Why I need these numbers:**

I'm connecting a Sparkfun Bluetooth Mate/BlueSMIRF to the ArduiMUs FTDI headers and need to set a few settings in its command mode before it operates without flaws.
This is the code I'm using:

    #include <SoftwareSerial.h>

    int bluetoothTx = ???;  // TX-O pin of bluetooth mate, Arduino D2
    int bluetoothRx = ???;  // RX-I pin of bluetooth mate, Arduino D3
    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

    void setup()
    {
      Serial.begin(9600);  // Begin the serial monitor at 9600bps

      bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
      bluetooth.print("$$$");  // Enter command mode
      delay(5000);  // Short delay, wait for the Mate to send back CMD
      bluetooth.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
      // 115200 can be too fast at times for NewSoftSerial to relay the data reliably
      bluetooth.begin(9600);  // Start bluetooth serial at 9600
    }

![enter image description here][2]

  [1]: https://store.3drobotics.com/products/arduimu-v3
  [2]: https://i.stack.imgur.com/ySSNf.png

body:
You can use FTDI cable with your board on the last row of pads as you have highlighted.

Unfortunately your board designers do not publish a pdf version of the schematic so I opened the provided schematics in EAGLE and exported the FTDI connector diagram.

Here is the FTDI connector connections from the schematic:

![FTDI][1]

Here is the pinout of the FTDI cable

![FTDI Cable][2]

So you can solder a 6 pin header on the bottom row and use the standard FTDI cable.

The FTDI row on your board indicates "BLK" on the left so orient your FTDI connector's black wire with the "BLK" pad on your board.

**EDIT:**

As per your edits you are using hardware serial on your arduino board to monitor and you are using one instance of "SoftwareSerial" to interface with bluetooth.

As [SoftwareSerial][3] library says, you can define any digital pins for Tx and Rx. In the example they have used Arduino pins 10 (pin 14 of the ATMEGA) and 11 (pin 15 of ATMEGA) for Rx and Tx respectively. In your non-standard arduino board, the micro-controller pin 14 is labeled as PWM1 and pin 15 is labeled as MOSI and they are brought out on connector JP7.

![port][4]

So in a nutshell you can use pin 4 of JP7 as SoftRx and pin 5 of JP7 as SoftTx.

If those pins are in use, you can always use other digital pins that are unused in your design. Just refer to the schematic of your board, ATMEGA328 datasheet and arduino libraries.

  [1]: https://i.stack.imgur.com/8WX32.png
  [2]: https://i.stack.imgur.com/rdsaD.png
  [3]: http://www.arduino.cc/en/Reference/SoftwareSerial
  [4]: https://i.stack.imgur.com/fitkg.png


message:
Increasing ADC resolution

At this moment I am using oversampling to increase my analogread resolution.
This in combination with increasing the frequency of the ADC.
Is someone able to take a look at it?

    #define FASTADC 1
    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    int value[100];   // variable to store the value coming from the sensor
    int i=0;

    void setup()
    {
      Serial.begin(9600) ;
     int start ;
     int i ;

    #if FASTADC
     // set prescale to 16 (1MHz)
     sbi(ADCSRA,ADPS2) ;
     cbi(ADCSRA,ADPS1) ;
     cbi(ADCSRA,ADPS0) ;
    #endif
    }

    void loop()
      {
      for (i=0;i<100;i++)
      {
       value[i]=Read12bit(0);
      }
      for (i=0;i<100;i++)
      {
       Serial.println(value[i]);
      }
      Serial.println();//Some blanks between values
      Serial.println();
      delay(5000);

    }

    int Read12bit(uint8_t pin){
          int Result = 0;
          analogRead(pin);                      //Switch ADC
          for(int i = 0;i < 16; i++) {          //Read 16 times
            Result = Result + analogRead(pin);  //Sum results
          }
          Result = (int)Result/4;               //Divide by 4 for 12 bit value
          return(Result);
        }

At this moment the resolution of this oversampled analogread is 12-bits. With a little calculation the time to read will take 0,208milliseconds. If I want to increase my resolution more i.e. 13-bit. This will take the measurement 0,832 milliseconds. This seems rather big, so my question is can I do this in another way?

EDIT
**Why?**
*I am trying to position multiple linear actuator using multiple arduino's connected via CAN-bus (the arduino's will not communicate with eachother unless an error occures) THe positioning has to be precise (<0.1mm on a 30 cm rod).*

**Why is 12 or 13 bit accuracy and/or resolution needed?**

*12 is probably enough. But I just like to find out the boundaries of the equipment :)*

**What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?**

Probably none 13-bit resolution is probably too high for my application anyways.

**Other reason why I like a higher resolution**
First couple of voltages I cannot use. My sensor gives a 4 to 20mA signal which i convert with resistor to ground.

body:
Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.

I often use the [MCP3553](http://www.microchip.com/wwwproducts/Devices.aspx?product=MCP3553) which allows 60sps at 22-bit.


body:
This is in response to the question.
It is an answer to the extent that it says that

 - The current method may not work (several reasons given),

 - There may be better ways to do it, and

 - Is it necessary?

Addressing these points, or knowing that they have been addressed, is an essential part of arriving at a good solution .

If we knew the desired conversion time and actual desired resolution it would allow better answers.
If we knew what you were trying to do it might help immensely.
ie knowing what you are really trying to do may allow a quite different approach to be suggested or allow a fatal flaw to be identified.

Apart from the statistical sampling considerations that you are addressing, you cannot usually extend ADC bits indefinitely by oversampling with any great  expectations of accuracy. Oversampling works on the basis of the variable + noise being linearly randomly distributed across the 'space' at least 1/2 a bit size either side of the true value. And it makes assumptions about ways in which ADC sample and hold and acquisition gating and more work.
As you try to squeeze more bits out of the ADC the assumptions become less likely to be consistently valid.

Also, implementation of the analog input circuitry initially becomes important and then immensely important as bits of ADC resolution increase (whether achieved by over sampling or other means).

12 bits  = 0.0244% per step (as you know)
or 1.22 mV steps in a 5V reference system
or 0.81 mV/bit in a 3.3V reference system.
Getting your overall system working to that level of accuracy is possible but usually not achieved.
Any reference you are using will be natively much less accurate than that and those sort of accuracies will require calibration both initially and possibly ongoingly.
Ratiometric systems, where eg the excitation voltage of a bridge also serves as a reference, allow reference accuracy to notionally be perfect (as readings and excitation are the same and move together.
However, ensuring that the voltage at the controllers Aref pin wrt controller Agnd, and the bridge's excitation pin wrt the bridge's ground input are the same  within usefully under 1.22 mV in a 5V 12 bit system (0.6 mV in a 13 bit system, and that the bridge and controller grounds are the same within say a few hundred uV, are an obvious necessity if the 13 bits of resolution are to be meaningful - but unlikely to be achieved without the most exquisite attention to both design & implementation. (Ask me how I know :-).)

Generally, it will be much easier to obtain and maintain ADC resolutions of as many bits as are needed by the use of purpose designed conversion ICs operating as close to the signal source as is reasonably possible. (Or using instrumentation amplifiers to acquire the signals and reliably "convey" them elsewhere.) Knowing desired conversion times and resolutions is a necessary first step.

**BUT**

Why?
Why is 12 or 13 bit accuracy and/or resolution needed?
What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?
Such requirements - and much more accurate again, certainly do exist.
But knowing what the actual application is may help with decisions of how to meet it.


body:
you squeezing run time, I wonder, how much time you may save,
if instead of looping to measure you do 16 times +=
and >>2 instead /4
an another optimization to make  an own analog read function, it would be pretty simple based on original, so in additional you save time to call read function 16 times with all CPU overhead for each call.

lastly, in your own read function run the ADC in free run mode and accumulate a significant amount of data samples for oversampling.


body:
In my tests, the Arduino ADC starts to suffer from accuracy issues when you push it to 500kHz for oversampling, but 250kHz does not suffer from this problem. Also you need some kind of dither/noise, or the oversampling does not really work. I found that pulsing a digital pin with a resistor connected to ground gave me enough noise for the techinque:

https://edwardmallon.wordpress.com/2017/02/27/enhancing-arduinos-adc-resolution-by-dithering-oversampling/


message:
Arduino ADK, other board, shield or what?

Sorry for bothering.
I have a problem with my project and I can't fine someone who can help me yet.

I need the next configuration:
PC --------------USB cable-----------------MegaA---------------USB cable----------------MegaB

I need serial communication with USB cable in both boards.

I have now solved the ( PC --------USB cable------MegaA) part.

And the other part, I have done PC------------------USB cable------------------MegaB

But I need do that like the first schematic.
I don't have access to the MegaB because this is inside a machine, I can't access to its pines, I need connect to it by USB Cable.
Is possible do that with ARDUINO MEGA ADK in the MEGA A position? or I need other kind of board or add one shield (like USB host)?
I need send one thing from the pc to MegaA and Mega A send the same thing to MegaB.
Is it possible? because I can't find some way to specify that I need recieve the information from one serial port, and send it to another different serial port.
I need help, is very important.
Excuse my english
Thanks

body:
A USB host is far beyond what an AVR Mega handle. You could add a 'daugther' board of some kind, but that would be a computer far more powerfull than the Mega itself (think of a RaPi, or a fat 32-bit micro-controller), so it would be a bit weird.

You might physically patch the first USB through to the second one, using for instance a relay. That would allow the PC (but not the first Mega) to talk to the second Mega.


body:
You don't actually need to use serial-over-usb, the two devices can communicate more simply. The simplest way would be to Serial1, which uses pins D18 and D19; connect Serial1 on MegaA to either the serial or serial1 on MegaB. Since MegaA's transmit is MegaB's receive, you need to cross-over the wires (i.e. connect MegaA's TX to MegaB RX and vice versa).

Complete details can be found at: http://www.arduino.cc/en/Tutorial/MultiSerialMega

Make sure the two Megas have a common ground - the easiest way is to use one power supply (in your case, the USB) - you should just be able to wire GND and +5V from one board to the same pins on the other. If you use two different power supplies (e.g. two USB ports, even on the same PC), they may have different ground levels, and you can get a current flow directly out of one ground, and in to the other, damaging your PC.


body:
You would need a USB host shield to achieve what you want.

The Arduino by itself is not capable of connecting to both a PC and another Arduino through USB without the addition of extra hardware.  In this case the USB Host Shield as detailed on the Arduino website:

http://www.arduino.cc/en/Main/ArduinoUSBHostShield

In the list of supported devices is:

* USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.

The magic word there is ACM - that (or more specifically CDC/ACM) is what the Arduino USB Serial interface is.


message:
I am running 1.6.5, but the folder says 1.6.3?

I just downloaded the latest version of the Arduino software (1.6.5). However, when I look into the Application Support folder under Library (I have a mac), I find that I have a folder named 1.6.3:

   Library ▸ Arduino15 ▸ packages ▸ arduino ▸ hardware ▸ sam ▸ 1.6.3

Does this mean there is a hidden 1.6.5 folder that I am not seeing?

BTW, this issue surfaced, because I am trying to fiddle around with the ADC clock speed, but it seems that nothing is happening:

    void setup() {
      #define ADC_FREQ_MAX = 1;
      Serial.begin(9600);
      Serial.println(ADC_FREQ_MAX);
    }

    void loop() {
    }

gives me:

    opamp.ino: In function 'void setup()':
    opamp:2: error: expected primary-expression before '=' token
    opamp.ino:4:18: note: in expansion of macro 'ADC_FREQ_MAX'
    opamp:4: error: expected primary-expression before ')' token
    opamp:4: error: expected ';' before ')' token
    expected primary-expression before '=' token

body:
1.6.5 is the version of the Arduino IDE.

1.6.3 is the version of the Arduino SAM Boards package that you have installed.

>Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via **Tools > Board > Boards Manager** are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

1. **Tools > Examples > 01.Basics > BareMinimum**
2. **Sketch > Show Sketch Folder** - this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

>BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.


body:
The error you see is because of the equal sign in your #define.  That equal should not be there. So the line that uses it ends up being.

Serial.println(= 1);

Which is obviously wrong.


message:
Weird Arduino math result

I have a simple code, part of which contains the calculation 800/1000, which seems to return a value of zero for some reason (even though I store it in a float variable). When I replace the calculation with the expected result (0.8) the code works as expected, I just wonder why the calculation doesn't produce the same result.

body: A whole numbers like 800 or 1000 are integers, while a number like 800.4 is considered fractional and is treated as a float. Two integers divided gives an whole integer result, in your case 0. If one number in the division is an integer, and one is a float, the result is a float.


body:
Both 800.0/1000 or ((float)800)/1000 will work.

The former works only with hardcoded constants, while the latter works also with variables:

    int a = 800;
    int b = 1000;
    float c = ((float)a) / b;


message:
Reading tiny voltage changes

I have an mpx12DP pressure sensor that I want to use to measure the depth of water in a 1m tall water tank.

But it only measures up to 55mV of voltage change, which the arduino can't really detect changes in. (The sensor measures 0 to 1.45psi- 1m of water should give me 1.4psi, so I should be able to get really good accuracy).

Is this as good sensor to use for this purpose? How do I amplify the signal from the sensor? I have tried an LM324 op-amp, but couldn't get it to work (this may be entirely the wrong thing to use! And I was utterly unsure of the kind of circuit to use it in). Any advice on parts.. schematics.. a suitable already-amplified sensor that reads only up to 1.45psi?

Thank you,

Pressure sensor datasheet: http://www.digikey.co.uk/product-detail/en/MPX12DP/MPX12DP-ND/684659
Op amp datasheet: http://www.ti.com/lit/ds/symlink/lm124-n.pdf

body: You could try using `analogReference(INTERNAL);`, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.


body:
Your sensor has differential output, with a voltage difference between the Vout+ and Vout- being the measurement. The span of this difference is 0 to 55mV. The reason the sensor is wired this way is to reduce noise. To amplify this type of output you would need a differential output amplifier which is more complicated than a single op amp.

However, you can also just wire the Vout- from the sensor to ground, and then use the sensor as a single-ended output from 0 to 55mV (noise might be a problem). If you do this, you can then amplify Vout+ with your LM324 op-amp as described on page 13 of the LM324 datasheet with a non-inverting amplifier. By setting the ratio of R2/R1 to 60, you would get up to 55mV*80 = 4.4V which is pretty good.

The op amp needs some voltage headroom, so if you are using 5V supply for it, don't set the amplified voltage max to 5V.

edit: I don't think you need much headroom and 4.4V will give you better resolution than 3.3V


body:
It is reasonable to use  `analogReference(INTERNAL);`, as suggested by Alexander M, to set the range of the ADC to 1.1 V.

Another alternative is to use two resistors to make a voltage divider, to make an external reference of 1 V (min.) at the AREF pin, and then use  `analogReference(EXTERNAL);`, but the Arduino's supply voltage is likely to be noisier than the internal reference.

Regarding tiggun's suggestion about grounding the V- pin, it isn't clear to me that the mpx12DP will function correctly with V- and ground connected together.

In any case, you can use two or three of the op amps in the four-op-amp LM324 package to make a differential amplifier or an instrumentation amplifier.  See figures 38 and 39 on page 20 of the [LMx24 datasheet](http://www.ti.com/lit/ds/symlink/lm124-n.pdf) mentioned in the question.  Figure 38 shows a differential amplifier; you could, for example, replace R3 with a 50KΩ resistor and R4 with a 1MΩ resistor to get a voltage scaleup of about 21, via the formula shown: Vₒ = (1 + R4/R3)·(V₂-V₁).  Alternately, you can use a small variable resistor as in figure 39 to make a variable-gain instrumentation amplifier.


message:
How to Store the results from a Ping Sensor in a variable

I need your suggestions and help with my Ping Sensor.
I have an Arduino Uno with a Parallax Ping sensor and a motor.

My ping sensor is set to to start the motor when the nearest object is <= 10cm. That works fine.
Now, I'd like the motor to start only if the values of the sensor are progressing in a decreasing manner i.e 15, 14, 13, 12, 11, 10 but do nothing if the values are progressing in a increasing manner.

I was thinking if I stored the last 3 pings as variables and using an if/else statement but I don't know how to implement it.

How can I implement this, or if you have any other suggestion, please help me.
Thank you

Here is what i have so far:

    /* Ping))) Sensor

       This sketch reads a PING))) ultrasonic rangefinder and returns the
       distance to the closest object in range. To do this, it sends a pulse
       to the sensor to initiate a reading, then listens for a pulse
       to return.  The length of the returning pulse is proportional to
       the distance of the object from the sensor.

       The circuit:
     * +V connection of the PING))) attached to +5V
     * GND connection of the PING))) attached to ground
     * SIG connection of the PING))) attached to digital pin 7

       http://www.arduino.cc/en/Tutorial/Ping

       created 3 Nov 2008
       by David A. Mellis
       modified 30 Aug 2011
       by Tom Igoe

       This example code is in the public domain.

     */

    // this constant won't change.  It's the pin number
    // of the sensor's output:
    const int pingPin = 7;
    const int motorPin = 9;
    //Yomis code
    //int pings[3] = {-1,-1,-1};
    //int i;
    //bool Increasing(int p1, int p2, int p3)
    //{
    //  if(p1 < p2 && p2 < p3){
    //    return true;
    //  }
    //}
    //
    //bool Decreasing(int p1, int p2, int p3)
    //{
    //  if(p1 > p2 && p2 > p3){
    //    return true;
    //  }
    //}
    //
    //end of yomis code
    void setup() {
      // Set up the motor pin to be an output:

      pinMode(motorPin, OUTPUT);

      // initialize serial communication:
      Serial.begin(9600);
    }

    void loop()
    {

      // establish variables for duration of the ping,
      // and the distance result in inches and centimeters:
      long duration, inches, cm;

      // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
      pinMode(pingPin, OUTPUT);
      digitalWrite(pingPin, LOW);
      delayMicroseconds(1000);
      digitalWrite(pingPin, HIGH);
      delayMicroseconds(2000);
      digitalWrite(pingPin, LOW);

      // The same pin is used to read the signal from the PING))): a HIGH
      // pulse whose duration is the time (in microseconds) from the sending
      // of the ping to the reception of its echo off of an object.
      pinMode(pingPin, INPUT);
      duration = pulseIn(pingPin, HIGH);

      // convert the time into a distance
      inches = microsecondsToInches(duration);
      cm = microsecondsToCentimeters(duration);

      Serial.print(inches);
      Serial.print("in, ");
      Serial.print(cm);
      Serial.print("cm");
      Serial.println();

      delay(1000);

    //        //Yomis code
    //        if (cm <= 10)
    //        {
    //          Serial.println();
    //          Serial.println(pings[0]);
    //              Serial.println(pings[1]);
    //              Serial.println(pings[2]);
    //          Serial.println();
    //          if(Increasing(pings[0],pings[1],pings[2]))
    //          {
    //            int Speed1 = 100;  // between 0 (stopped) and 255 (full speed)
    //            int Time1 = 3000;  // milliseconds for speed 1
    //            analogWrite(motorPin, Speed1);  // turns the motor On
    //          }
    //        }
    //        else
    //        {
    //          analogWrite(motorPin, LOW);
    //        }
    //
    //        //End of yomis code

      if (cm <= 10) {

        int Speed1 = 150;  // between 0 (stopped) and 255 (full speed)
        int Time1 = 2000;  // milliseconds for speed 1

        int Speed2 = 250;   // between 0 (stopped) and 255 (full speed)
        int Time2 = 3000;  // milliseconds to turn the motor off

        analogWrite(motorPin, Speed1);  // turns the motor On
        delay(Time1);                   // delay for onTime milliseconds
    //    analogWrite(motorPin, Speed2);  // turns the motor Off
    //    delay(Time2);                   // delay for offTime milliseconds
      }
      else if (cm > 10) {
        analogWrite(motorPin, LOW);  // turn the motor off
      }
      else {
        Serial.print(inches);
        Serial.print("in, ");
        Serial.print(cm);
        Serial.print("cm");
        Serial.println();

        delay(100);
      }

    }

    long microsecondsToInches(long microseconds)
    {
      // According to Parallax's datasheet for the PING))), there are
      // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
      // second).  This gives the distance travelled by the ping, outbound
      // and return, so we divide by 2 to get the distance of the obstacle.m
      // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
      return microseconds / 74 / 2;
    }

    long microsecondsToCentimeters(long microseconds)
    {
      // The speed of sound is 340 m/s or 29 microseconds per centimeter.
      // The ping travels out and back, so to find the distance of the
      // object we take half of the distance travelled.
      return microseconds / 29 / 2;
    }

body:
The general idea of your code is fine, but it can be tweaked to make it more efficient.

Firstly, your function `increasing(int p1, int p2, int p3)` can be simplified to `increasing(int *pingArray)`. This way you pass a *reference* to the function, rather than three `int`s. If you decide later that your `pings` array needs to hold more values you don't have to change the function arguements. However, if you're going to be experimenting with different lengths of the `ping` array you need to make sure you change the code *within the function* to reflect this. An easy way to stay on top of it is with `#define`:

    #define MAX_PINGS 3       // Put this at the start of your code somewhere

    int pings[MAX_PINGS];     // When you come to declare 'pings'
    for (int x=0; x<MAX_PINGS; x++)
        pings[x] = -1;        // Whatever each element is initialised to.

    // Your 'increasing' function
    //   (... and the same for 'decreasing', if you decide to use it!)
    bool increasing(int *pingArray)
    {
        // CODE GOES HERE
        // and it doesn't matter how long pingArray / pings is
        // because you have 'MAX_PINGS' defined.
        return true;
    }

    // You call the 'increasing' function as you'd expect:
    if (increasing(pings))
    { /* stuff */ }

Now to the concentrating:

Your initial work is good but from what I've read on ultrasonic sensors, and from experience with any generic sensor, is that the readings aren't going to be perfect. The real world is a noisy place and you aren't going to get nice, accurate distance readings. Finding the average is a simple technique, but you will need to find an optimal solution yourself. Once you have your nice row of average values you can then determine if the distance is increasing or decreasing or neither.

Thus you have two steps:

# Average the distance
Create an array (`dist`, for now) and use it to find the average distance your sensor is from an object.

    #define MAX_DIST 5

    int dist[MAX_DIST];    // create an array, no need to initialise.
    double distAverage;    // average distance, could be 'int' instead.
    int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.

    // As you get the distance from your sensor, update 'dist' and
    // then calculate the running average.

    dist[distIterator] = microsecondsToCentimeters(duration);
    distIterator++;
    if (distIterator == MAX_DIST) distIterator = 0;
    distAverage = 0.0;
    for (int x=0; x<MAX_DIST; x++)
        distAverage += dist[x];
    distAverage /= MAX_DIST;

I hope you understand the cyclic buffer principle - if you don't you can google it! A key point about the way the code above is constructed is the use of that `#define MAX_DIST 5`. You can change that single number to anything and your code will change along with it. You will discover that there is an optimum number; I can't tell you what it is (but I recommend it remains odd).

Now that you have a nice *reliable* distance measurement, you need to find if it is increasing or decreasing...

# Average the averages
As you have worked out, you need an array of values to determine if the distance is increasing. Bring in, again, the cyclic buffer.

    #define MAX_DIST 5     // these could also be 'const int's
    #define MAX_AVRG 3     // but my preference is this way

    int dist[MAX_DIST];    // create an array, no need to initialise.
    int distIterator = 0;  // 'dist' will be a CYCLIC BUFFER. woooOOOOooo.
    int distAvrg[MAX_DIST]; // create an array of averages.
    int avrgIterator = 0;  // wwwwoooOOOOooo ? Not this time.

    // There's no single 'distAverage' anymore; the result dumps straight
    //into 'distAvrg[avrgIterator]'...

    dist[distIterator] = microsecondsToCentimeters(duration);
    distIterator++;
    if (distIterator == MAX_DIST) distIterator = 0;
    distAvrg[avrgIterator] = 0.0;
    for (int x=0; x<MAX_DIST; x++)
        distAvrg[avrgIterator] += dist[x];
    distAvrg[avrgIterator] /= MAX_DIST;
    avrgIterator++;
    if (avrgIterator == MAX_AVRG) avrgIterator = 0;

Now you have an array of your averages. Winner.

From here you can create your `increasing`/`decreasing` function. I'll leave most of this up to you, but consider the following:

 - The contents of `distAvrg` may not be perfectly smooth;
 - The longer any of the arrays, the more reliable the average;
 - The longer the array, the slower the response of the 'machine';
 - Using `int` rather than `double` for `distAvrg` may help 'numb' some of the fluctuations in averages;
 - Because `distAvrg` is a cyclic buffer, when analysing it *make sure you start at the correct element!* **HINT:** If you add your increase/decrease function *after* all the code above rather than amongst it, `avrgIterator` will always point to the *oldest* average value;
 - If the `distAverage` array gets beyond three of four elements, you should definitely *pass it by reference* to the relevant functions; this is what I did in the first codeblock I wrote. It's beyond this answer to explain why you should do it other than "it's more efficient". This is a general rule for any large chunk of data, but you'll learn more as you go along.

The simplest algorithm for determining whether the `distAvrg`s are increasing or decreasing is to run through from oldest to newest and count how many *increases* there are and how many *decreases* there are:

    int direction = 0;
    for (x=oldest ... x=newest)
    {
        if (x > x+1) direction++;
        if (x < x+1) direction--;
    }

The above is pseudo-code - you'll have translate it yourself. You end up with a value of `direction` that is a positive number (increase), a negative number (decrease), or zero. The actual value of `direction` will help you determine the speed of the increase/decrease, if it's relevant.

----------
# A possible solution:

> ** EDIT ** As pointed out by @EdgarBonet, `double` and `float` are 'expensive', in that they take up a lot of computing cycles to be dealt with. The Arduino website recommends avoiding them if you can. The alternative is to use scaled `int`s. For example, multiplying the return value from `microsecondsToCentimetres()` by 10 will give you the equivalent of one decimal place's worth of extra precision. No other code needs to change unless you're outputing the value on an LCD or similar and want it in centimeters. Dividing by 10 is conveniently the distance in millimeters, which is why I picked it, but there's no reason you can't scale by a different factor. Just be aware that there is a maximum (and mirrored minimum) value that `int` can hold, but I doubt you're going to hit it unless you scale by an unnecessarily high factor.

Let's say `MAX_AVRG` is `6`. This gives five *changes* between distances to look at. The simplest function for determining an increase is:

    bool increasing(int * DIST)
    {
        int dir = 0;

        for (int x=1; x<MAX_AVRG; x++)
        {
            if (DIST[x] > DIST[x-1])   // change this to < for DECREASE
                dir++;
            else
                dir--;
        }

        if (dir > 0)
            return TRUE;
        else
            return FALSE;
    }

The 'decrease' version is identical, save for the single commented line. The `for` loop starts at the *second* sample and checks against the *previous* sample, which is why `x` starts at 1, not 0 as 'usual'. The return value will be `true` if `distAv` has increased more times than it has decreased, and vice versa for decreasing().

Let's say distAve = { 1, 2, 1, 3, 4, 5 }. In the function:

    distAve   1   2   1   3   4   5
                ^   ^   ^   ^   ^
    start       |   |   |   |   |    dir = 0
    increase   -'   |   |   |   |    dir = 1
    decrease       -'   |   |   |    dir = 0
    increase           -'   |   |    dir = 1
    increase               -'   |    dir = 2
    increase                   -'    dir = 3

    dir > 0 therefore INCREASE.

But what if distAve = { 5, 4, 3, 2, 1, 6 } ? If `increasing()` will now return `false` because there are four decreases vs one increase, except the final distance indicates that the sensed object has ended up at an increased distance than when it started.

    int distance(int * DIST)
    {
        int overallDistance = 0;
        for (int x=1; x<MAX_AVRG; x++)
            overallDistance += (DIST[x] - DIST[x-1]);
        return overallDistance;
    }

Now you have an explicit value for the overall distance change.


body: Okay but why is everyone arguing about const and #define. That's clearly not the real problem that the person who posted the question is asking, so i'm kind of lost. @chaaarlie2. What exactly does averaging the averages do, since the distances have already been averaged to find the correct distance.


body:
I would use subtraction to find a decreasing series
you can subtract the new ping output from the previous one in every loop this way you can scale to a longer series without allocating more memory for the array

assuming you have defined somewhere:

    /*use whatever number you want here*/
    #define SERIES_LENGTH 3

declare globally:

    int prevPingSample;
    int decCount = 0;

than in your loop:

    int pingSample = analogRead(sensorPin) //or however else you sample the sensor
    if (prevPingSample > pingSample)
    { /*if the new reading is smaller than the previous -  the series is decreasing*/
     decCount = decCount + 1;
    }
    if (decCount >= SERIES_LENGTH)
    {
        //move motor code
    }
    else
    {
        decCount = 0;
    }
    //and whats left is to update the previous ping sample for the next loop
    prevPingSample = pingSample;


body:
A simpler solution. Use a variable to detect the trend and another for previous distance. Initialized to false and a very large number respectively.

Once a new distance is available the two variables are updated. If the trend is decreasing and the distance is less than your desired distance activate the motor.


message:
Analog INPUT_PULLUP for resistive sensors?

Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between *Ax* and *GND*. Software is the same, except declaring *Ax* as INPUT_PULLUP instead of INPUT.

body:
> Can you use the internal pull-up on an ADC pin?

Yes.

> Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.

Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the `DIDR0` and `DIDR1` registers appropriately.


message:
Pro Mini 5v with Adafruit motor shield v1 power sharing problems

I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine.

Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.

I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.

1. Uses 8 AA cells to power the motor shield on EXT-PWR input.
2. From EXT-PWR in motor shield one wire goes to RAW in Pro mini.
3. From Pro Mini, VCC connected to +5v on motor shield.
4. One micro servo having range sensor getting its current from motor shield.
5. Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)

Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off.

At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.

Thanks

Qazi

body: I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.


body: Sounds good, a more capable linear regulator with heat sink. Another possibility is to get a DC to DC converter (buck regulator from 12 volts to 5 volts), that way is more energy efficient than a linear regulator. They cost just slightly more than a linear regulator on ebay, and don't need a heat sink.


message:
Programmed 5 Volt output to power a relay

I need to put out 5 volts from an Arduino UNO digital pin. I've read that the pins can do approx. 5 volts, but I need to know if it will actually reach 5. I'm also powering a few other devices from the Arduino.

Are the digital pins capable of emitting 5 volts consistently? Are there any better alternatives?
Thanks.

body: Your concern for the output capability of the pin should be its current sourcing or sinking capability, not its voltage. Arduino pins typically have a limit of 40ma per pin and a total maximum of 200ma. This is for the Atmega328p (you didn't say which Arduino you're using. You'll need to drive motors or relays or anything else with a substantial current requirement with a driver circuit powered independently of the Arduino itself. That can be with a shield made for the purpose or a circuit you design and build into your project. Motors and relays in particular need snubber diodes to protect the driving circuits from inductive "kickback" or spikes generated in their coils.


message:
Assembling a float from an array of bytes

I would like to convert an array of bytes, received from serial, to a float.

Let's consider this exemple. I'm sending 0.12 byte-wise from an Android application. The conversion from float to array of bytes in the Android side is handled by this function

    public static byte [] float2Bytes(float value)
        {
            return ByteBuffer.allocate(4)./*order(ByteOrder.LITTLE_ENDIAN).*/putFloat(value).array();
        }

When bytes arrive, they are stored in an array and the assembled.

    hiBytew1 = bufferBytes[9];
    //Serial.println(hiBytew1);
    loBytew1 = bufferBytes[10];
    //Serial.println(loBytew1);
    hiBytew2 = bufferBytes[11];
    //Serial.println(hiBytew2);
    loBytew2 = bufferBytes[12];
    //Serial.println(loBytew2);
    float conAck = assemble(hiBytew1, loBytew1, hiBytew2,loBytew2);

How can I achieve this kind of conversion assuming that bytes are received in the correct order?

body:
Just cast the pointer.

    float conAck = *((float*)(bufferBytes + 9));


message:
Parsing Int over Serial Slow

I am trying to communicate between my PC and Arduino Mega 2560 using this serial [library][1]. It works reliably, however I am having trouble passing messages at a high rate over serial. I set the baud to 460800 bps on both systems, and am using a serial handshake. The Arduino reads the values by parsing a string, however during my testing I cannot parse more than ~240 messages per second. Each message into the Arduino is either of the form "r/n" to reset some variables or "0,0,0\n" where in this case the zeroes are the ints I want to parse, these can change. My Arduino code in the loop is as follows:

    if(Serial.available() > 0){
      resultString = Serial.readStringUntil('\n');
      if(resultString.equals("r")){
        countEnc0 = 0;
        countEnc1 = 0;
        countEnc2 = 0;
      }else{
        int counter = 0;
        int lastIndex = 0;
        for (int i = 0; i < resultString.length(); i++) {
          // Loop through each character and check if it's a comma
          if (resultString.substring(i, i+1) == ",") {
            // Grab the piece from the last index up to the current position and store it
           write[counter] = resultString.substring(lastIndex, i).toInt();
           // Update the last position and add 1, so it starts from the next character
           lastIndex = i + 1;
           // Increase the position in the array that we store into
           counter++;
          }
          // If we're at the end of the string (no more commas to stop us)
          if (i == resultString.length() - 1) {
            // Grab the last part of the string from the lastIndex to the end
            write[counter] = resultString.substring(lastIndex, i+1).toInt();
          }
        }
        analogWrite(8, write[0]);
        analogWrite(9, write[1]);
        analogWrite(10, write[2]);
      }
      Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
    }

I know there are more efficient ways to parse this, however my attempts to use them yield similar results (Using parseInt(), char*, etc). Additionally, I am using 3 interrupts to read sensor values and store them in variables here, and writing the values I acquire to the PWM. As long as I can read and send up to 1000 messages per second that's all I need for now. Many thanks...been banging my head against the wall on this one.

  [1]: https://github.com/wjwwood/serial

body:
First off, I would recommend [ `strtok`][1] or even `getline` to parse comma delimited strings.

Secondly, I'm pretty sure no PWM is responsive enough for 1000 updates per second. But for other purposes this data rate might be needed.

To do this, build a custom cache that does the following:

 1. Reads 1000 characters per go, if available, or less.
 2. Parses on the go. From this set up callbacks to you PWM class, so that you can set PWM values while parsing.

Why this? I am not convinced that the sluggishness is due to the `for` parsing data. More likely, it's because you are processing every instruction as you get it.

1000 serial reads with 6 length `for` loops over strings (your case) will be significantly slower than 1 serial read and a 6k length `for` loop.

  [1]: http://www.cplusplus.com/reference/cstring/strtok/


body:
If your bottleneck is really in the parsing (and you should confirm this before you spend any effort to optimize it), eliminate the parsing.

I usually recommend sending ASCII strings on serial channels to make debugging simpler, and I'd still suggest you get everything working this way first, even if you can't make the sample rate you need.

Once you're convinced your system works except for its speed, you can replace the ASCII communication with raw binary. A simple protocol would suffice: 3 or 6 bytes (do you need `int16_t`s?) of data and a 1 byte checksum downstream, and an ACK / NAK byte upstream to trigger a resend if needed, will probably be more than sufficient.

The receiver would only have to confirm the checksum and process the already ready-to-go binary sample values.


body:
The String class is slow. I would get rid of that first. I am confused about whether you are sending or receiving, or both, as your code seems to parse and then send. See this test code here:

    int countEnc0 = 123;
    int countEnc1 = 456;
    int countEnc2 = 789;

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

      unsigned long start = micros ();
      Serial.println(String(countEnc0) + "," + String(countEnc1) + "," + String(countEnc2));
      Serial.flush ();

      Serial.print ("Time taken = ");
      Serial.print (micros () - start);
      Serial.println (" uS");
      }  // end of setup

    void loop () { }

That replicates the time taken for that one line which echoes the three figures. My results were:

```Time taken = 1632 uS```

OK, yours will be faster at the faster baud rate, but only 4 times as fast.

So, 240 times that and allowing for the faster baud rate gives:

    1632 * 240 / 4 = 97920 µS

That's a fair bit of that second gone (a tenth), without even parsing anything.


message:
Why the bootloader burn on ATmega328 rather than Atmega16U2 in Arduino Uno

I have been researching about the reason why we have a second MCU in arduino UNO for a while now. finally i understood that its been use as  USB to serial converter. the question that really bug me now, why is the boot-loader is burn on the main ATmega328 not Atmega16U2 ?

body:
The purpose of the bootloader is to get the firmware through the serial
port and burn it into the flash. The 16U2 has no access to the 328's
flash. The job has to be done in the 328 itself.


message:
How to measure direction the car is coming to garage door?

my garage door is pretty narrow, about 10 cm (4") on each side of my car's rear mirrors. So every time I drive to garage, I need to go very slowly because I am afraid I might not be lined up correctly.

 I am thinking about using Arduino and some sensors to help me. Output is pretty simple, just two leds, one for each side, showing me if I should turn little right or left to have perfect lineup to center. This I can handle with no problem

 What I am asking for is idea how to measure the alignment of my car. I know how to use ultrasonic sensors for measuring distance. But I am not sure they are suitable for this project, because I want preferably to put arduino and sensors in my garage, not in my car.

Any idea how to work this out ?

body: It is very hard to determine position accurately there is a new project on kickstarter called Pozyx, you can look at that but that's expensive, to be honest this sounds like a job for hanging tennis balls or strings or something like that. But if you have a lot of money to blow and you just want a project go for it, you may be able to do this with ultrasonic sensors but I reckon that would be painful. Anyway good luck


body:
It seems like an ultrasonic sensor on each door-post should do it. You need, I'm guessing, 30cm to the sides of your car as its nose enters the doorway. Smooth the sensor reading, compute a difference and display the sign of the differences as right/left lights. Keep a small dead-band around zero-difference or you'll drive the driver crazy!

Do Ultrasonic sensors have the range and accuracy you need for the job? Time for a feasibility study.

Update:
Is 10cm plus the length of a mirror = a couple of feet? But even if so, you have to keep to +/- 10cm of the centerline to prevent striking the mirrors, so you could project your sensors out into the doorway by an amount the still keeps them > 10cm away from the car. You could mount them hinged (like the mirrors are) and padded to limit any damage from the occasional accidental touch.


body: Try to place two distance ranging sensors like ultrasonic or active infrared at the sides of the driveway or garage door. Make sure that their readings are similar so that you know that you are in the center. If one has a higher reading(farther distance) light an led to your right so you know  to go that direction and vice versa. Use communication through xbees, bluetooth, or something similar.


message:
What is GND on board?

I've looked in several places, and so far can not understand to want to be the GND who is on the board.

There is this documented anywhere?

body:
It is the 0V reference for everything else, as well as the power supply return.

"Ground (electricity)" on Wikipedia


message:
Handle reading timing in Python using pySerial

I'm not sure about how to properly handle timing readings from serial inside a Python script. I need to read a value every **5 seconds**.

From Arduino I could do,

    Serial.println(value);
    delay(5000); // should I wait here?

Inside Python script I could do,

    import serial
    import time

    arduino = serial.Serial('/dev/ttyACM1', 9600, timeout=5) # should I set timeout?

    while True and arduino.isOpen():

        try:
      value = arduino.readline().strip()
         print value

      time.sleep(5) # should I wait here?

     except KeyboardInterrupt:
      print "\nClosing..."
      arduino.close()

EDIT: Apart from that, the first reading is always wrong, like if there was something in the reading buffer.
I've found out that to solve that I should add `arduino.flushInput()` just after opening the port.

body:
The answer is that it depends on what you are actually trying to accomplish. If there is nothing else to be done on the Arduino then it is fine to have it sit and wait; on the other hand if there is nothing else for the python script to do then it is fine for it to sit and wait, but there is no reason for both of them wait.

Arduino `delay`s
------

You don't need to deal with the timing delay in python if the Arduino is `delay`ing. According to [the documentation](http://pyserial.sourceforge.net/shortintro.html#readline) `readline` will wait until it has received a value or until the timeout is reached. That said, I would make the timeout slightly longer than the delay on the Arduino side of things.

Note that `readline` will block your program from doing anything else while it waits. As such, It is pretty useful to explore python [`threading`](https://docs.python.org/2/library/threading.html#module-threading) when you are writing a program which collects data over a serial stream unless the program is *only* collecting data.

Python `sleep`s
-----
If there is other stuff to be done on the Arduino (perhaps if you are doing some filtering of the temperature data using the Arduino so as to reduce noise) then it might make more sense for it to push data to the serial stream at the end of each `loop`, and for the python script to only read the data every 5 seconds. In this case you could have python `sleep` and use no delay (or a shorter delay) on the Arduino. You can achieve this behavior without resorting to using `sleep` by using a [`timer` object](https://docs.python.org/2/library/threading.html#timer-objects) to periodically call a function that `open`s the serial stream (possibly flush it), reads the data, processes it, and closes the serial stream.


message:
How to simulate Arduino?

QUCS is the only open source software which offers simulation (and designing PCB layout [in future]) of electrical circuits. But the problem with QUCS is that it is under development and many important features are not yet available in it.

I want to simulate Arduino Uno board in it for my circuit. Does anyone know how to simulate Arduino or any other micro-controller in it?

**P.S.** Also any other open source software for simulation and PCB designing?

body:
Simulating a microcontroller's program is common, but not as part of a circuit, unless you're into Systems on Chips.

## Model the micro interfaces and simulate the peripherals separately ##

Analog systems cannot be modelled accurately by hand calculations alone, therefore simulation is often a necessary step (on top of that, real circuits might behave differently from the model). Non-programmable digital systems are deterministic in their behaviour, but only if the interfaces are correct - tight specifications on impedances and such often mean simulation is required here as well. Generally speaking, for both simulation becomes a must when the system is not dead simple. Microcontrollers on the other hand are sufficiently deterministic not to require any simulation: they do what they're told, except in very very very rare cases (single event upsets from radiation for example). Now, what they're told might allow glitches to happen, but that's a different story*. Therefore, usually the analog, or digital circuits around a microcontroller would be given equivalent interfaces based on the microcontroller's behaviour and physical specifications, and simulated separately.

*: As the code becomes more and more complex, it gets more and more difficult to follow what the microcontroller might do. Unexpected glitches may arise from e.g. concurrent access (though I can't say this is common in the micro realm), or insufficient resources (that is why dynamic allocation [malloc,new] are highly discouraged, so that the resources allocation is known at compilation time) etc. That's usually why tests are required, and step-by-step debugging is used as a means to locate any error that arises. But inherently, microcontrollers are highly predictable and except in certain cases, it is not worth it to go through simulation (do not mix up simulations and tests, tests are always required!).

## Advantages of microcontroller simulators ##

However, microcontrollers simulators do exist. They are particularly helpful to watch what happens inside the microcontroller when the code executes step by step: call stack, watches on variables, interrupt vectors etc. This can also be done on the actual hardware using in circuit debuggers, but simulators are cheaper and are also good to save on EEPROM erase/write cycles and to avoid damaging your micro if you are afraid that the devices around it might be incorrectly configured (some controllers are very expensive, especially if they are qualified for medical, military or aerospace applications). I have seen such ICD's and simulators for Microchip PICs (MPLABX), but there must be equivalents for AVR (the micro which is on the Arduino's), or perhaps even integrated in an arduino-friendly environment (though I doubt it). You might want to take a look [here][1].

## If you've got deep pockets: mixed signal simulators ##

Finally, there are mixed signal simulators which allow you to simulate analog, programmable and non-programmable digital circuits alike; one component will have an analog SPICE model, another a VHDL model, and ADC/DAC blocks will be added automatically by the simulator between those devices depending on the logic input/output technology you specify. Those are extremely expensive (the one I used is Cadence Virtuoso), you don't want to do that unless you're doing an integrated circuit or something critical.

P.S: DesignSpark PCB v3 has LTspice in it. Never tried that feature in there though, I used to use LTspice directly.

*Note that your opening "QUCS is the only open source software [...]" is wrong. There are plenty of simulators out there which are open source. I agree QUCS is a very user-friendly one though.*

  [1]: https://electronics.stackexchange.com/questions/1677/how-can-i-use-avrsim-to-simulate-arduino?rq=1


body:
You can use [123d.circuits.io][1] for simulation and PCB design for Arduino circuits.

See [this one][2] for example.

More generally, a previous answer states that Microcontroller based circuits are not simulated. Maybe that's true when prototyping costs are low (though I doubt it), but in an SoC or complex embedded system, microcontrollers certainly are simulated as part of the overall system.

Sometimes as a highlevel model such as a symbolic simulator or sometimes as a part of the overall mixed-signal simulation environment in which the digital part is usually simulated at RT level.

  [1]: https://123d.circuits.io
  [2]: https://123d.circuits.io/circuits/251828-16led


body: See my blog which will explain all steps at http://tutorial4you.weebly.com/blog/arduino-simulation-on-proteus


body: To add to the list of simulator answers, try out [Micro-Cap 12](http://www.spectrum-soft.com/download/download.shtm). It was a few thousand dollars originally, but the company has ceased operations now and has provided it for free. Pretty cool.


body:
How to simulate Arduino? What is the best Arduino simulator?

Following are the main features of the wokwi arduino simulator

It is free :)

• Supports multiple file projects

• Supports most of the famous Arduino libraries

• Whatever compiles on the Arduino IDE will compile on the simulator

• Supported by all browsers

• Compiles with latest Arduino IDE

• Supports FastLED and many other peripherals

• No download or installation needed

• Easy to share the code and project with just a single click

• Smart - Code Autocompletion, Code auto-formatting are supported

• Provides standard library demo examples

• Project can be compiled on RUN on Mobile browsers as well

• Tries to be closer to real circuits – Example – Button bounce like in real hardware

• Supports Arduino Mega, Arduino Nano, Arduino UNO, ATtiny85

• Supports assembly instruction execution

• Provides LED power and FPS features for FastLED projects

• Supports a plethora of Arduino peripherals for the project – Ultrasonic sensors, Slide switches, NeoPixel matrix, Potentiometer, Servo motors, SSD1306 OLED displays, temperature and humidity sensors, rotary dialer, membrane keypad and more

• Serial monitor is supported as well

Website: https://wokwi.com
------------------
Here are a few examples
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]
[![enter image description here][6]][6]
[![enter image description here][7]][7]
[![enter image description here][8]][8]

  [1]: https://i.stack.imgur.com/diA67.gif
  [2]: https://i.stack.imgur.com/XlmxY.gif
  [3]: https://i.stack.imgur.com/9IyQW.gif
  [4]: https://i.stack.imgur.com/1iTVS.gif
  [5]: https://i.stack.imgur.com/gR0pW.gif
  [6]: https://i.stack.imgur.com/yT2dq.gif
  [7]: https://i.stack.imgur.com/YcW81.gif
  [8]: https://i.stack.imgur.com/OaBZT.gif


message:
ESP8266 wifi module sending data via jQuery

Hey all I have the ESP8266 module and I have already set it up and it's working good. However, when I run this HTML page code here:

    <html>
     <head>
      <title>ESP8266 LED Control</title>
     </head>
     <body>
     <button id="6894" class="led">Toggle Pin 13</button> <!-- button for pin 13 -->

     <script src="jquery.min.js"></script>
     <script type="text/javascript">
      $(document).ready(function(){
       $(".led").click(function(){
        var p = $(this).attr('id'); // get id value (i.e. pin13, pin12, or pin11)

        $.get("http://192.168.9.60:80/", {pin:p}); // execute get request
       });
      });
     </script>
     </body>
    </html>

I have to send the number 6894 instead of 13 because for some reason its not sending out the correct number. If i send 13 then what it receive is 114. When i send 6894 i receive 689.

My arduino code is this:

    */
    //====================================================================================
    //                                [The SSDI of the current wifi router]
    //                                |              [The password of the current wifi router]
    //                                |              |
    //                                V              V
    String SSIDandPW    = "AT+CWJAP=\"xxxxxxwifi\",\"xxxxxx123\"\r\n";

    //                                      [The STATIC IP of the wifi module]
    //                                      |                [The main IP of the router]
    //                                      |                |              [The default submask]
    //                                      |                |              |
    //                                      V                V              V
    String eIPrIPmask   = "AT+CIPSTA_DEF=\"192.168.9.60\",\"192.168.9.1\",\"255.255.255.0\"\r\n";
    const int ledDimmer = 5;         // Used to dim the LED strip (digital Pin 3)

    SoftwareSerial esp8266(9,10);    // Pin D10 to=> TX on ESP8266 | Pin D9 to=> RX on ESP8266
    //================================= End define WiFi Module =================================
    //==========================================================================================

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

      pinMode(13, OUTPUT); //Just for a wifi demo from html page

      //================================ Start Setup WiFi Module =================================
      //==========================================================================================
      esp8266.begin(19200);
      sendData("AT+RST\r\n",                    2000, true); // Reset module
      sendData("AT+CWMODE=1\r\n",               2000, true); // Configure as access point
      sendData(SSIDandPW,                       5000, true); // Pass of current wifi
      sendData("AT+CIPMUX=1\r\n",               2000, true); // Configure for multiple connections
      sendData("AT+UART_DEF=19200,8,1,0,0\r\n", 2000, true); // Set baud of COM
      sendData(eIPrIPmask,                      2000, true); // Default network mask IP
      sendData("AT+CIPSERVER=1,80\r\n",         2000, true); // Turn on server on port 80
      sendData("AT+GMR\r\n",                    2000, true); // Get firmware version
      sendData("AT+CIFSR\r\n",                  2000, true); // Get ip address
      Serial.print("Server is now running!");
      //================================ End Setup WiFi Module ===================================
      //==========================================================================================
    }

    void loop() {
      //=========================================== Start Loop WiFi Module ===========================================
      //==============================================================================================================
      if(esp8266.available()) {                               // check if the esp is sending a message
        if(esp8266.find("+IPD,")) {
          delay(500);
          int connectionId = esp8266.read() - 48;             // subtract 48 because the read() function returns

          esp8266.find("pin=");                               // advance cursor to "pin="
          int retunedNum = (esp8266.read() - 48) * 100;       // get first number (example: 123.. this would be "1")
          retunedNum += (esp8266.read() - 48) * 10;           // get second number (example: 123.. this would be "2")
          retunedNum += (esp8266.read() - 48);                // get last number (example: 123.. this would be "3")
          String closeCommand = "AT+CIPCLOSE=";               // make close command
          Serial.print("returned: ");
          Serial.print(retunedNum);
          Serial.print("----------");
          closeCommand += connectionId;                       // append connection id
          closeCommand += "\r\n";
          sendData(closeCommand,                250, true);   // close connection
          //digitalWrite(retunedNum, !digitalRead(retunedNum));   // toggle pin
          if (retunedNum == 6894) {
            Serial.print("OFF");
            digitalWrite(ledDimmer, LOW);
          } else if (retunedNum == 6904) {
            Serial.print("ON");
            digitalWrite(ledDimmer, HIGH);
          } else if (retunedNum == 689) {
            digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
            delay(1000);              // wait for a second
            digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
            delay(1000);              // wait for a second
          }
        }
      }
      //============================================ End Loop WiFi Module ============================================
      //==============================================================================================================
    }

    //                     [The data/command to send]
    //                     |                  [The time to wait for a response]
    //                     |                  |                [Print to Serial window (true = yes | false = no)]
    //                     |                  |                |
    //                     V                  V                V
    String sendData(String command, const int timeout, boolean debug) {
      String response = "";
      long int time   = millis();

      esp8266.print(command);          // send the read character to the esp8266

      while((time + timeout) > millis()) {
        while(esp8266.available()) {
                                       // The esp has data so display its output to the serial window
            char c = esp8266.read();   // read the next character.
            response += c;
        }
      }

      if (debug) { Serial.print('Returned: ' + response); }
      return response;
    }

And the console output is this:

    14880AT+RST

    OK
    14880
    "qXÑ{ÂB!É
    1Â±þ)ÒBÙa
    +ò“H!a5)�#)ÒÂia%YakN‘ J!ÐCÊ!�
    ÷þˆ2ô
    ready
    14880AT+CWJAP="xxxxxxwifi","xxxxxx123"

    OK
    14880AT+CIPMUX=1

    OK
    14880AT+UART_DEF=19200,8,1,0,0

    OK
    14880AT+CIPSTA_DEF="192.168.9.60","192.168.9.1","255.255.255.0"

    OK
    14880AT+CIPSERVER=1,80

    OK
    14880AT+GMR

    AT version:0.22.0.0(Mar 20 2015 10:04:26)
    SDK version:1.0.0
    compile time:Mar 20 2015 11:00:56

    OK
    14880AT+CIFSR

    +CIFSR:STAIP,"192.168.9.60"
    +CIFSR:STAMAC,"18:fe:34:9b:4e:68"

    OK
    Server is now running!

    returned: 689----------148804 HTTP/1.1
    Host: 192.168.9.60
    Connection: AT+CIPCLOSE=0

    0,CLOSED

    OK

What I really am wanting to do is have a way to send a 10 charater string to the arduino instead of the limited 3 numbers above. I just am not sure what i need to add/modify in order to make it see letters/numbers and only the first 10 that i send.

Any help would be great!

body:
      int retunedNum = (esp8266.read() - 48) * 100;       // get first number (example: 123.. this would be "1")
      retunedNum += (esp8266.read() - 48) * 10;           // get second number (example: 123.. this would be "2")
      retunedNum += (esp8266.read() - 48);                // get last number (example: 123.. this would be "3")

Your code always expects the pin number to have 3 digits.

In case of 13, it takes a space character as the last digit.
It reads charachters '1', '3' and ' '. Their ASCII codes are 49, 51 and 32. With this, the calculated number is

    (49 - 48) * 100 + (51 - 48) * 10 + (32 - 48) = 114.

With 6894, it just uses the first three digits and ignores the last.

For 1 or 2 digit long number you could just pad it with '0' character i.g. "013".

If you want to read an arbitrary string, you should replace the above code with this code:

    String retunedStr = "";
    for(;;) {
        char c = esp8266.read();
        if (c == ' ')
            break;
        retunedStr += c;
    }

And obviously replace

    Serial.print(retunedNum);

with

    Serial.print(retunedStr);

With this, you should only use letters (A-Z, a-z), numbers (0-9), dash (-) and an underscore (_) for the string.
If you use other characters, you could have problems with the URL character encoding.


message:
Sketch Upload to LinkIt ONE Timeout

I've just bought a new LinkIt ONE IoT prototyping board, and I'm having trouble getting started with it.

I'm working on a mac. I've installed the LinkIt ONE SDK onto my Arduino IDE as specified in the instructions here: http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd

When I go to upload my first sketch to my board, the sketch compiles and goes through uploading, but before it uploads, it stops uploading and the Arduino IDE perpetually tells me "Uploading...". When I look at the console below, it's telling me this:

    [txd] AT

    [txd] AT

    [medrv]: Time out call back

    [error] time out
    [medrv]: Kill timer, event is AT_TIMEOUT

I've read some forums about an issue similar to this on the MediaTek website, but they don't help with the issue on the Mac. The ability to use LinkIt ONE on a Mac is new only this month, so I believe if we come up with a fix for this issue, it will help lots of people in the future who have this similar problem.

body:
*Disclaimer: I do not have access to one of these devices to test this on.*

Section 3.4.1 of [LinkIt's developer's guide](http://labs.mediatek.com/fileMedia/download/5fed7907-b2ba-4000-bcb2-016a332a49fd) (which you linked to) seems to indicate that it is necessary to install COM port drivers on OS X before you can communicate with the board. The `[txd]` report is communication from your computer to the board, so it seems like you are never establishing a connection. The suggestions in the developer's guide are as follows:

> If you are using a LinkIt ONE development board on Mac OS X 10.10, then a USB driver is required to enable connectivity with and firmware updates on the LinkIt ONE development board. The OS X 10.10 built-in generic CDC ACM USB driver is not compatible with three ports available on the LinkIt ONE development board. The steps to install a custom driver to enable the BROM port for Firmware Updater are as follows:
>
> 1. Extract the content of the zip file available in LinkIt ONE SDK software’s **Driver** folder (see 2.3.2, “Installing LinkIt ONE SDK”) named `MacOS_USB_COM_Driver_BM_xxx.xx.x.zip`.
>
> 2. Run the installation package (`BMCDCACM_Driver_v115.05.0.mpkg`) and click **Next** to install it.
>
> 3. Wait until driver installation has finished, then restart your Mac.
>
> BROM USB driver installation is now complete and you have access to the MTK USB Serial ports.