message:
How to structure data for HTTP upload

I'm building a GPS tracker using an arduino nano, Adafruit Ultimate GPS breakout, a SD card slot and a SIM800L module.

So far everything works, the tracker uploads the data to a server as well as saving an extra copy to the SD card. The problem is now, that I don't really think that sending a HTTP request every cycle (gps data point) is very efficient and I would also like to have a way of storing information if there is no GPRS reception.

The idea is to save the GPS data to SD card and bulk send it out every 5 minutes or so.

What would be the best way to set up the data structure? I'm saving the deta in a csv style file:

    2016-8-2 22:23:44, 52.53251922, 13.31121666, 18.30, 7, 1.33;

Parsing that is not the problem, but rather how to keep track of what has been sent already and what not. I was thinking about Marking the lines that I sent with a # or something similar as first character.

The only problem I could see with that would be performance, since it could take a while to go though it every time once it's getting a bit larger.

Thanks!

Lukas

body:
The only alternative structure I can think of is, since you have a number of data fields to send, you could create a struct to contain all the fields. Write the gathered GPS data to the file in its raw format, with `file.write(&your_struct, sizeof(your_struct))` and read in a similar manner into a struct.

 - This will reduce the number of bytes written or read for any data point, and
 - Reduce the overall size of the file, compared to your original method, for the same number of GPS points.

The former improvement means there will be about 3 times as many GPS data points in a single block of data read from or written to the SD card, when compared to your current structure. Another more subtle advantage is that each data point occupies a known number of bytes in the file, making file navigation potentially easier. But you can only use this structure if you don't intend to view the CSV file with some spreadsheet program like MS Excel. You could, of course, very easily write your own PC program to parse the file and write to proper CSV. The Python `struct` module is very capable.

However, if you wish to continue with your current format, you can keep track of your current position in the file with `file.position()`; no need to use # as an indicator. You create 2 position variables, one to hold the position of the next line to be uploaded, `curr_pos`, and the other to hold the position of the end of the file for writing new data, `end_pos`. Initialize the former to 0.

 - You gather data as usual, and after 5 mins, you save the current file position to `end_pos` and seek to `curr_pos` with `file.seek()`.
 - You read a line from the file and send it to the server.
 - If it's sent successfully (use the return code), you update `curr_pos` with `file.position()` so that it's now pointing to the next line in the file to be uploaded and go to step 2.
 - Else if the upload fails perhaps due to service, you stop uploading and *don't* update `curr_pos`. You seek to `end_pos` with `file.seek()` and go to step 1.

You will, of course, use `available()` to know when you've hit the end of the file to stop uploading, or you can compare `curr_pos` with `end_pos` for equality, whichever's more direct for you.

This involves a lot of operations on the file and I/O operations don't come cheap with SD cards, both in terms of current drawn and latency. Depending on how often you collect data and if you don't need to view it on a PC, you might consider some other means of storage (SPI flash, perhaps) or use a more capable Arduino like the Mega with more RAM and store the data temporarily in an array before upload, granting you faster access by orders of magnitude and much reduced power drain in the long term, since each block of file data will be accessed only once.


sender: user

message:
Frequency generator

Can arduino generate the frequency with the resolution of 2 decimal places?
i.e. 100.12 Hz, 98.23Hz, 1.92Hz...

recently I need to generate a frequency to allow a stepper motor to move accordingly. But to ensure the stepper motor to functions normally, frequency must be generated , and it must be of 2 decimal places.

Can Arduino do that? Or is there any specific product that may generate frequency resolution as such?

sender: assistant

body:
The standard Arduino Uno is clocked at a nominal 16MHz, and has three timers: Timer0, 1 and 2. Timer1 uses a 16 bit counter (the others are 8 bit), and can be prescaled by 1, 8, 64, 256 and 1024. That lets you do _very_ precise timings (assuming an accurate clock!), simply by choosing different prescaler values and the relevant values.

Using your example rates, and assuming that you want a square wave (hence the "Halved" column), here are the calculations:

     Hertz Prescaler  Calculated      Halved  Actual Hz
    100.12         8  19976.02876548   9,988  100.120144173...
     98.23         8  20360.3787      10,180   98.231827112...
      1.92       256  32552.08333333  16,276    1.9200049...

Note that to do this, you need to program the Timer yourself - the standard Arduino library sets Timer1 to a default setting, which won't do what you want.


body:
I happened to do a similar analysis for Timer 1 on 328 / 32U4 clocked at 16MHz the other day and produced this plot:

[![Timer 1 Frequency Error Bound][1]][1]

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

This shows the frequency resolution as a proportion of frequency in red assuming optimal prescaling (the jumps are where prescale changes). The blue markers are realized frequency errors at frequencies drawn at the E12 series in magnitudes from 0 to 5. Unsurprisinly these are half or better than the resolution.

As a conclusion, you get a relative error of around 5e-5 for frequencies up to about 1kHz. After that you loose an order of magnitude per order of magnitude (which of course makes perfect sense).


body:
The other answers about the way you can configure the timers are very good, but Edgar Bonet's comment goes to the heart of the matter. Do you need accuracy?

Your example of 98.23Hz suggests that you want 98.23Hz and not 98.22Hz or 98.24Hz. That means therefore that you require an accuracy of around 1 in 10000 (0.01%).

> Can arduino generate the frequency ...

You haven't said *which* Arduino, but assuming one of the basic models, like the Uno, they come with a *resonator* which will have an accuracy of around 1%.

If the system clock is only good for 1% accuracy there isn't much point worrying about trying to get a frequency within 0.01%.


message:
Installing Pyserial

I will be running my CNC Via Arduino UNO R3, so i have found out that it runs on GRBL and that i need to load Python and Pyserial and a graphic interface.
Loaded Python 3.5.2, no problems, opened dos window typed Python, got the python >>> prompt, so far so good, downloaded/unzipped/copy/paste Pyserial  into c:/python35/lib/site-packages/pyserial.
at this point, at the dos prompt i type >>>python setup.py install. All i get is a syntax error.

I have included the dos script for comment

    Microsoft Windows [Version 6.1.7601]
    Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

    C:\Users\Goblin>python
    Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In
    tel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.

    >>> import os
    >>> os.getcwd()
    'C:\\Users\\Goblin'
    >>> os.chdir("/users/")
    >>> os.getcwd()
    'C:\\users'
    >>> os.chdir("/../")
    >>> os.getcwd()
    'C:\\'
    >>> os.chdir("/python35/lib/site-packages/pyserial/")
    >>> os.getcwd()
    'C:\\python35\\lib\\site-packages\\pyserial'
    >>> python setup.py install
      File "<stdin>", line 1
        python setup.py install
                   ^
    SyntaxError: invalid syntax
    >>>

This is about the 7th attempt.
I seem to be following the instruction correctly but it wont install ....HELP Please, this is so frustrating, what have I done wrong.
Thanks in advance
Doug

body:
not exactly related to Arduino but here it goes...

First check if you have pip installed:

    pip --version

**if not installed** go [here](https://pip.pypa.io/en/stable/installing/) and download the get-pip script.
then on directory where you saved get-pip run on console:

    python get-pip.py

this will install pip into your system which makes installation of packages in python way more easy.

if installed but not latest version ( at momment 8.1.2) do an upgrade before:

> On Linux or OS X:

    pip install -U pip

> On Windows:

    python -m pip install -U pip

after install pyserial using pip:

    pip install pyserial

**Did it work?**
If not, try:

    python -m pip install pyserial

**if it still doesn't work** install from source. Get the latest version [here](https://pypi.python.org/pypi/pyserial) extract it and in the dir where you extrated run:

    python setup.py install

PS: change to dir first, no need to do it inside python.


body:
I'm pretty sure that what you are trying to do is actually call 'python setup.py' within the python script itself. Which you cannot do. The easiest way to install pyserial is via pip like so. (Windows)

    python -m -U pyserial --upgrade

Now if you still want to use setup.py or you don't have pip installed. Make sure that you meet all of the package dependencies. Which in pyserial there are no others. Try exiting out of the python interpreter and just running

    python setup.py install

 In the same folder location as the extracted zip (use cd to change directories)


body:
Thanks All...by running the command at a std DOS prompt I was able to install the Pyserial.py file.
i have since seen comments that some of the 3.x.x series Python has glitches,(I am running Windows7). I have gone to 2.7 Python as a program i would like to use doesn't appear to run under 3.x.x   bCNC likes the earlier versions, not sure why, but it does run under 2.7  . for those interested JCNC, EFL CNC, Grbl Controller seem to run OK under 3.x.x


message:
Software Serial and multiple shields for Arduino Uno

I have a SIM900 GPRS/GSM Shield ([details here][1]) and I am looking to stack a GPS shield ([such as this one here][2]).

My question is: I believe that they both require software serial, also it says to use software serial on D7 and D8 for both. Is this possible on an Uno?

I am a bit confused at if software serial has to have these two specific pins, or if these are just what is chosen on schematics?

What would be the most effective way to stack these two shields so they don't interfere with each other?

EDIT: Using a gps shield such as [this][3] gives the option  of

> If you need to move the software serial port pins, they can be custom-routed to any other pin by cutting the solder jumpers between pins GPS-RX and D8 and/or GPS-TX and D9.

This isn't entirely clear to me, but am I right in thinking it means I can have multiple software serials on my Uno, just using different pins?

  [1]: http://linksprite.com/wiki/index.php5?title=SIM900_GPRS/GSM_Shield
  [2]: https://www.adafruit.com/product/1272
  [3]: https://www.sparkfun.com/products/13750

body:
SoftwareSerial can use any pins. That's the whole point of it. However, some shields are wired to use specific pins. If two shields try and use the same pins then you can't use them together. Not stacked, anyway. You will have to use flying leads, or physically alter the shield (cutting tracks, soldering in "bodge" wires) to use them together.

That said, though, you can only use ONE SoftwareSerial port reliably at a time. That means, regardless of what pins they use, you can't use two shields together that require pins other than 0 and 1 (hardware serial).

To use them both you will need a board with multiple hardware UART ports and modify the shields (as mentioned above) to use the correct pins for those UART ports.


message:
Simple IR Receiver code

Can I know a code for simple IR receiver. I using external trasmitter, and when the receiver (on arduino board) get the input (detect signal from transmitter), LED will be HIGH.

body:
Here is a library that might be able to help you out: https://github.com/cyborg5/IRLib/. Also a specific example of controlling a server from a sony remote control. https://github.com/cyborg5/IRLib/blob/master/examples/IRservo/IRservo.ino

I am slightly confused on what you mean 'get input'. So I am assuming an input from a button. Here is some pseudo code compiled from the IRservo example that might point you in the right direction.

    #include <IRLib.h>

    #define MY_PROTOCOL SONY
    #define BUTTON_0 0x90bca  //LED ON
    #define BUTTON_1 0x00bca  //LED OFF

    #define LED_PIN 13 //Pin to LED

    IRrecv My_Receiver(11);//Receive on pin 11
    IRdecode My_Decoder;

    void setup() { //Code to run once
      My_Receiver.No_Output();//Turn off any unused IR LED output circuit
      My_Receiver.enableIRIn(); // Start the receiver

      pinMode(LED_PIN, OUTPUT); //Set LED 13 to out
      digitalWrite(LED_PIN, LOW); //Start off in the off position
    }

    void loop() { //Code that runs forever
        if (My_Receiver.GetResults(&My_Decoder)) {
           My_Decoder.decode(); //Convert the values into types
           if(My_Decoder.decode_type==MY_PROTOCOL) { // Match the controller
              switch(My_Decoder.value) {
                case BUTTON_0:      digitalWrite(LED_PIN, HIGH); break; //Turn the LED on
                case BUTTON_1:      digitalWrite(LED_PIN, LOW); break; //Turn the LED off
              }
           }
         My_Receiver.resume(); //Wait for next input
        }
    }

This should theoretically work, but has never been tested. Now if you are just wanting any result to turn on the LED you might be able to do this

    void loop() { //Code that runs forever
        if (My_Receiver.GetResults(&My_Decoder)) {
            My_Decoder.decode();
            digitalWrite(LED_PIN, HIGH); //Turn the LED on
        }
        My_Receiver.resume(); //Wait for next input
    }

**Edit:**

A sample from getting text (Different library) from the receiver and printing it to the Serial Monitor. Link to library: https://github.com/z3t0/Arduino-IRremote

        #include <IRremote.h> //Link: https://github.com/z3t0/Arduino-IRremote

    #define IR_PIN = 11; //The data pin to the IR recv
    #define LED_DATA = 13; //Either the builtin LED or plug one in

    IRrecv irrecv(IR_PIN); //Start recv obj
    decode_results results;

    void setup()
    {
      Serial.begin(9600); //Start Serial at 9600 baud
      pinMode(LED_DATA, OUTPUT); //Set LED pin to out
      digitalWrite(LED_DATA, LOW); //Start recv data view pin in low
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        //We have recieved something... lets print it and turn on the LED
        digitalWrite(LED_DATA, HIGH);
        Serial.println(results.value, HEX); //Send line in ascii hex format
        delay(200); //Make the LED visible
        digitalWrite(LED_DATA, LOW); //Turn off data led
        irrecv.resume(); // Receive the next value
      }
    }

**Edit #2**

Since an image has been provided I believe this is what you want. To turn the ir data into a visible light... To do that is a little more tricky in just doing code. Here's an example that doesn't require any external libraries and will do what you want.

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

    #define TIMER_RESET  TCNT1 = 0
    #define SAMPLE_SIZE  64
    #defome LED_PIN 13

    int IRpin = 2;
    unsigned int TimerValue[SAMPLE_SIZE];
    char direction[SAMPLE_SIZE];
    byte change_count;
    long time;

    void setup() {
      Serial.begin(115200);
      Serial.println("Analyze IR Remote");
      TCCR1A = 0x00;          // COM1A1=0, COM1A0=0 => Disconnect Pin OC1 from Timer/Counter 1 -- PWM11=0,PWM10=0 => PWM Operation disabled
      // ICNC1=0 => Capture Noise Canceler disabled -- ICES1=0 => Input Capture Edge Select (not used) -- CTC1=0 => Clear Timer/Counter 1 on Compare/Match
      // CS12=0 CS11=1 CS10=1 => Set prescaler to clock/64
      TCCR1B = 0x03;          // 16MHz clock with prescaler means TCNT1 increments every 4uS
      // ICIE1=0 => Timer/Counter 1, Input Capture Interrupt Enable -- OCIE1A=0 => Output Compare A Match Interrupt Enable -- OCIE1B=0 => Output Compare B Match Interrupt Enable
      // TOIE1=0 => Timer 1 Overflow Interrupt Enable
      TIMSK1 = 0x00;
      pinMode(IRpin, INPUT);
      pinMode(LED_PIN, OUTPUT);
    }

    void loop()
    {
      Serial.println("Waiting...");
      change_count = 0;
      while(digitalRead(IRpin) == HIGH) {}
      TIMER_RESET;
      TimerValue[change_count] = TCNT1;
      direction[change_count++] = '0';
      while (change_count < SAMPLE_SIZE) {
        if (direction[change_count-1] == '0') {
          while(digitalRead(IRpin) == LOW) {}
          TimerValue[change_count] = TCNT1;
          direction[change_count++] = '1';
          digitalWrite(LED_PIN, LOW);
        } else {
          while(digitalRead(IRpin) == HIGH) {}
          TimerValue[change_count] = TCNT1;
          direction[change_count++] = '0';
          digitalWrite(LED_PIN, HIGH);
        }
      }
      Serial.println("Bit stream detected!");
      change_count = 0;
      time = (long) TimerValue[change_count] * 4;
      digitalWrite(LED_PIN, LOW)
      Serial.print(time);
      Serial.print("\t");
      Serial.println(direction[change_count++]);
      while (change_count < SAMPLE_SIZE) {
        time = (long) TimerValue[change_count] * 4;
        Serial.print(time);
        Serial.print("\t");
        Serial.println(direction[change_count-1]);
        Serial.print(time);
        Serial.print("\t");
        Serial.println(direction[change_count++]);
      }
      Serial.println("Bit stream end!");
      delay(2000);
    }

If you want a non code example check out the answer below. It is a great solution. Without needing any arduino.

best regards, David


body:
I know you want code.  However your question is how to light up an LED when an external remote control is transmitting.  This can be done with the following hardware:

Many ASK sensors integrate an IR photo sensor, AGC & PLL into a 3 pin package that has an appearance of a transistor.  Supply power and get back a signal when an ASK IR transmitter is detected.  Check the current capabilities of the ASK receiver, you might have to add a transistor to drive an LED.  No Arduino needed for detection.

Here is an example found on the web:

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

  [1]: https://i.stack.imgur.com/fR8Ku.gif


message:
Error when using buzzer and IR sensor

I am doing code for IR sensor. My problem is when I put this code (below) for buzzer, there will be error.

C:\Program Files\Arduino\hardware\arduino\avr\cores\arduino/Tone.cpp:536: multiple definition of `__vector_7'
IRremote\IRremote.cpp.o:

C:\Program Files\Arduino\libraries\IRremote/IRremote.cpp:312: first defined here
collect2: error: ld returned 1 exit status

      tone(buzzer, 4000); // Send 1KHz sound signal...
      delay(500);        // ...for 1 sec
      noTone(buzzer);     // Stop sound...
      delay(500);        // ...for 1sec

body: Both the IRRemote library and the tone command use the same timer. You can't use them both together without modifying one of them to use a different timer. And that means looking at the source code for them both.


message:
Parse HTTP Request Arduino

I am sending a HTTP Request to my WiFi module `http://192.168.4.1/STA/ID=HelloWorld/Pass=Testin123`

How can I parse above string in Arduino. First I need to check for `STA`, if it exists, continue to scan the string. Put Value of `ID`, in this case `HelloWorld` should be store in String data type `SSID` and Value of `Pass`, in this case `Testin123` should be store in String data type `Pass`.

How can achieve above using ARDUINO code! Please help.

body:
Your incoming string, as Gerben has mentioned, will actually be more like:

    GET /STA/ID=HelloWorld/Pass=Testin123 HTTP/1.1

My personal preferred method is to use `strtok()` to split the string up.  I'd use a two-pass method for this.

First split the string up into three parts - one GET, one the request, and the third the request type (though you don't need to use that for anything).  Assume the string is in C string `incoming`:

    char *get = strtok(incoming, " ");
    char *request = strtok(NULL, " ");
    char *rtype = strtok(NULL, " ");

The request is now pointed to by the `*request` pointer and the string has been sliced up in-place.  So now you can do something similar with the request, this time splitting on `/` instead of space:

    String SSID;
    String Pass;

    if (request != NULL) {
        char *part = strtok(request, "/");

        bool seenSTA = false;
        while (part) { // While there is a section to process...

            if (seenSTA) {
                if (!strncmp(part, "ID=", 3)) { // We have the ID
                    SSID = String(part + 3);
                } else if (!strncmp(part, "Pass=", 5)) { // We have the password
                    Pass = String(part + 5);
                }
            } else if (!strcmp(part, "STA")) {
                seenSTA = true;
            }

            part = strtok(NULL, "/");
        }
    }


message:
Connecting external mic to the Teensy

I have a Teensy 3.2 and the [Teensy audio board][1].

I was going to connect lavalier microphone to its audio jack but learned that it's only for output.
There are line-in pins though (see "Back Side" scheme). And MIC+GND pins, but these are for, ehm, radio parts microphones, I guess?

Being a complete novice I have no idea how to connect microphone jack (or audio connector) to line-in pins and whether I would need an amplifier between microphone and pins. If so then probably I just can't do it.

I would be grateful for detailed instructions.

  [1]: https://www.pjrc.com/store/teensy3_audio.html

body:
It is easier than I thought! I soldered audio jack to MIC+GND, inserted microphone in and it works!
And pretty well :-)
Cheap random lavalier model: Panasonic RP-VC201. I guess any consumer model will do.


message:
Arduino Serial library (Synchronous or Asynchronous?)

On an Arduino 101, I have this code running:

    void setup()
    {
     pinMode(2, INPUT);
     Serial.begin(9600);
    }

    int counter = 0;

    void loop()
    {
     Serial.print(millis()/1000);
     Serial.print("\t");
     Serial.print(counter);
     Serial.print("\t");
     Serial.println(digitalRead(2));
     counter++;
    }

A wire can be used to jump Pin2 between 3.3V and GND.

When running with the Serial Monitor on, I see the values increment at a rate where counter increases by the hundreds very quickly and steadily ticks through the thousands over time.

If I close Serial Monitor momentarily and re-open it, I notice that this counter value has increased dramatically (by the tens-of-thousands).  Another sign of this is when starting the program and waiting a moment to start the Serial Monitor.  As the Arduino 101 does not restart when the Serial Monitor is opened, I see a large initial value in the tens of thousands despite having just started the program.

My question is this: is the Serial library operating synchronously or asynchronously? I was led to believe that it was asynchronous; however, if that was the case, why should the Arduino execute any slower when the serial monitor is on?

While I understand that increasing baud rate will increase the speed at which counter increases, I still see the same dramatic increase in this code when the monitor is closed and then re-opened.

Another possibility I thought of was that maybe counter was being stored in a buffer and what I was seeing was not an up-to-date time or count.  To check this, the program prints the digitalRead value of pin2 as I swap the jumper between 3.3v and GND. This change in value was reflected instantaneously on the Serial Monitor, and I believe this means I am not seeing past data slowly being printed out to the monitor.

One last attempt at understanding what was going on was executing this code:

    void setup()
    {
     pinMode(2, INPUT);
     Serial.begin(9600);
    }

    int counter = 0;

    void loop()
    {
    counter++;
    if (counter00==0)
     {
      Serial.println(counter);
     }

In this example, counter can be seen ticking through quite fast, by the hundreds of thousands, which indicates that the program is capable of running very quickly until a print statement is made. The effect is notably less when baud rate is increased to something like 115200 but is that saying that baud rate is literally slowing the processing speed of the controller?

Any kind of explanation as to what exactly is going on would be very appreciated.

Thank You for your Time.

Source of Arduino being supposedly Asynchronous:
https://itp.nyu.edu/physcomp/lessons/serial-communication/serial-communication-the-basics/

body:
The Universal asynchronous receiver/transmitter (UART) is a chip that control the actual wires for serial communication. The UART operates independently and asynchronously.

As far as I know the UART (or USART) has a buffer, and the serial.print* functions will write to this buffer, and if it is full will block until the buffer has room. The UART will consume the buffer and transmit it over the wire. So your code will run full speed until the buffer is full then it will have to wait for the UART to make space.

> ... but is that saying that baud rate is literally slowing the processing speed of the controller?

When the UART's buffer becomes full, the Serial API has no choice but to wait for the buffer to empty so it can fill it again. This makes it appear as if the code is running synchronously; waiting on the buffer is essentially acting as a synchronization device. So yes a slow baud rate can slow the micro-controller down since the code is forced to wait for the UART even though it is asynchronous!

You may not notice any of the above effects, since even 9600, a relatively slow rate, is much faster than humans can read. 300 baud is approximately the rate at which humans can read comfortlably. If you repeat your experiments with a higher baud rate you should see the text fly past on the serial monitor much faster than at 9600; if you lower the speed to 300 (the lowest supported by the library) you should be able to read along, and see that things do go slower. The buffer on the UART is rather small, and even when slowing down to 300 baud, it might be difficult to see the buffering behavior.

When the serial monitor is closed the serial communications are still happening, the UART on the receiving side is receiving the data, but it gets dropped on the floor since no one is reading it. If you were to disconnect the serial wires at some point this should stall the sending UART which should cause the serial.print* functions to block (alternatively the UART could be configured to drop the data if it can't physically transmit it over the wire.)


body:
The Arduno 101 doesn't communicate to the PC using a UART. It uses CDC/ACM over USB, which *looks* like a UART to the PC.  But it isn't.

* USB sends packets of data, not individual characters
* It only sends if there is something to receive it at the other end
* There is no such thing as *baud rate* with USB.

Basically, when the CDC/ACM port has been opened by an application (e.g., the serial monitor) the Arduino 101 starts to send the data down the line. When the port is closed all data to be sent gets silently dropped by the Arduino since there is nowhere to send it to.

Hence when the port is closed it runs much faster since the data that would normally have to be packed into packets and sent down USB isn't. It's just thrown away.

----

To address your confusion:

You are misunderstanding the concept of synchronous and asynchronous with regards to serial. There are basically two types of serial communication: Asynchronous, where both ends have to (pretty precisely) agree on the speed of communication (baud rate), and synchronous, where one end tells the other end what the speed is by providing a discrete clock signal. UART (RS-232, RS-485, etc) is asynchronous. It sends at a specific rate and has to rigidly stick to that rate for the other end to be able to receive it properly.  SPI and I2C are synchronous - they both (as master) provide a clock signal to the receiving end (slave) and the receiver *synchronises* its reading and writing of data with that clock signal (hence *synchronous*).

You are confusing those concepts with another meaning of synchronous and asynchronous - terms that could better be used would be *parallel* and *sequential processing*. If something happens *in parallel* then two (or more) things happen at once. This is the case of the hardware UART where you submit characters to be sent to the buffer and they get transmitted out by the hardware separately to the sketch - in parallel. Sequential would mean that one thing has to happen after the other. If the UART behaved like that your program would stall every time you wanted to send a single character.

So UART processing happens in the background, in *parallel* to your sketch. So does USB data processing for CDC/ACM. These things are generally coupled with interrupts to allow the CPU to handle tasks such as placing more data in the buffer or storing data that has arrived somewhere that you can get to it.  Interrupts aren't strictly parallel, in that they do stall your program while they run, but they are kind of in a different thread, or *context*. So they appear to be parallel.


message:
nRF24L01+ packet loss caused by Arduino reading and communicating with sensors

I have 2 Arduinos communicating with each other. My problem is that one sends packets every 1.5-2 seconds but the other Arduino does sensor reading and data uploading with a Wifi module, which may take up to 5 seconds until the next time the nRF24L01+ is available to receive data.

This results in about 4 packet losses and if I am lucky sometimes 2. Is there any way that when the nRF24L01+ sends data, the other Arduino stops everything to get the data? Like a communication between these two Arduinos that will be open 24/7, so that the other Arduino can multitask (reading sensors and upload the data through wifi).

I am using the code from this [tutorial][1]. Here is a my problem in an image (I hope this helps you understand it). Thanks in advance. [![enter image description here][2]][2]

  [1]: https://www.youtube.com/watch?v=D40cgHyBLL4
  [2]: https://i.stack.imgur.com/oz1os.jpg

body:
You need to re-factor your program somewhat (I would imagine).  The nRF needs to be read *at the same time* as doing other things. That means interleaving it with your other operations.

There is a concept called a [finite state machine](https://en.wikipedia.org/wiki/Finite-state_machine) which is the best way of writing a complex program like this. The idea is that nothing ever *blocks*, it just changes states. And all the time other things can be happening, such as reading the nRF24L01+ module.

I have a little tutorial on the Finite State Machine here:

* https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/

If you use the Finite State Machine concept to run the reading of your sensors and the writing of data to the WiFi the nRF can then be polled constantly outside of the FSM constantly - maybe with an FSM of its own to deal with reception etc.

Things to remember:

* Avoid `delay()`, certainly for anything longer than a couple of ms.
* Avoid `while()`, `for()`, etc except for very short loops that finish quickly.
* Any operation that takes more than a few ms to complete should be broken down into a number of sub-operations and coded as separate states of the FSM.


body:
I see this is an old thread, but thought I'd chime in.

For an example implementation of a finite state machine, [there are libraries built for this][1] or you can use simple loop timers with if statements to "poll" sections of code instead of using ***ANY*** delays. Delays stop execution and waste your MCU time, preventing it from doing anything else, as already mentioned. Checking for wifi or serial messages can then execute with higher priority. An example pseudo-code would look like:

    int update_ms = 500;
    int last_update_ms;

    setup{

    last_update_ms = millis(); // or 0, to execute immediately

    }

    loop{

    if(millis() - last_update_ms >= update_ms){
        last_update_ms = millis();
        execute_thing();}

    check_for_wifi_msg();

    }

There are libraries that [do this essential behavior for you with more eloquence, as well, such as PollingTimer.][2] I'm often surprised this isn't given as tool early on when people learn Arduino/ MCU programming, or in example codes. It is easy and so powerful.

You could accomplish the same "finite state machine" functionality with a real-time operating system built for microcontrollers. I can recommend FreeRTOS as a user-friendly entry to this. This makes your single core machine work like a multi-core machine, with a task scheduler. You can define several continually running while loops that the RTOS thread handler then interleaves for consistent execution. You could have 1 thread for your RF and 1 thread for your WiFi, with set execution rates, and RTOS handles the rest, e.g. it will try to fit RF reads inside of the Wifi loop whenever it can find downtime. This will likely make your Wifi loop somewhat longer as a sacrifice.

You can get started with these:
[FreeRTOS Kernel Quick Start Guide][3]
[The FreeRTOS Reference Manual][4]

Other solutions, which I won't elaborate on here include using a multi-core chip, like a ESP32, or to make use of WiFi interrupts to break out of other execution. Though, I do not know if this is specifically supported on the nRF24L01+.

  [1]: https://github.com/twrackers/StateMachine-library
  [2]: https://github.com/hideakitai/PollingTimer
  [3]: https://www.freertos.org/FreeRTOS-quick-start-guide.html#page_top
  [4]: https://www.freertos.org/fr-content-src/uploads/2018/07/FreeRTOS_Reference_Manual_V10.0.0.pdf


message:
IR basic connection

Can I know how to change or connect from this circuit (three pin IR receiver) to two pin IR receiver because when I change the connection (3 pin to double pin), my arduino cannot receive the signal from transmitter.

I dont know because of my connection or because of there are different between tree and double pin IR receiver. Can anyone help me.

My code too long, so I just paste IR sensor for detect signal from transmitter.

    {
      indicator();
      irrecv.resume();
      while(1)  //-------loop M1
      {
          HM_1();
          if(irrecv.decode(&results) >0 || digitalRead(SBB) == HIGH )
          // if IR receiver detect signal or button pressed
          {
             indicator();
             break;
            //irrecv.resume();
          }//
          else
          {    //-------else "if(sensor 2)"
              //go back to else "if(sensor 1)"
          }//-------else "if(sensor 2)" end
          //nothing
        }//-------while end
    }

[![double pin][1]][1]

[![IR connection][2]][2]

  [1]: https://i.stack.imgur.com/aMd94.jpg
  [2]: https://i.stack.imgur.com/PCHh4.gif

body:
From what you have described, i think you are getting confused between the function of the two types. The 3 leg style is designed to receive coded pulses from remote controls (TV,Video, etc) where as the 2 leg is typically used, but not limited to, IR switching, where a signal is generated when the light path between the sender and receiver is broken with an opaque blade or similar or a beam is reflected back from an object as it passes. So trying to use the same code for the two types is provably where you are having problems.

Two example of this are [here][1] this uses a reflected IR beam where as [this][2] slot sensor is the break a beam type, often used in a limit or timing situation. One half of this is similar to the 2 leg diode you show.

It just depends on what situation you are using it in as to which is appropriate.

Without seeing your code, this is about as far as i can go, post your code so the forum can view it and make suggestions.

  [1]: http://www.ebay.com.au/itm/Car-Sensor-Obstacle-for-Arduino-IR-Infrared-Avoidance-Robot-NEW-Smart-Module-/331917171309?hash=item4d47ce1a6d:g:~5AAAOSwIgNXlAVO
  [2]: http://www.instructables.com/id/low-cost-air-flow-sensor/?ALLSTEPS


body:
To expand on Doug's answer:

There are two types of IR receiver. The two-pin one you have is basically a photodiode with infra-red filter. When infra-red light hits it the transistor gets biased and turns on. This is the most basic type you can get and is very hard to work with for anything other than simple on-off signals.

The second type is the IR receiver *module*. This contains a photodiode as above, but also contains extra circuitry. It receives IR light on the photodiode and filters it through a band-pass filter. A remote control sends a sequence of pulses of light which itself is further made up of high frequency pulses (36KHz square wave, for example). It's this high frequency pulsing that is allowed through the band-pass filter. The internal circuitry then turns these pulses of high frequency square waves into pulses of ON or OFF signals by low-pass filtering them to remove the high frequency component.

This latter type of receiver is far easier to work with for sending of data or commands from (eg) a remote control. But it can't detect a steady-state IR signal. The modulation and filtering means that a much weaker signal can be extracted from the background IR light meaning much greater distances can be achieved using much weaker transmission LEDs.

So while it is possible to use the former type with an Arduino you have to realise that the software required to do all the filtering and detection, as well as the extra hardware required to interface it, makes them considerably harder to use. That is why almost everyone uses the three-pin versions that do all that for you.

One thing to note with the three-pin versions: they have to match the carrier frequency of the transmitter. So a 36KHz transmitter has to be paired with a 36KHz receiver. Otherwise it won't be able to detect the signal. Just like a radio - it has to be tuned to the right band.


message:
What are the Ramps pins on my Arduino mega?

I've been working on a 3D printer and I've come to the last step, which is wiring it all up.

The 3D printer I'm making works ONLY with the Arduino Mega. No Ramps. If I need to get Ramps later, I will, but for now, can someone please help me understand which of the Ramps pin goes with which Arduino pin. For example, in the Repetier firmware, the code is like this:

    #define X_STEP_PIN         54
    #define X_DIR_PIN          55
    #define X_ENABLE_PIN       38
    #define X_MIN_PIN           3
    #define X_MAX_PIN           2

But Arduino doesn't have a 54 and a 55 pin. I've been googling this and I found that Ramps pins 54 - 69  are the same as pins A0 - A15 on the Arduino Mega.

I know this but not for the other pins...

Can someone please tell me the connection of all the Ramps pins to the Arduino pins?

Like: pin 54 on Ramps = A0 on Arduino. I need this for all of the pins.

body:
You are right, your have all the information in your question.

Pin 54 Refers to the Arduino PIN Number, nothing to do with RAMPS.
0-53 are the digital pins and the 54 is A0, etc.
So the pin numbers should go higher than 69, which is A15.


body:
You're very close to your answer.  Here are the specifics:

    Name      software pin  Mega2560 board label
    X_STEP_PIN    54         Analog A0
    X_DIR_PIN     55         Analog A1
    X_ENABLE_PIN  38         Digital 38
    X_MIN_PIN     3          PWM 3
    X_MAX_PIN     2          PWM 2

http://reprap.org/mediawiki/images/3/3f/Arduinomegapololushieldschematic.png shows the mapping.


message:
ESP8266 does not respond after changing baud rate to 9600

I have ESP8266 WiFi module and Arduino Mega Board connected. I use external 5 to 3.3 V regulator to power up the module. Common (-ve) line on the external power source and Arduino Mega GND is connected. Then I used 1K and 2K voltage divider for WiFi module RX and TX use as same. I am sure my circuit is well works.

Then I connect RX0-RX and TX0-TX. Then i put CH-PD to 3.3v

Then I opened the Arduino IDE and upload the Blink sketch. Done.. Then I opened Serial Monitor and set baud rate to 115200. Then power up the module. It gave me a lots of garbage values and ready. Fine.

Then I downloaded the FLASH_DOWNLOAD_TOOLS_v0.9.5. configure the 0x0000, 0x1000 and 0x7c000

 1. SPI speed = 40MHZ
 2. SPI mode = QIO
 3. FLASH size = 4Mbit
 4. 0x1000 = ai-thinker-0.9.5.2-9600.bin

Then O power off the module and connect GPIO0 to ground and again power on.

Then push start button. Then it downloaded to the chip. It worked. Done. Success fully uploaded. Then I again disconnected the GPIO0 and power on. Then I put AT and it results OK.

AT+GMR gives version 0.9.5 updated.done.

The problem was the module was responded for 115200 baud rate, not 9600. Then I:

    AT+IPR=9600

it gives me nothing.

Now I can't communicate with it at either 115200 or 9600 baud. No respond whatever baud rate I put. Sometimes I am having same garbage values.

body: This is a common issue. Using the `AT+IPR` command seems to brick the module. Try to re-flash your module, like you did the first time. If it works, use this command: ` AT+UART_DEF=9600,8,1,0,0 ` instead to change the baud rate.


message:
Pros and Cons of using a non-pointer class object

In this example I have an one object which uses a pointer and one object which does not.

    class MyClass {
      public:
        void myMethod() {
          // do nothing
        }
    };

    MyClass* mc1;
    MyClass mc2;

    void setup() {
      mc1 = new MyClass();
    }

    void loop() {
      mc1->myMethod();
      mc2.myMethod();
    }

Is one implementation better than the other? Why?

body:
In this situation, where you are just working with globals, the static declaration is preferred, although it makes little difference.

The static declaration (`MyClass mc2`) will reserve space in the BSS. The dynamic allocation (`mc1 = new MyClass()`) will allocate space on the heap at run time at the start of your sketch. Both are in pretty much the same area of RAM (the heap is directly above the static data area).

The only trouble starts to come when you want to free (`delete`) the object created with `new`. That can, over time, make a complete swiss-cheese mess of your heap which can cause memory allocation problems.

For that reason the dynamic method is shunned, but if all you ever do is allocate at the start and never deallocate then there is little practical difference between the two methods.


body: It depends on what you are trying to do and partly a matter of taste but I tend to take this one step further when the class corresponds to a specific hardware resource. In this case you can use static methods exclusively to guarantee a 1 to 1 correspondence. Templates come to rescue when you want to bind a specific physical instance of some finite resource (e.g. one of the timers) and this can be further refined using specialization and traits (each timer has different characteristics).


message:
No data from U-Blox Neo-6M

I'm trying to get Neo-6M module to work with Arduino Uno, but it just isn't transmitting any data. It is getting 3.3V.
I've tried measuring the Amps and I got zero, so I'm afraid that the module could be broken.

Neo-6M wiring:
![gps module wiring](https://i.stack.imgur.com/dY9P8.jpg)
Arduino wiring (power):
![arduino power wiring](https://i.stack.imgur.com/ABrFk.jpg)
Arduino wiring (data):
![arduino data wiring](https://i.stack.imgur.com/nHuyf.jpg)

Arduino code:

    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>
    /*
       This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
    */
    static const int RXPin = 4, TXPin = 3;
    static const uint32_t GPSBaud = 9600;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    // The serial connection to the GPS device
    SoftwareSerial ss(RXPin, TXPin);

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

      Serial.println(F("DeviceExample.ino"));
      Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
      Serial.print(F("Testing TinyGPS++ library v. "));     Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println(F("by Mikal Hart"));
      Serial.println();
    }

    void loop()
    {
      // This sketch displays information every time a new sentence is correctly encoded.
      while (ss.available() > 0)
        if (gps.encode(ss.read()))
          displayInfo();

      if (millis() > 5000 && gps.charsProcessed() < 10)
      {
        Serial.println(F("No GPS detected: check wiring."));
        while(true);
      }
    }

    void displayInfo()
    {
      Serial.print(F("Location: "));
      if (gps.location.isValid())
      {
        Serial.print(gps.location.lat(), 6);
        Serial.print(F(","));
        Serial.print(gps.location.lng(), 6);
      }
      else
      {
        Serial.print(F("INVALID"));
      }

      Serial.print(F("  Date/Time: "));
      if (gps.date.isValid())
      {
        Serial.print(gps.date.month());
        Serial.print(F("/"));
        Serial.print(gps.date.day());
        Serial.print(F("/"));
        Serial.print(gps.date.year());
      }
      else
      {
        Serial.print(F("INVALID"));
      }

      Serial.print(F(" "));
      if (gps.time.isValid())
      {
        if (gps.time.hour() < 10) Serial.print(F("0"));
        Serial.print(gps.time.hour());
        Serial.print(F(":"));
        if (gps.time.minute() < 10) Serial.print(F("0"));
        Serial.print(gps.time.minute());
        Serial.print(F(":"));
        if (gps.time.second() < 10) Serial.print(F("0"));
        Serial.print(gps.time.second());
        Serial.print(F("."));
        if (gps.time.centisecond() < 10) Serial.print(F("0"));
        Serial.print(gps.time.centisecond());
      }
      else
      {
        Serial.print(F("INVALID"));
      }

      Serial.println();
    }

body:
It isn't enough to power the module with 3.3V. You also have to level-shift the Arduino's 5V TX signal to 3.3V that is acceptable by the GPS module's RX pin, using a 1:2 voltage divider.

[![Converter][1]][1]

You should also know that the Arduino's 3.3 V pin can't source more than 50 mA; your module's current draw may sometimes exceed this limit (max is 67 mA). Instead, connect the Arduino's 5 V pin (which can source up to 500 mA) to the VCC of the GPS module through an LM1117T 3.3 V regulator:

[![Regulator][2]][2]

The input goes the Arduino 5V pin and the output goes to the NEO-6M VCC. Connect all GNDs together.

Then run a basic sketch like this:

    #include "SoftwareSerial.h"

    SoftwareSerial gps(4,3);

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

    void loop(){
      while (gps.available())
        Serial.write(gps.read());
    }

This will basically make the Arduino grab any NMEA data sent by the NEO-6M and forward it to your PC's serial monitor. If you receive legible data, it means you've established comms with the module. You can then upload your original sketch.

  [1]: https://i.stack.imgur.com/CBwwb.png
  [2]: https://i.stack.imgur.com/QcsNT.png


body:
I run my board from the 5v Arduino tap as it has a 3.3v low drop off voltage regulator on board. So my belief is that you should also tap off the Arduino boards 5v supply.

[![Neo-6 Arduino board components][1]][1]

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

Mine draws about 60ma from the Arduino board. The device should get a fix, then start transmitting over the tx line.  Indicated by the 'Position Fixed' led indicator on board, flashing once a second (at 9600 baud.)

Good luck, keep in mind that these boards are only about $7.50 on Amazon, order a couple for peace of mind. :)


message:
Talking to Eurotherm 2416 temperature controller over modbus rs232

I am trying to implement the modbus library written by smarmengol to read process values and to set new setpoints (e.g. temperature) on a Eurotherm controller. The Arduino sketch looks like this:

    /**
     *  Modbus master example 2:
     *  The purpose of this example is to query several sets of data
     *  from an external Modbus slave device.
     *  The link media can be USB or RS232.
     *
     *  Recommended Modbus slave:
     *  diagslave http://www.modbusdriver.com/diagslave.html
     *
     *  In a Linux box, run
     *  "./diagslave /dev/ttyUSB0 -b 9600 -d 8 -s 1 -p none -m rtu -a 1"
     *  This is:
     *   serial port /dev/ttyUSB0 at 9600 baud 8N1
     *  RTU mode and address @1
     */

    #include <ModbusRtu.h>
    #include <SoftwareSerial>

    SoftwareSerial mySerial (3,5);

    uint16_t au16data[16]; //!< data array for modbus network sharing
    uint8_t u8state; //!< machine state
    uint8_t u8query; //!< pointer to message query

    /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  u8serno : serial port (use 0 for Serial)
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
    Modbus master(0); // this is master and RS-232 or USB-FTDI

    /**
     * This is an structe which contains a query to an slave device
     */
    modbus_t telegram[2];

    unsigned long u32wait;

    void setup() {
      // telegram 0: read registers
      telegram[0].u8id = 1; // slave address
      telegram[0].u8fct = 3; // function code (this one is registers read)
      telegram[0].u16RegAdd = 1; // start address in slave
      telegram[0].u16CoilsNo = 1; // number of elements (coils or registers) to read
      telegram[0].au16reg = au16data; // pointer to a memory array in the Arduino

      // telegram 1: write a single register
      telegram[1].u8id = 1; // slave address
      telegram[1].u8fct = 6; // function code (this one is write a single register)
      telegram[1].u16RegAdd = 2; // start address in slave
      telegram[1].u16CoilsNo = 250; // (Setpoint) number of elements (coils or registers) to read
      telegram[1].au16reg = au16data+4; // pointer to a memory array in the Arduino

      Serial.begin(9600);
      master.begin( &mySerial, 9600); // baud-rate at 9600

      master.setTimeOut( 5000 ); // if there is no answer in 5000 ms,roll over
      u32wait = millis() + 1000;
      u8state = u8query = 0;
    }

    void loop() {
      switch( u8state ) {
      case 0:
        if (millis() > u32wait) u8state++; // wait state
        break;
      case 1:
        master.query( telegram[u8query] ); // send query (only once)
        u8state++;
     u8query++;
     if (u8query > 2) u8query = 0;
        break;
      case 2:
        master.poll(); // check incoming messages
        if (master.getState() == COM_IDLE) {
          u8state = 0;
          u32wait = millis() + 1000;
        }
        break;
      }
       Serial.print(au16data[O]);

      au16data[4] = analogRead( 0 );

    }

I can read process values with telegram[0] very well (temperature and/or setpoint), but I cannot change the setpoint with telegram[1]. If I run the code, it puts the current temperature to serial monitor but resets manually changed setpoints to zero. Where is the error? Should I write the value for the setpoint as HEX or DEC? What does the last command do actually?

Thank you!

body:
You could also take a look at this github project:
https://github.com/ukos-git/arduino-eurotherm2416

It is specifically designed for the purpose you ask for.
It basically includes Module named Temperature and a possibility to set or read it:

    Temperature.set(100)
    t = Temperature.getTemperature()

Look at https://github.com/ukos-git/arduino-eurotherm2416/blob/master/app/app.ino.


message:
Building an AtMega328p from Transistors

I'm a little new to circuitry, and the Arduino in itself!

From what I know, I think that it might be possible to actually build one (the processor itself, of course) from transistors. This isn't a practical question, of course, but it would be an excellent learning opportunity.

Would it be actually possible to go through with such a project (Even without EEPROM)?

If so, how would it be completed?

Thank you!

body:
Yes, it is possible - after all, the Arduino is essentially just a bunch of incredibly tiny transistors. Early computers, before ICs were invented, were built from transistors. Before that it was valves. Before that it was relays. All just, at the end of the day, switches.

Would it be a practical project? Not really, although someone has done it (not for the AVR CPU, but the concept is the same): http://www.megaprocessor.com/

How would you start? Well, first off you'd create the basic building blocks of a CPU, which is logic gates. There are two basic ones that can be combined together to make any other gate: the NAND gate and the NOR gate. You'd pick one of those and put lots of them together to make the basic sections of the CPU. Then those blocks connect together to form the CPU. More logic gates go together to make the IO functionality, memory, interfaces, etc.

Basically:

* Transistors combine to make NAND gates (or NOR gates if you prefer that form)
* NAND (or NOR) gates combine to make complex gates.
* Complex gates combine to make logic functions
* Logic functions combine to make logic blocks (like the ALU)
* Logic blocks combine to make the CPU


body:
Why not? Atmel did it.  But if you mean by soldering up discretes...

In the mid 70s the Zilog Z80 had 8,500 transistors; a couple of years later, the Intel 8088 had 29000(source: [Wikipedia)][1]. Neither of those had on-chip memory. The AtMega 328p has 2K of RAM and 1K of EEPROM on chip, so factor in for those and their drivers. At 20 MHz it will probably be fun 1) keeping signals where they belong; and 2) keeping the wire runs short enough and suitably arranged that capacitance doesn't slow and distort the signals to unusability.

  [1]: https://en.wikipedia.org/wiki/Transistor_count


body:
While it is possible, you will have to spend a lot of money and a lot of time. I think about thousends of dollars and months of work. Even when accomplished you will have learned more about electronics than about the ATmega328P. In order to accomplish, you will also have to ask Atmel to hand you over the schematics to get the inner working right. I highly doubt they will aggree since it is not Open Hardware.

I highly discourage you to do that. Instead I suggest you start with an Arduino UNO and discover the capabilities and then go a step further and use a bare ATmege328P.


body:
I do not think you could build an ATmega328P out of discrete parts: you
would need floating-gate transistors for implementing the flash, and
these do not seem to be available as discretes.

If you forgo the flash (or replace it with RAM or ROM), then it should
in principle be possible. This processor, however, is probably not a
good choice for such a project. From [the discussion][] linked to by
Mikael Patel, it seems you would need something like 80 K
transistors for the core alone, and much more if you include the RAM and
the peripherals. It would be a daunting task to assemble all this by
hand. For comparison, the [Megaprocessor][]1 as about
42 K transistors total (core + RAM + LED drivers).

If you want to pursue such a project, I recommend you target a simpler
CPU. The [MOS 6502][] may be a good choice. This CPU, which was very
popular in the late 70s and early 80s, has “only” 3,510 transistors and
is well documented. See for example the resources at [visual6502.org][].
They have an amazing [online transistor-level simulator][] built from
the actual layout of the chip.

1Thanks Majenko for the link

[the discussion]: https://www.embeddedrelated.com/showthread/comp.arch.embedded/14362-1.php

[Megaprocessor]: http://www.megaprocessor.com/
[MOS 6502]: https://en.wikipedia.org/wiki/MOS_Technology_6502
[visual6502.org]: http://www.visual6502.org/
[online transistor-level simulator]: http://www.visual6502.org/JSSim/


body:
The ATmega128 have 800000 transistors. (+-200000 transistors)
So If you want to take some transistors and breadboards and build an ATmega128p
first count the money for transistors (if 1 transistor costs 0.01€ then 800000 x 0.01 = 8000€ and the breadboards is much more expensive than transistors!)


body:
> Would it be actually possible to go through with such a project (Even without EEPROM)?

yes.

> If so, how would it be completed?

the easiest would be to find or write a soft-core for AVR on a fpga. Get the logic blocks for that softcore , and then implement those logic blocks with transistors.

Before you set out actually doing it, however, check if you have enough of space or bank account (for the electric bills).


body: Try to build out the entire thing inside a simulator instead of buying 10s of thousands of transistors and several other components....less messy and gets the job done at almost no expense


message:
Using two software serial - two UART

I have ATMega328p chip, and I have HC-06 on pin A5, A4 (RX, TX) and I have another device on pin 10, 9 (RX,TX).

I want to be able to send some command on BT via Bluetooth Terminal and pass raw (exact) command to that device unchanged just to log on my computer (on my serial monitor) incoming command from BT and to log the response from device the same way on serial monitor and pass unmodified to HC-06.

How can I do that?

I tried by using "listen()" method but sometimes I get some weird character while I'm transferring\reading data, so not sure how to do this.

All baud rates are 9600.

body:
> How can I do that?

You can't.

It is impossible to use two SoftwareSerial ports together. Simply because while you are writing to one port everything else stops. Interrupts are disabled, and receiving requires interrupts. So anything that arrives while you are sending will either be lost or corrupted.

The only solution is to use a board with multiple hardware UARTs like the Mega or any of the more powerful alternatives to Arduino such as chipKIT or Teensy.


body:
You can have high-speed debugging by utilizing either I2C or SPI to send to a second Arduino. That second Arduino can be devoted to receiving debugging information and passing it on (via serial to your PC).

I describe the process [here](http://www.gammon.com.au/forum/?id=11329).

The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.

Example code:

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

    // make true to debug, false to not
    #define DEBUG true

    #include <SPI.h>

    // conditional debugging
    #if DEBUG

      #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
      #define Trace(x)      SPIdebug.print   (x)
      #define Trace2(x,y)   SPIdebug.print   (x,y)
      #define Traceln(x)    SPIdebug.println (x)
      #define Traceln2(x,y) SPIdebug.println (x,y)
      #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

      class tSPIdebug : public Print
      {
      public:
        virtual size_t write (const byte c)
          {
          digitalWrite(SS, LOW);
          SPI.transfer (c);
          digitalWrite(SS, HIGH);
          return 1;
          }  // end of tSPIdebug::write
      }; // end of tSPIdebug

      // an instance of the SPIdebug object
      tSPIdebug SPIdebug;

    #else
      #define beginDebug()  ((void) 0)
      #define Trace(x)      ((void) 0)
      #define Trace2(x,y)   ((void) 0)
      #define Traceln(x)    ((void) 0)
      #define Traceln2(x,y) ((void) 0)
      #define TraceFunc()   ((void) 0)
    #endif // DEBUG

    long counter;
    unsigned long start;

    void setup() {
      start = micros ();

      beginDebug ();
      Traceln (F("Commenced device-under-test debugging!"));
      TraceFunc ();  // show current function name

    }  // end of setup

    void foo ()
      {
      TraceFunc (); // show current function name
      }

    void loop()
    {

      counter++;
      if (counter == 100000)
      {
        Traceln (F("100000 reached."));
        Trace (F("took "));
        Traceln (micros () - start);
        counter = 0;
        foo ();
      }  // end of if

    }  // end of loop

The other Arduino (which receives the debugging information) simply echoes it to Serial:

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

    char buf [1000];
    volatile int inpoint, outpoint;

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

      Serial.println ();
      Serial.println (F("Commencing debugging session ..."));
      Serial.println ();

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

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

      // now turn on interrupts
      SPCR |= bit (SPIE);

    }  // end of setup

    // SPI interrupt routine
    ISR (SPI_STC_vect)
    {
    byte c = SPDR;  // grab byte from SPI Data Register
    int next = inpoint + 1;  // next insert point

      // wrap-around at end of buffer
      if (next >= sizeof buf)
        next = 0;

      if (next == outpoint)  // caught up with removal point?
        return;  // give up

      // insert at insertion point
      buf [inpoint] = c;
      inpoint = next;  // advance to next

    }  // end of interrupt routine SPI_STC_vect

    void loop (void)
    {
      // insertion and removal point the same, nothing there
      noInterrupts ();  // atomic test of a 16-bit variable
      if (outpoint == inpoint)
        {
        interrupts ();
        return;
        }
      interrupts ();

      // display anything found in the circular buffer
      Serial.print (buf [outpoint]);

      noInterrupts ();
      if (++outpoint >= sizeof buf)
        outpoint = 0;  // wrap around
      interrupts ();

    }  // end of loop

---

SPI is quite fast, so the overhead of doing the debugging should be slight. The receiving end can batch up the debugging information (up to a point which is about 1000 characters) and then send it to your PC via Serial.

---

I made a library out of the relevant code. The library is available from:

<http://gammon.com.au/Arduino/SPI_Debugging.zip>

Example using the library:

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

    // make true to debug, false to not
    #define DEBUG true

    #include <SPI.h>
    #include <SPI_Debugging.h>

    long counter;
    unsigned long start;

    void setup() {
      start = micros ();

      beginDebug ();
      Traceln (F("Commenced device-under-test debugging!"));
      TraceFunc ();  // show current function name

    }  // end of setup

    void foo ()
      {
      TraceFunc (); // show current function name
      }

    void loop()
    {

      counter++;
      if (counter == 100000)
      {
        Traceln (F("100000 reached."));
        Trace (F("took "));
        Traceln (micros () - start);
        counter = 0;
        foo ();
      }  // end of if

    }  // end of loop

---

There is a similar library for I2C debugging:

<http://gammon.com.au/Arduino/I2C_Debugging.zip>

Example of doing I2C debugging:

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

    // make true to debug, false to not
    #define DEBUG true
    const byte SLAVE_ADDRESS = 100;  // which address debugging goes to

    #include <Wire.h>
    #include <I2C_Debugging.h>

    long counter;
    unsigned long start;

    void setup() {
      start = micros ();

      beginDebug ();
      Traceln (F("Commenced device-under-test debugging!"));
      TraceFunc ();  // show current function name
    }  // end of setup

    void foo ()
      {
      TraceFunc (); // show current function name
      }

    void loop()
    {

      counter++;
      if (counter == 100000)
      {
        Traceln (F("100000 reached."));
        Trace (F("took "));
        Traceln (micros () - start);
        counter = 0;
        foo ();
      }  // end of if

    }  // end of loop

---

All of the examples illustrate using a `#define` to turn the debugging output on or off, so you can leave the debugging prints there in case things go wrong, but with debugging disabled they won't have any penalty.


message:
Can't display text on LCD 1602

Today I tried to display some text with my Arduino UNO and a LCD 1602A screen. I did find some schemas online, but I cannot get any character or "black boxes" on the display.

I connect wires like that :
Pin 1 : GND
Pin 2 : +5V
Pin 3 : 50K Pot.
Pin 4 : Pin 7 from Arduino
Pin 5 : GND
Pin 6 : Pin 6 from Arduino
Pin 11 : Pin 5 from Arduino
Pin 12 : Pin 4 from Arduino
Pin 13 : Pin 3 from Arduino
Pin 14 : Pin 2 from Arduino
Pin 15 : +5V
Pin 16 : GND

You can see my setup here : [https://i.stack.imgur.com/u32sj.jpg][1]

The LCD screen is lighten up, but nothing else appears. Pot. is working (increase or decrease light). I tried to change the LCD with another, but both are not working. I tested some many code, here an example :

    /*
      LiquidCrystal Library - Hello World

     Demonstrates the use a 16x2 LCD display.  The LiquidCrystal
     library works with all LCD displays that are compatible with the
     Hitachi HD44780 driver. There are many of them out there, and you
     can usually tell them by the 16-pin interface.

     This sketch prints "Hello World!" to the LCD
     and shows the time.

      The circuit:
     * LCD RS pin to digital pin 12
     * LCD Enable pin to digital pin 11
     * LCD D4 pin to digital pin 5
     * LCD D5 pin to digital pin 4
     * LCD D6 pin to digital pin 3
     * LCD D7 pin to digital pin 2
     * LCD R/W pin to ground
     * LCD VSS pin to ground
     * LCD VCC pin to 5V
     * 10K resistor:
     * ends to +5V and ground
     * wiper to LCD VO pin (pin 3)

     Library originally added 18 Apr 2008
     by David A. Mellis
     library modified 5 Jul 2009
     by Limor Fried (http://www.ladyada.net)
     example added 9 Jul 2009
     by Tom Igoe
     modified 22 Nov 2010
     by Tom Igoe

     This example code is in the public domain.

     http://www.arduino.cc/en/Tutorial/LiquidCrystal
     */

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("hello, world!");
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

Do you have an idea ? Thanks !

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

body:
Wiring on the photo and description you provided are not consistent. On the photo, LCD-RS (PIN 4) is connected to `D12` and LCD-E (PIN 6) is connected to `D11`?

If so, initialization must be `LiquidCrystal lcd(12, 11, 5, 4, 3, 2);`


body: I realize that your question is based around using multiple connections to the arduino, however if you wish to simplify the setup/operation have a good look into I2C interface, this only uses 2 pins SDA and SCL to operate, you can get an interface board on Ebay for $1.00....just a thought.


message:
pH ORP sensor esp12 esp82666

I need to know if there is a sensor that mesure pH and ORP, I have already googled about this type of sensor but i found only AtlasScientific that commercialise this kind of sensor

thanks

body:
Yes there are lots.  You might try search for "Arduino PH Sensor" and "Arduino ORP sensor" you'll get a lot more hits for Arduino than ESP8226.
This might be useful:
http://www.instructables.com/id/ORP-pH-Temperature-Data-Logger/?ALLSTEPS


message:
Uno R3's a4 and a5 not working after installing itead SD Shield 3.0

I'm working on a data logging project and would like to use all six analog inputs on my Arduino Uno R3.  I've been able to get everything working, including writing to the SD card.  However, with the shield installed I'm getting junk readings from a4 and a5.  They work fine without the shield.

body:
The shield has pull-up resistors for I2C/TWI on pins A4 and A5. Special care (resistor bridge) needs to be taken if using these as analog pins. Please see the schematics for more details.

https://www.itead.cc/wiki/images/4/46/Sch_sd_shield_3.0.pdf

Cheers!


message:
Arduino Saint Smart Chapter 7 Tri Color Module

I am very new to Arduino, I bought a starter's kit and I am working with the user manual that is available. I am in chapter 6 Tri Color Module

I am using the following code:

    // Defining the LED driver pins and some other
    // variables.
    const int numLEDs = 3;

    int blueLEDPin  = 3;
    int greenLEDPin = 4;
    int redLEDPin   = 5;
    int ledPin[3];
    int ledPinIndex = 0;

    // the setup routine runs once when you press reset:
    void setup() {

      Serial.begin(9600);

      // initialize the digital pin as an output.
      ledPin[0] = blueLEDPin;
      ledPin[1] = greenLEDPin;
      ledPin[2] = redLEDPin;

      for (int i=0; i < numLEDs; i++)
         pinMode(i, OUTPUT);

    }

    // the loop routine runs over and over again forever:
    void loop() {

      digitalWrite(ledPin[ledPinIndex%numLEDs], HIGH);
      delay(1000);
      Serial.println(ledPinIndex%numLEDs);
      delay(2000);
      digitalWrite(ledPin[ledPinIndex%numLEDs], LOW);

      ledPinIndex++;
    }

My problem is that in the setup() method where the following code is

    for (int i=0; i < numLEDs; i++)
             pinMode(i, OUTPUT);

From my understanding pinMode OUTPUT is use to send power out of the specific pin. As the code displays pin 3, 4, and 5 are used but the above code is setting pinMode for 0, 1, 2. Is this write? And even if I comment out the two lines up my project no differently as to the previous code.

Can someone verify if the above code is correct, or should it be setting pinMode for 3, 4, and 5.

body:
This line `pinMode(i, OUTPUT);` should probably be replaced by `pinMode(ledPin[i], OUTPUT);`
Otherwise it won't make sense.


message:
Help understanding SoftwareSerial recv() and PCINT

In the SoftwareSerial library, I see the beginning of recv() as follows

    void SoftwareSerial::recv()
    {

    #if GCC_VERSION < 40302
    // Work-around for avr-gcc 4.3.0 OSX version bug
    // Preserve the registers that the compiler misses
    // (courtesy of Arduino forum user *etracer*)
      asm volatile(
        "push r18 \n\t"
        "push r19 \n\t"
        "push r20 \n\t"
        "push r21 \n\t"
        "push r22 \n\t"
        "push r23 \n\t"
        "push r26 \n\t"
        "push r27 \n\t"
        ::);
    #endif

      uint8_t d = 0;

      // If RX line is high, then we don't see any start bit
      // so interrupt is probably not for us
      if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
      {

This comment seems to be testing for if the pin change was from low to high, or high to low.  If you are using inverse logic - where the line is held high, and start bits are low - then a call to rx_pin_read() should return 0.

This doesn't seem correct.  In inverse logic the line is held high and a drop indicates a start bit.

Is the SoftwareSerial library ignoring the start bit and relying on some kind of return to zero break between the start bit and any subsequent bits?

It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

[![typical ttl ][1]][1]

  [1]: https://i.stack.imgur.com/4DOst.gif

body:
> This doesn't seem correct. In inverse logic the line is held high and a drop indicates a start bit.

No, in inverse logic (for a UART) the line is held LOW and a rise indicates a start bit. The diagrams you show in your question show that UART communication normally is HIGH with LOW for a start bit.

> It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

The PCINT is only used to identify the falling (or rising in the case of inverse logic) edge of the start bit. From then on it samples at pre-defined periods to read each bit. Accurate timing is needed for that, so assembly code is used to give precise delays (see `tunedDelay()`). Once the whole 10-bit packet has been received the interrupt handler finishes and control is returned to the main thread again. The PCINT is then free to look for the next start bit.


message:
WiFi Password Safety

Are there any best practices regarding password safety?  The following is taken from a wifi tutorial sketch.

    #include <SPI.h>
    #include <WiFi.h>

    char ssid[] = "yourNetwork";      // your network SSID (name)
    char pass[] = "secretPassword";   // your network password
    int keyIndex = 0;                 // your network key Index number (needed only for WEP)

While I accept that the tutorial is there for learning how to use the shield, I would assume hard coding the password into the sketch leaves this open to attackers.  Is this actually the case?  If so, are there any strategies to harden the sketch, for example with encrypted storage?

I am a relative newbie with physical computing and Arduino, so sorry if I am overlooking something obvious.

body:
You're actually entering into a very tricky and difficult area.

Yes, having a plain text password in your sketch is a risk. It is stored in flash as plain text. If an attacker can gain access to the contents of the flash through some means (whatever they may be) then they could obtain that WiFi password.

You would think that encrypting the password would be the answer, but that's not the case. The problem with an encrypted password like this is it has to be decrypted to use it. That means that both the encrypted password and the encryption key are both stored together in flash. If you can get one you can get the other, and thus the encryption is null and void.  Encryption security relies on keeping the encrypted data and the key used to encrypt/decrypt it completely separate. After all, you don't leave the key to your house in the front door lock when you go out, do you? It's exactly the same.

So what do you do?

Well, there's lots of different ways of looking at security. In this case there is one specific viewpoint that works best:

# Security Through Obscurity

Your system is (pretty much) unique. Nobody but you knows just what it does and how it does it, or how you interact with it. It's not obvious to the casual observer just what it is or what could be done with it. That means that they won't know how to break in to it.

The majority of use of vulnerabilities in systems rely on those systems being ubiquitous - that is, all over the place; easy to obtain. In short, easy to find out what they are, how they work, and even reverse engineer them to a certain extent. Attackers aren't going to be able to do that with your system, since you are the only person in the world with it.

However, it's far from perfect, and you shouldn't rely *only* on Security Through Obscurity.

Simple obfuscation of the password (not actual encryption, but just storing it in a way that isn't obvious) can help, since it isn't then easy to see where in a memory dump the password would be. Splitting it up and scattering it around the place, too, can be useful.

Basically there is no simple answer, other than *make it as hard for an attacker to find sensitive things as possible* and *don't tell anyone what you have done to hide it* ;)


body:
Unfortunately, I don't have a precise answer to your question currently, but I would like to warn you about the Security Through Obscurity approach proposed by Majenko.
This approach may be reasonable for something very homemade, but it is strongly discouraged by researchers and experts.

For instance, if you have a look at the [Guide to General Server Security](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-123.pdf) you will read between the "Server Security Principle":

>
> Open Design—System: security should not depend on the secrecy of the implementation or its components.
>

So, try always to use a standard approach if you can.


message:
Atmega328p - PCB ISP pins for bootloader and sketch upload

I want to design my PCB with Atmega328p chip on it and I want to be able to burn Bootloader and sketch after that while everything is soldered on the PCB. So my question is, what would be the best way to do that? My current idea is to leave extra pins for burning a Bootloader, and to leave also extra pins for uploading the sketch, and to "unplug" other stuff connected on these pins (for example on hardware UART) by adding\removing jumpers.

I'm pretty new to all this stuff, so I'm not quite sure what's the best approach.

body:
Realistically, you should design ATmega boards to support both ISP and bootloader pins.  The logic is simple:

- Unless you buy pre-programmed chips, or have a programming fixture, you will need ISP either to load the firmware itself, or to load a bootloader.

- Even if you plan to use only ISP for programming, it is still worth providing external connections to the UART pins for interacting with firmware during development; generally with ATmega-based Arduinos you do not have a breakpoint debugger, so debug messages on serial are your primary visibility into what is happening.

- You should wire the reset line to somewhere that you can manipulate it, so you don't have to power cycle your firmware every time you want to restart it in testing.

Once you have done all that, you end up with support for both ISP and UART bootloader - regardless if you plan to use them both or not.


message:
Arduino Mega 2560 Only Powers on with USB

I have an Arduino Mega 2560 board running a ramps 1.4 shield for a 3D printer.  For some reason, I can only power the Mega with USB.  It does not get power from the ramps shield and it also will not power on when plugged in to a 12v wall adapter.  I know all power sources are working because I have a second Mega that works fine on all.  What could I check on the Mega board to help figure this out.  Other than being powered only by USB, everything else works as expected with no problems.

body:
Looking at [this][1] Arduino Mega 2560 schematic, if IC1 or IC2 failed (assuming only one or the other is installed for a given board), then you would only be able to power the board using the USB port.

Looking at [this][2] ramps 1.4 shield schematic it is assumed that the RAMPS 1.4 shield is providing 12 volts through D1 to the Arduino Mega 2560.  And that testing included using a known good Arduino Mega 2560 board with the RAMPS 1.4 shield board with good results.  Thereby eliminating the possibility that D1 on the RAMPS 1.4 shield is damaged.

If these assumptions are correct, this reinforces the likelihood that either IC1 or IC2 has failed on the Arduino Mega 2560 board.

  [1]: https://arduino-info.wikispaces.com/file/view/arduino-mega2560-schematic-F.jpg/346627792/arduino-mega2560-schematic-F.jpg
  [2]: http://reprap.org/mediawiki/images/f/f6/RAMPS1.4schematic.png


message:
Board and library updates required caused an error

I compiled my code several times today,
I would quit and restart randomly through the day.
each time I started I get a error box board and libraries need updates.
I did an AVR board up date, then compiled and now I get this every time.....
________________________________________________________________________________
avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again
________________________________________________________________________________
Yes I have tried rebooting my Windows 7 64 bit AMD machine.

this is on IDE "Arduino 1.6.8"

Of course I made the mistake of not backing up my IDE folders in the belief that an update would not screw my IDE up.

Nothing will upload, not even any of the examples.
I turned on Show Verbose output during Compilation, and upload
I pasted the full output and it was 4500 char to many for this so I turned of the compilation check and left just the upload check on show verbose errors

I loaded in the example blink,

the file followed by the IDE lower window text.
----------------------------------------------------------------------
<!-- language-all: c -->

    /*
      Blink
      Turns on an LED on for one second, then off for one second, repeatedly.

      Most Arduinos have an on-board LED you can control. On the Uno and
      Leonardo, it is attached to digital pin 13. If you're unsure what
      pin the on-board LED is connected to on your Arduino model, check
      the documentation at http://www.arduino.cc

      This example code is in the public domain.

      modified 8 May 2014
      by Scott Fitzgerald
     */

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin 13 as an output.
      pinMode(13, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      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 OF FILE
Copy and paste of the lower IDE window  last lines the same as above
_______________________________________________________________________________

    Sketch uses 928 bytes (2%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
    C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/bin/avrdude -CC:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf -v true -patmega328p -carduino -PCOM10 -b115200 -D -Uflash:w:C:\Users\Lee\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.hex:i

    avrdude: Version 6.3, compiled on Jun 22 2016 at 16:05:21
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf"

    avrdude: no programmer has been specified on the command line or the config file
             Specify a programmer using the -c option and try again

_______________________________________________________________________________
There is that line again   What do I do to fix this?
besides deleting everything and starting all over again?

I do not want to delete and start over

body: This sounds very much like the problem I had when I updated my ARV version,I was also getting "no programmer has been specified error", I run Windows 7 32bit, the way i got out of it was to go back to the update screen when it pops up and in Arduino ARV Boards area....select versions....I went back to version 1.6.10...now it all works again.....at this point I am no longer updating my ARV, but I will after a few more version updates come out, there is obviously something that conflicts at this stage, if you google the problem you will find other of ways to fix this.


message:
Programming arduino using avrdude from command prompt

Out of curiosity, I am trying to upload a simple hex file to Arduino UNO using avrdude from windows command prompt.

As per [this forum][1], I tried to implement it. But got stuck at

> avrdude: ser_open(): can't open device "COM41": The system cannot find the file
specified.

This command was directly imported from Arduino IDE verbose, and also it works fine when uploaded with Arduino IDE. I checked both the device and syntax are correct unless I would not be able to generate the hex file by Arduino compiler.

P.S. I have installed Winavr separately although it was pre-installed by Arduino
itself.

Here is a snapshot of the error [![command prompt][2]][2]

What could be the possible reason for it to fail? Please notify, if anything is missing.

  [1]: https://asensar.com/blog/2013/programming-arduino-using-avrdude/
  [2]: https://i.stack.imgur.com/nWwWW.png

body:
    can't open device "COM41": The system cannot find the file specified.

This means there is no device at `COM41`. This may be due to 2 reasons:

1. You may not have connected your arduino. If this is the case then you please connect the arduino and retry

2.  Your arduino might be on a different COM port. If this is the case, then, go to device manager and check your arduino's COM port and replace `COM41` with that and retry.


body:
After a lot of experiment, I finally made it. I got to know from some forum that when COM PORT is greater than 10, you have to put a '.' after COM PORT setting e.g. -P.COM41.

But, unfortunately that did not work. Then I changed the COM PORT to under 10 in device manager -> Properties -> COM Port Setting -> Advanced Setting; e.g. COM6.
Then it worked. At the time of flash just I have to press the RST button for once.
And now bingo!!

Still, I will try to find out why it didn't work with higher COM Port.


message:
How do I split a number into individual digits?

How would I split `part1` into 2-3 digits and put them into `num1`, `num2`, and `num3`?

    int FMSTATION = 10250;

    int update_display() {
      int fm_station = FMSTATION ;

      int part1;
      int part2;

      part1 = (FMSTATION / 100);
      part2 = (FMSTATION % 100);
      part2 = (part2/10);

      int num1 = ;
      int num2 = ;
      int num3 = ;
      int num4 = part2;

      matrix.writeDigitNum(0, num1, false);  //1st number on lcd
      matrix.writeDigitNum(1, num2, false);  //2nd number on lcd
      matrix.writeDigitNum(3, num3, true);   //3rd number on lcd and adds "."
      matrix.writeDigitNum(4, num4, false);  //4th number on lcd

      matrix.writeDisplay();
    }

I have searched the web from top to bottom, but could not find the answer. In the end what I should get displayed on my LCD is `102.5`.

body:
I think this will help you:

    int FMSTATION = 10250;
    int update_display() {
      int fm_station = FMSTATION ;

      int part1;
      int part2;
      part1 = (FMSTATION / 100); //102
      part2 = (FMSTATION % 100); //50
      part2 = (part2/10); //5

      int num1 = part1/100; //1
      int num2 = (part1 % 100)/10; //0
      int num3 = part1; //2
      int num4 = part2; //5

      matrix.writeDigitNum(0, num1, false); //1st number on lcd
      matrix.writeDigitNum(1, num2, false); //2nd number on lcd
      matrix.writeDigitNum(3, num3, true); //3rd number on lcd and adds "."
      matrix.writeDigitNum(4, num4, false); //4th number on lcd

      matrix.writeDisplay();
    }


body:
`% 10` returns the final digit of a number. Dividing by 10 shifts the number one digit to the right.

So if you have the number 10250 as an integer you can get at each number with:

    10250 % 10 = 0
    (10250 / 10) % 10 = 5
    (10250 / 100) % 10 = 2
    (10250 / 1000) % 10 = 0
    (10250 / 10000) % 10 = 1

So your code could be written as:

    num4 = (fm_station / 10) % 10;
    num3 = (fm_station / 100) % 10;
    num2 = (fm_station / 1000) % 10;
    num1 = (fm_station / 10000) % 10;

No need to mess with "part" variables.


message:
Pass templated function as attachInterrupt parameter

So I want to do something like this:

    template<int PIN, int CHANNEL>
    void initPin() {
     attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
    }

    template<int PIN, int CHANNEL>
    void rising() {
     startTimes[CHANNEL] = micros();
     attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
    }

    template<int PIN, int CHANNEL>
    void falling() {
     values[CHANNEL] = micros() - startTimes[CHANNEL];
     attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
    }

but the compiler gives me this error

    no matches converting function ‘rising’ to type ‘void (*)()’

Can I even do this, or do I have to write all the functions by myself?

body:
Try this:

    template<int PIN, int CHANNEL> void initPin() {
        attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
    }

    template<int PIN, int CHANNEL> void rising() {
        startTimes[CHANNEL] = micros();
        attachInterrupt(PIN, falling<PIN, CHANNEL>, FALLING);
    }

    template<int PIN, int CHANNEL> void falling() {
        values[CHANNEL] = micros() - startTimes[CHANNEL];
        attachInterrupt(PIN, rising<PIN, CHANNEL>, RISING);
    }

The problem is actually the Arduino preprocessor. It adds illegal forward declarations if template functions are formated as your original code.


body:
Please have a look implementation
https://github.com/Yurik72/SimpleButton

There are implementation how to assign function with arguments to interrupt handler


message:
Testing Logic Gates using Arduino

hello guys is there someone who can help me with my first project.
its basically about logic circuits.

by using tact switch and pull-up resistor to set the values to logical 1 or 0.
the output can be verified by using a LED as an indicator.
so the code goes like this:

    //AND GATE
    int pin2=1;         //set pin2=1
    int pin3=1;         //set pin3=1

    void setup()
    {
    pinMode(2,INPUT);
    pinMode(3,INPUT);
    pinMode(4,OUTPUT);
    pinMode(11,OUTPUT);
    pinMode(12,OUTPUT);
    }
    void loop()
    {
      pin2=digitalRead(2);
      pin3=digitalRead(3);

     if(pin2==1)            //turn led on pin11 when pin2 =1
     {
     digitalWrite(11,HIGH);
     }
     else
     {
     digitalWrite(11,LOW);
     }

     if(pin3==1)          ////turn led on pin12 when pin3 =1
     {
       digitalWrite(12,HIGH);
     }
     else
     {
       digitalWrite(12,LOW);
     }

    //TRUTH TABLE OF AND

      if(pin2 && pin3)
      {
        digitalWrite(4,HIGH);
      }
      else
      {
      digitalWrite(4,LOW);
      }
    }

    //OR GATE
    int pin2=1;
    int pin3=1;

    void setup()
    {
    pinMode(2,INPUT);
    pinMode(3,INPUT);
    pinMode(4,OUTPUT);
    pinMode(11,OUTPUT);
    pinMode(12,OUTPUT);
    }
    void loop()
    {
      pin2=digitalRead(2);
      pin3=digitalRead(3);

     if(pin2==1)
     {
     digitalWrite(11,HIGH);
     }
     else
     {
     digitalWrite(11,LOW);
     }

     if(pin3==1)
     {
       digitalWrite(12,HIGH);
     }
     else
     {
       digitalWrite(12,LOW);
     }

    //TRUTH TABLE OF OR

      if(pin2 || pin3)
      {
        digitalWrite(4,HIGH);
      }
      else
      {
      digitalWrite(4,LOW);
      }
    }

    //NAND GATE
    int pin2=1;
    int pin3=1;

    void setup()
    {
    pinMode(2,INPUT);
    pinMode(3,INPUT);
    pinMode(4,OUTPUT);
    pinMode(11,OUTPUT);
    pinMode(12,OUTPUT);
    }
    void loop()
    {
      pin2=digitalRead(2);
      pin3=digitalRead(3);

     if(pin2==1)
     {
     digitalWrite(11,HIGH);
     }
     else
     {
     digitalWrite(11,LOW);
     }

     if(pin3==1)
     {
       digitalWrite(12,HIGH);
     }
     else
     {
       digitalWrite(12,LOW);
     }

    //TRUTH TABLE OF NAND

      if(!(pin2 && pin3))
      {
        digitalWrite(4,HIGH);
      }
      else
      {
      digitalWrite(4,LOW);
      }
    }

can you guys help me to run this in one sketch by using tact switch  to select the logic gate to be tested or run? thank you in advance

body:
What about something like this:

    const uint8_t    inA =  2;
    const uint8_t    inB =  3;
    const uint8_t   outA =  4;
    const uint8_t   outB = 11;
    const uint8_t   outY = 12;
    const uint8_t button =  5;

    void setup() {
        pinMode(inA, INPUT_PULLUP);
        pinMode(inB, INPUT_PULLUP);
        pinMode(outA, OUTPUT);
        pinMode(outB, OUTPUT);
        pinMode(outY, OUTPUT);

        pinMode(button, INPUT_PULLUP);
    }

    uint32_t check_time = 0;

    uint8_t     counter = 0;
    uint8_t       funct = 0b0110; // start with XOR

    void loop() {
        // active low: (for usage with buttons connected to ground with internal pullup)
        // uint8_t state = (digitalRead(inA)==LOW) | (digitalRead(inB)==LOW)<<1;

        // active high:
        uint8_t state = (digitalRead(inA)==HIGH) | (digitalRead(inB)==HIGH)<<1;

        digitalWrite(outA, (state & 1) > 0);
        digitalWrite(outB, (state & 2) > 0);

        digitalWrite(outY, ((funct >> state) & 1) > 0);

        // button handling
        uint32_t actual = millis();
        if (actual > check_time) {
            check_time = actual + 4; // check every 4ms

            if (digitalRead(button) == LOW) { // expects pull-up and active low
                if (++counter == 4) { // debounce - confirmed after 16ms (4*4) and every 256*4 ms again
                    funct = (funct + 1) & 0xF;
                }
            } else {
                counter = 0; // reset counter
            }
        }
    }

It uses push button to cycle through all 16 possible functions of two inputs.
Default is XOR. Assumption is Active HIGH inputs (you can use INPUT instead of INPUT_PULLUP).


body:
For simulating different gates with the same program, an option is to
use the serial port to tell it what gate you want it to simulate. Here I
am also using a function pointer (called `gate`) to represent the
selected gate:

    /* Wiring. */
    const int inputA    = 2;
    const int inputB    = 3;
    const int outputA   = 11;
    const int outputB   = 12;
    const int outputRes = 4;

    void setup()
    {
        pinMode(inputA,    INPUT_PULLUP);
        pinMode(inputB,    INPUT_PULLUP);
        pinMode(outputA,   OUTPUT);
        pinMode(outputB,   OUTPUT);
        pinMode(outputRes, OUTPUT);
        Serial.begin(9600);
        Serial.println(F("Type 'a'(for AND), 'o' (OR) or 'n' (NAND)."));
    }

    /* Available gates. */
    bool AND(bool a, bool b)  { return a && b; }
    bool OR(bool a, bool b)   { return a || b; }
    bool NAND(bool a, bool b) { return !(a && b); }

    /* The gate we want to test. */
    bool (*gate)(bool a, bool b) = AND;

    void loop()
    {
        // Select the gate through the serial port.
        switch (Serial.read()) {
            case 'a': gate = AND;  Serial.println("AND");  break;
            case 'o': gate = OR;   Serial.println("OR");   break;
            case 'n': gate = NAND; Serial.println("NAND"); break;
        }

        // Simulate the gate.
        bool a = !digitalRead(inputA);  // input is in negative logic
        bool b = !digitalRead(inputB);
        digitalWrite(outputA, a);
        digitalWrite(outputB, b);
        digitalWrite(outputRes, gate(a, b));
    }

Here is another version, that uses an `enum` instead of a function
pointer to identify the gate. The constants and the `setup()` are the
same as before, then:

    void loop()
    {
        // The gate we want to test.
        static enum { AND, OR, NAND } gate;

        // Select the gate through the serial port.
        switch (Serial.read()) {
            case 'a': gate = AND;  Serial.println("AND");  break;
            case 'o': gate = OR;   Serial.println("OR");   break;
            case 'n': gate = NAND; Serial.println("NAND"); break;
        }

        // Simulate the gate.
        bool a = !digitalRead(inputA);  // input is in negative logic
        bool b = !digitalRead(inputB);
        digitalWrite(outputA, a);
        digitalWrite(outputB, b);
        bool res = false;
        switch (gate) {
            case AND:  res = a && b;    break;
            case OR:   res = a || b;    break;
            case NAND: res = !(a && b); break;
        }
        digitalWrite(outputRes, res);
    }


message:
Arduino servo seems to time out after code runs for some amount of time

I am running a simple servo program that swings the servo back and forth, it is essentially pressing a button continuously. However, after some time the servo stops moving and it seems like the code stops. I have no code in the program to tell it to stop and I am uploading from a sketch. Can anyone tell me why the servo will stop after some amount of time? is this some kind of safety or programmatic end that is used when you use the sketch compiler to run code?

Here is my code:

    #include <Servo.h>

    int servoPin = 9;
    Servo servo;

    int servoAngle = 0;

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(9600);
        servo.attach(servoPin);
    }

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

        int randnum = rand()%(40000-1000 + 1) + 1000;
        int randnumreturn = rand()%(600-350 + 1) + 350;
        servo.write(45);
        delay(randnum);
        servo.write(22);
        delay(randnumreturn);
    }

body:
`int` in AVR architecture is signed 16 bits. This means 40000 is actually an overflow if it gets assigned to an integer. It would work in most cases, but when the resultant number is `> 32767`, you would get a minus value, which may cause delay not to work properly.

In order to solve the issue, you may either use long int for randnum or use a random interval smaller than 32768.

**Edit:** I did some calculation, if you hit exactly 40000 you would delay for 4294974529 milliseconds (+/-1). Any value over 32767 will cause delays that are extremely long.


message:
How to control 12v water pump by arduino?

I have arduino uno and I've bought [12 Volt/350 GPH Seaflo Electric Bilge Pump][1], how to control it directly from arduino?

  [1]: https://www.amazon.co.uk/12-Volt-350-GPH-Seaflo-Electric-Bilge/dp/B00OCHCRBC

body:
It's not possible to control it directly. You need relay module (better one is with opto coupler).

Or you can use some N-Mosfet like IRF540 with antiparallel fast diode to supress induced high voltage from coil. However arduino output might be weak for fast charge/discharge mosfets gate and it gets hot.