body:
I copy here the answer from https://forum.arduino.cc/t/wire-h-no-such-file-or-directory-solved/297761, cause it worked for me:

> It's not enough to put "#include <Wire.h>" in the source file you are using the library in. It seems you must also put "#include <Wire.h>" in the main *.ino file for the sketch as well, before it can be used in any other source code files.


sender: user

message:
Arduino 4G LTE Shield

Is there by any chance a shield that can take an 4G LTE compatible SIM card activated by a carrier and establish a connection?

sender: assistant

body: Googling "4g shield arduino" gave [this](https://www.cooking-hacks.com/4g-gps-3g-gprs-gsm-gps-lte-wcdma-hspa-shield-for-arduino). It will need a 4G LTE capable SIM, but I guess "it depends" if *any* 4G LTE SIM will work..


body:
This is a really old post but I also found [this LTE shield][1] which is much cheaper than the cooking hacks one.

  [1]: https://www.botletics.com/products/sim7000-shield

Be carefully; this module is a dual band only (900/1800 MHz); no 850 or 1900 MHz.


message:
Arduino and a Web Server

I'm here because I couldn't find any answer anywhere and the problem seems pretty easy and hard in a same time.

I have a website, for exemple : My_website.host.fr
I have arduino's sensors at home, for exemple temperature sensor in my garage, servomotor in shutter, etc... with Wifi-module.

I want to, as a User, access the website, update some information on the website, for exemple : I want the shutter down, so I put it to 0 on the website, and the arduino will, for exemple each X seconds check if the value has changed, if it does then it updates itself and so lower the shutter.

So, by this, i'll never have to connect directly through an @ip to my arduino, without hosting a server at home which could be hacked or anything, the arduino update itself with the infos that are on the website,

So from my arduino I must ? I have no idea, get the source code of the web page and search for some value, or, from the web page, update a file with PHP variables and retrieve that file with my arduino then read it for the values ?

I don't know if it's clear tho and I have no idea how to manage it.

Sorry about the bad english sentence or words, not main language;

Thank for the help i'm kind of lost.

body:
I believe the term you want to search on is "[web scraping][1]".  Assuming you are fine with people knowing the state of "things" in your home, you can simply leave the states up on your public web page.  That is, you click on a button on your web page and change the text from "shutter up" to "shutter down".  Mean while, your Arduino is "web scraping" the same page looking for "shutter" and acting on the next word "up" or "down".

In [this blog][2], someone has posted his Arduino "web scrapping" code.  I have not tried it, so do some research before considering this particular solution.

  [1]: https://en.wikipedia.org/wiki/Web_scraping
  [2]: http://www.rogerclark.net/arduino-ethercard-web-scraping/


body:
Another option is [Blynk][1] who offer a server, a smartphone app, and a set of libraries and example sketches for Arduino. Also an active and helpful online user community, where the developers participate.

The server does not make view-able web pages; its job is to enable the Arduino and the app to communicate with each other.

The app lets the user quickly and easily configure a custom control panel which can communicate both ways with your Arduino.

The Arduino Blynk libraries can be installed and an example program compiled and uploaded a few minutes, with support for I/O port reading and writing already built-in. Online documentation describes how to expand the example code to do more specific things. Blynk is still under active development, meaning the documentation isn't always as detailed as one might like, that bugs are being fixed and occasional new ones appear, and new features are being developed.

I use it myself and teach other people how to, and I find it a really quick and easy to use platform for interactive remote control of my Arduino-based gadgets.

For example, I am using it right now to develop a ventilation controller for room- and window-fans. It will mix the room air in winter when the heat rises to the ceiling, and ventilate or just mix the room in summer depending on the floor, ceiling, and outdoor temperatures. It will report back to the smartphone which fans are on and off; allow me to turn any of them on or off; and display a history of the temperatures and fan states.

  [1]: http://www.blynk.cc/


body:
From your comment of Jul 1st, I understand that you can program your
server in PHP. Then, and to expand on my own comments, I am only
recommending that, whatever Web API you design, you keep it as simple as
possible. For example, for telling the Arduino whether it should keep
the shutter open or closed, you could write something like this in PHP:

<!-- language: lang-php -->

    header('Content-Type: text/plain');

    if (user_wants_shutter_open())
        echo "open";
    else
        echo "close";

In particular, it makes absolutely no sense to write a PHP program that
generates an HTML document. Consider that the Arduino is a very low
powered platform: there is no point in having it process more than a
handful of bytes when you only want to communicate a single bit of
information. And you should know that there is really nothing wrong with
using HTTP to transport plain text (but you should use the header
`Content-Type: text/plain`). If you want to send a more complex set of
data, you could use something like text/tab-separated-values, or maybe
even application/json.

Concerning web scrapping, it is a solution to a specific problem, the
problem being that the server returns the information in a format that
is not very well suited for machine consumption. You do _not_ have this
problem. Obviously, you could _create_ the problem by having your PHP
return an HTML document, and then you could apply the solution. My point
is that it is better to avoid creating the problem in the first place:
just return the information in a format that is as easy to parse as
possible.


message:
Sketch behaves differently when motor driver is added

I have written a simple sketch that takes values via serial communication through a Python script.
Here's the code-

    #define LEDPin 13

    void setup() {
    Serial.begin(9600);
    pinMode(LEDPin, OUTPUT);
    Serial.println("Ready");
    }

    void loop() {
    char inByte = ' ';
    if(Serial.available()){
     inByte = Serial.read();
    }
    if (inByte == 'L')
     digitalWrite(LEDPin, HIGH);
    if (inByte == 'R')
     digitalWrite(LEDPin, HIGH);
    if (inByte == 'S')
     digitalWrite(LEDPin, LOW);
    }

Now this code runs perfectly fine with my python script. No problems at all. But When I add code for my L293D motor driver module, like this -

    int E1 = 6;
    int Left= 5;
    int Right = 4;
    char data = ' ';

    void setup()
    {
      pinMode(E1, OUTPUT);
      pinMode(Left, OUTPUT);
      pinMode(Right, OUTPUT);
      pinMode(13, OUTPUT);
      Serial.begin(9600);

      }

      void loop(){
        if (Serial.available()>0){
          data = Serial.read();
        }
        if (data =='L'){
          digitalWrite(E1, HIGH);
          digitalWrite(Left, HIGH);
          delay(2000);
          digitalWrite(Left, LOW);
          digitalWrite(E1, LOW);
          digitalWrite(13, HIGH);
        }
         if (data == 'R') {
          digitalWrite(E1, HIGH);
          digitalWrite(Right, HIGH);
          delay(2000);
          digitalWrite(Right, LOW);
          digitalWrite(E1, LOW);
          digitalWrite(13, HIGH);
        }
         if(data == 'S'){
          digitalWrite(E1,LOW);
          digitalWrite(Right, LOW);
          digitalWrite(Left, LOW);
          digitalWrite(13, LOW);
        }

         }

With this code added, the sketch, takes the first value it recieves, for example L, and then would go on executing the if block for that particular value **ONLY**. Even if the valueschange, still the same code block gets repeated. If I reset the Arduino, using the reset button, again the first value it recieves it starts executing the conditions of the same value and not the rest of the sketch.

P.S- I have attached the capacitor between the pins 5v and RESET.

**EDIT**

I put `ser.readline()` in my python script and found that no matter what the script only sends S to the Arduino. Even if the other two conditions are being satisfied, only S is send, and then suddenly, either L or R will be sent and then thats it. No more sending from the script.

Here's my script-

    import numpy as np
    import cv2
    import serial
    ser = serial.Serial('COM3',9600,writeTimeout = 0)
    def f(x): return
    cv2.namedWindow('Thresholding Control')

    # create trackbars for color change
    cv2.createTrackbar('High H','Thresholding Control',179,179, f)
    cv2.createTrackbar('Low H','Thresholding Control',0,179, f)
    cv2.createTrackbar('High S','Thresholding Control',255,255, f)
    cv2.createTrackbar('Low S','Thresholding Control',0,255, f)
    cv2.createTrackbar('High V','Thresholding Control',255,255, f)
    cv2.createTrackbar('Low V','Thresholding Control',0,255, f)
    cv2.createTrackbar('Guassian Blur','Thresholding Control',0,99, f)

    cap = cv2.VideoCapture(0)
    while(True):
      ret, image = cap.read()
      HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
      # Getting trackbar values
      highH = cv2.getTrackbarPos('High H','Thresholding Control')
      lowH = cv2.getTrackbarPos('Low H','Thresholding Control')
      highS = cv2.getTrackbarPos('High S','Thresholding Control')
      lowS = cv2.getTrackbarPos('Low S','Thresholding Control')
      highV = cv2.getTrackbarPos('High V','Thresholding Control')
      lowV = cv2.getTrackbarPos('Low V','Thresholding Control')
      # Thresholding the image.
      thresh = cv2.inRange( HSV, (lowH, lowS, lowV), (highH, highS, highV))
      blurVal = cv2.getTrackbarPos('Guassian Blur','Thresholding Control')
      if(blurVal%2==0):
          blurVal=blurVal+1
      thresh_smooth = cv2.GaussianBlur(thresh, (blurVal, blurVal), 0)
      #Defining the kernel to be used for Morphological ops.
      kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
      # Applying Opening and Closing.
      thresh_smooth = cv2.morphologyEx(thresh_smooth,cv2.MORPH_OPEN,kernel)
      thresh_smooth = cv2.morphologyEx(thresh_smooth, cv2.MORPH_CLOSE, kernel)

      #(minVal, maxVal, minLoc, maxLoc) = cv2.minMaxLoc(thresh_smooth)
      eleR = np.count_nonzero(thresh_smooth[0:480, 320:550])
      eleL = np.count_nonzero(thresh_smooth[0:480, 0:320])
      eleO = np.count_nonzero(thresh_smooth[0:480, 550:640])
      if (eleL>eleR and eleL>eleO and eleL!= (eleR+eleO)):
         cv2.putText(image,"Left Turn", (320,240), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
         print ('L')
      elif (eleO>eleR and eleO>eleL):
         cv2.putText(image,"Right Turn", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
         print ('R')
      else:
         cv2.putText(image,"Straight", (240,320), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
         print ('S')
      cv2.imshow("BGR", image)
      cv2.imshow("Thresholded", thresh_smooth)
      print ser.readline();
      if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    #cv2.imwrite('ImG.png', thresh_smooth)
    cap.release()
    cv2.destroyAllWindows()

body:
3 things:

1: your delay statement is worrying, I'd highly recommend parallel coding in this case.

2: you don't have a "data = ' ';" statement in your loop function of the second code, but you do in the first. Is this intentional?

3: if your arduino receives Serial while executing Delay, you mustn't pour in more than the buffer.


body:
You have got quite a bit of difference between the two codes.

In your first code you declare `char inByte = ' ';` at the beginning of `void loop`. This means that each time you run through the loop it clears the value which you assign the Serial value to.

In the second code you declare `data` as a global variable outside of loop.

What that means is that you first code basically allows a one-shot reaction to a Serial value because it clears the value at the beginning of loop. Thus it only goes into an `if()` statement once.

Whereas your second code will retain the value that it received at `Serial.read()` the first time. Thus it will continue to run the matching if statement.

What you could do is after each matched `if()` statement you do `data = ' ';` or at the beginning of loop you can clear it.

Also you might be missing the updates from your python script because of the delays during motor control. Also Gerben is correct about there possibly being issues with the motor drivers affecting the Arduino.


body:
Okay I figured it out. Putting what I did here, for people who are curious and for those who need help.

It was probably the Arduino, autoresetoverserialcomm, for some reason the Arduino auto-resets whenever you send a value over the serial comm to the Arduino from a computer, not from the Serial port (obviously). I knew of this earlier, and another one of my script which also sends data to the Arduino was working fine with this setup.

What I did? I just put a 10µ capacitor between the RESET and the GND pins. That didn't work initially, but I tried putting the +ve of the capacitor in the GND pin and -ve in the RESET pin and voila! The script started working just fine.

I guess this wasn't a programming issue at all, but an issue of the Arduino and the script not being able to contact each other.

I still am not sure as to what was causing the problem or whether what I have done is a permanent fix, or even a fix at all, but my problem seems to have been solved. I'll keep updating the post.

Suggestions and discussions are always welcome!


message:
How can I use wifi to wirelessly communicate (and wirelessly code if possible) between multiple arduinos?

I am using arduino as the base for an accelerometer project - the end goal is to have multiple arduinos with accelerometer chips that can wirelessly start and stop collecting data and wirelessly send this data back to the "base" arduino (which will be connected to a computer).  Currently we have only two arduinos communicating to test a lot of this, and currently are using a bluetooth node to wirelessly code the accelerometer arduino and Rf nodes to wirelessly send the data back to the arduino connected to a computer which then prints the data it is collecting.  How could we replace this with a wifi network?

body:
Sending data to a computer using WiFi is simple enough and there are plenty of examples. The simplest way is to set up a web server on the computer and use HTTP POST to send the data. There are "lighter" ways but entail more coding.

You won't do OTA updates on a normal Arduino. Yes, you could use a Yún, but they aren't always the best choice - the Linux side of things does make it a very "heavyweight* board.

You may be better off using an ESP8266 based system (not wired to an Arduino, but standalone) and programming it direct. Maybe a NodeMCU or something similar.  [The Arduino core for ESP8266 supports OTA programming direct from the Arduino IDE.](http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html)


message:
SoftwareSerial error:

Please help me with this library "Softwareserial". The basic sketch does not work. Please look the errors:

        C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:128:2: error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

     #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

      ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'bool SoftwareSerial::listen()':

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:184:23: error: 'SREG' was not declared in this scope

         uint8_t oldSREG = SREG;

                           ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:185:9: error: 'cli' was not declared in this scope

         cli();

             ^

    In file included from C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\cores\arduino/delay.h:27:0,

                     from C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\cores\arduino/Arduino.h:76,

                     from C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:43:

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::setTX(uint8_t)':

    C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:62:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]

     #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:360:18: note: in expansion of macro 'digitalPinToPort'

       uint8_t port = digitalPinToPort(tx);

                      ^

    C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:65:44: error: base operand of '->' is not a pointer

     #define portOutputRegister(port)   ( &(port->OUT.reg) )

                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:361:27: note: in expansion of macro 'portOutputRegister'

       _transmitPortRegister = portOutputRegister(port);

                               ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::setRX(uint8_t)':

    C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:62:82: error: invalid conversion from 'PortGroup*' to 'uint8_t {aka unsigned char}' [-fpermissive]

     #define digitalPinToPort(P)        ( &(PORT->Group[g_APinDescription[P].ulPort]) )

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:371:18: note: in expansion of macro 'digitalPinToPort'

       uint8_t port = digitalPinToPort(rx);

                      ^

    C:\Users\Vladyslav\AppData\Local\Arduino15\packages\adafruit\hardware\samd\1.0.9\variants\arduino_zero/variant.h:66:44: error: base operand of '->' is not a pointer

     #define portInputRegister(port)    ( &(port->IN.reg) )

                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:372:26: note: in expansion of macro 'portInputRegister'

       _receivePortRegister = portInputRegister(port);

                              ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::begin(long int)':

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:383:31: error: 'table' was not declared in this scope

       for (unsigned i=0; i<sizeof(table)/sizeof(table[0]); ++i)

                                   ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:399:38: error: 'digitalPinToPCICR' was not declared in this scope

         if (digitalPinToPCICR(_receivePin))

                                          ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:401:78: error: 'digitalPinToPCICRbit' was not declared in this scope

           *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:401:79: error: '_BV' was not declared in this scope

           *digitalPinToPCICR(_receivePin) |= _BV(digitalPinToPCICRbit(_receivePin));

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:402:37: error: 'digitalPinToPCMSK' was not declared in this scope

           *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

                                         ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:402:78: error: 'digitalPinToPCMSKbit' was not declared in this scope

           *digitalPinToPCMSK(_receivePin) |= _BV(digitalPinToPCMSKbit(_receivePin));

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'void SoftwareSerial::end()':

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:417:36: error: 'digitalPinToPCMSK' was not declared in this scope

       if (digitalPinToPCMSK(_receivePin))

                                        ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:418:77: error: 'digitalPinToPCMSKbit' was not declared in this scope

         *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:418:78: error: '_BV' was not declared in this scope

         *digitalPinToPCMSK(_receivePin) &= ~_BV(digitalPinToPCMSKbit(_receivePin));

                                                                                ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'virtual size_t SoftwareSerial::write(uint8_t)':

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:453:21: error: 'SREG' was not declared in this scope

       uint8_t oldSREG = SREG;

                         ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:454:7: error: 'cli' was not declared in this scope

       cli();  // turn off interrupts for a clean txmit

           ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:458:26: error: 'XMIT_START_ADJUSTMENT' was not declared in this scope

       tunedDelay(_tx_delay + XMIT_START_ADJUSTMENT);

                              ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp: In member function 'virtual void SoftwareSerial::flush()':

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:501:21: error: 'SREG' was not declared in this scope

       uint8_t oldSREG = SREG;

                         ^

    C:\Program Files (x86)\Arduino\libraries\SoftwareSerial\SoftwareSerial.cpp:502:7: error: 'cli' was not declared in this scope

       cli();

           ^
    PLEASE HELP ME!

body:
You're trying to use the AVR SoftwareSerial library with an ARM based board. It won't work. Ever.

There should be no need to use SoftwareSerial - the SAMD chips have multiple UART channels - just use one of those.


message:
Arduino for Weather and Air Monitoring: Casing and Power Source

I am intended to use Arduino to measure Temperature and Humidity (DTH11) and Gases Grove Sensor (Multichannel). Due to weather conditions in UK, I would to get your advice how to shield all of them in water proof box? Do you believe that using Polystyrene is useful?
Any recommended power source?

body:
I'd say, use a IP-54 protection plastic case. The IP is a standard, that tells you, how big particles can(not) come into the case.

About powering, depends, how often can you go and switch batteries.
If you can, you can plug the cable in the case - drill the hole through and use watertight silicone plug to ensure, it is water resistant.

In case of batteries - use some LiPo batteries with DC-DC converter to minimum voltage.
Maybe you could even add a solar panel or two for addional life extension of batteries.


message:
Communication between two Arduinos over RF module

I want to communicate Arduino A to Arduino B by using RF module. But my RF module (Tx- XLPCF20, Rx- XY-R01A) only consist of 4 pins of data pin where it can send 4 bits of data only. So, I want to develop a new encoding to send data by using 4 bits of data. How should i do for the coding since I don't want to use serial write for coding. Any suggestion? Help me please. If u can give me the coding, I'm beyond thankful.

body:
You have 4 channels of raw HIGH/LOW communication.  How you use them is up to you.

The simplest method is to use an asynchronous serial protocol:

* Use Serial: Connect the TX of one Arduino to channel 1 at the TX, and RX channel 1 to RX on the other Arduino
* Use SoftwareSerial: The same as above but you choose the pins
* Use VirtualWire: very similar to SoftwareSerial

For higher speeds, since you have 4 channels, you could use a *synchronous* serial communication protocol. It should be perfectly possible to connect three of the channels to SPI and communicate as if it were talking directly to an SPI device - one channel to SCK, one to MOSI and one to SS. The other end has SCK, MOSI and SS but running in slave mode.

No need to "invent" a 4-bit protocol, it's too much work.


message:
Passing pointers between setup and loop

I'm new to the Arduino world. The last time i was programming microprocessors, was back with the Z80 in assembly language.

I am also teaching myself C++ and seems to be going quite well.

I have decided to write my own 'library' for driving 7 segment LED's. The reason for writing my own, rather then using an existing one is to aid with the learning process. I'm quite pleased to say it works ( it may not be the most efficient code)

The books I have on C++ are great, but i do find sometimes the explanation of concepts seem to get lost.

what I would like to know, how do you go about initialising an object class in setup() and using it in loop()? I have this sneaky suspicion that it involves creating the object on the heap, and passing a pointer to the object over somehow.

I could just initialise it once in loop(), and make my own continuous loop afterwards, but there are other things done between the and of a loop() and the beginning of the next loop() (things like timer interrupts).

I will post the code im using, but not the library unless asked to, as it is quite a few lines.

    # include "Leddisplay.h"
    void setup() {

     byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };

     Leddisplay *pRightDigit = new Leddisplay(Digit);

    }

    void loop() {

     pRightDigit->setDigit(5);
     pRightDigit->displayDigit();

    }

^^  Obviously this does not compile  ^^

    # include "Leddisplay.h"
    void setup() {

    }

    void loop() {

     byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
     Leddisplay *pRightDigit = new Leddisplay(Digit);

     pRightDigit->setDigit(5);
     pRightDigit->displayDigit();

     for (;;); // or do.. while within which has other code to repeat
        // but wont allow anything to be executed between loop() iterations

    }

^^  This does, and runs fine, but may not achieve what I want  ^^

I'm not sure if I have used the right wording, or even asked the right question.
Thank you for any help in advance.
Dave

body:
> ... how do you go about initialising an object class in setup() and using it in loop()?

You declare it in a global context so that it's accessible by both.

But that's not *quite* what you want here:

    #include "Leddisplay.h"

    byte Digit[] = {...};
    Leddisplay RightDigit(Digit);

    void setup() {
    }

    void loop() {
        RightDigit.setDigit(5);
        RightDigit.displayDigit();
    }


body:
What you have to understand is the concept of *scope*.

Everything (well, almost everything) in C and C++ is enclosed in `{` and `}`. Those define a *scope*, and everything defined within that scope is available to any other scopes defined within that scope.

You can also assume that the whole sketch is surrounded by `{` and `}`. This scope is called the *global scope*.  Anything defined within it is available anywhere in your sketch.

So by defining the object in the *global scope* it is available everywhere:

    # include "Leddisplay.h"

    Leddisplay *pRightDigit;

    void setup() {
        byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
        pRightDigit = new Leddisplay(Digit);
    }

    void loop() {
        pRightDigit->setDigit(5);
        pRightDigit->displayDigit();
    }

However the use of `new` etc is discouraged in low-memory systems. Better is to *statically define* the object:

    # include "Leddisplay.h"

    const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    Leddisplay pRightDigit(Digit);

    void setup() {
    }

    void loop() {
        pRightDigit.setDigit(5);
        pRightDigit.displayDigit();
    }

Note that, when statically defined like this, things in the constructor aren't guaranteed to be run at the right time. They should be moved into a `.begin()` function that you then call from `setup()`:

    # include "Leddisplay.h"

    const byte Digit[9] = { 22, 23 , 24 ,25, 26, 27, 28, 29, 2 };
    Leddisplay rightDigit(Digit);

    void setup() {
        rightDigit.begin();
    }

    void loop() {
        rightDigit.setDigit(5);
        rightDigit.displayDigit();
    }


body:
Sorry, I cannot comment as I do not yet have enough rep.

This is in response to @Dave Dunnes comment

> The Library I have written can (and does) drive multiple led displays.
> I also understand then when programming for ucontrollers, you use as
> little ram as possible. Also, you usually know at compile time, what
> hardware is available, However, say you only know how many displays
> there are at runtime. This is why I have created the LED display
> instance on the heap (I assume on the Arduino, thats RAM, not flash)
> Let us say at runtime the program would ask you how many displays are
> connected via the serial terminal, then they will be activated, and a
> recompile is not an option. Regards, Dave – Dave Dunne 9 hours ago

If you do not know the exact number of segments (or any element really) at build time then you could implement a [linked list][1] and dynamically allocate new  Leddisplay objects at run time or build the list in to your class. Alternatively you can try try using [std::list][2] with the [AVR port of the STL][3] (I have not personally tried this).

  [1]: http://www.cprogramming.com/tutorial/lesson15.html
  [2]: http://en.cppreference.com/w/cpp/container/list
  [3]: http://gammon.com.au/forum/?id=11119 "AVR Port of the STL"


message:
Multiple HC-SR04 with one 5v 7805 regulator

I am working on a autonomous track vehicle. I have mounted

3 HC-SR04 sensors
1 Sharp infrared distance sensor
3 infrared led distance sensors

1 Arduino Mega 2560
1 H-bridge Board HG7881

I am trying to use 7.5 v 1700 mAh Nicd battery (also tried 11.1 Lipo 2200 mAh)
For all sensors power (5v) I developed 5v regulator using 7805 which is connected directly from battery as input. The output 5v is going to power distribution board (used from quadcopter extra board) which provides 5v to every sensor.

The real problem starts here when I am not getting correct or nothing in reading from Ultrasonic sensors and my vehicle starts behaving abnormal. I checked that sensor reading is either 0 or wrong. I used both simple and with NewPing library.

I checked when using 7.2v battery the output from 5v regulator is 3.72v.

Now my question is if the power is below 5v, does sensors starts behaving like this? How can we supply voltage so every sensor will receive full 5v to work properly?

My vehicle will not work until sensors provide correct distance reading. I worked successfully with one sensor but with number of these, tired working since many days.

body:
You really could benefit from a DC/DC switching power supply.  For instance you are wasting about 20% of the power of the 7.2V battery and something like 50% of the power of the 11.1V battery.

That said, could it be that you are triggering the 3 ultrasonic HC-SR04 too closely together?  If you don't wait for the sound to die out from the 1st sensor the 2nd sensor could give unexpected results.  Same goes for the 3rd sensor.


body:
Your 7805 regulator isn't working, it should have a output of 5v, 3.72v is way off. 2-4% diff from 5V is the normal specification. https://www.fairchildsemi.com/datasheets/LM/LM7805.pdf

Vin should be between 7-20volt even if the datasheet indicate that you can have as low as 5volt in.

Causes could be:

 - Wrong design
 - Low battery voltage
 - Faulty component
 - Faulty connection


message:
Posting to EEPROM via HTML - ESP8266 Arduino IDE

For those of you familiar with my somewhat steep EEPROM learning curve...thank you for continuing to share your knowledge.  I see how it's supposed to work and it's falling into place.

I've run into a new problem and I've spent two nights (~15hrs of Googling/trial and error...mostly error) trying to understand where I'm going wrong.

Below is a chunk of code that take user inputs from a webpage and saves it to EEPROM.  It works as intended when only SSID and PASS fields are provided on the form.  I added an "owner" field to add my name to the EEPROM (because why not?) and now the PASS field is ignored and the OWNER information is saved to the PASS and OWNER EEPROM locations.

I think it has something to do with the string.indexof("&") and repeated string.lastindexof("=") but I'm still wrapping my head around what these actually do.  If I understand it correctly, the second string.lastindexof("=") is actually overwriting the PASS which was saved milliseconds earlier.  If this is correct, how do I prevent this?  If I'm wrong, why?

      s += "<form method='get' action='a'>SSID: <input name='ssid' length=32>
PASS: <input name='pass' length=64>
OWNER: <input name='owner' length=32>

<input type='submit'></form>";
      s += "\r\n\r\n\r\n";
      Serial.println("Sending 200");
    }
    else if ( req.startsWith("/a?ssid=") ) {
      Serial.println("clearing eeprom");
      for (int i = 0; i < 128; ++i) {
        EEPROM.write(i, 0);
      }
      String qsid;
      qsid = req.substring(8, req.indexOf('&'));
      Serial.println(qsid);
      Serial.println("");
      String qpass;
      qpass = req.substring(req.lastIndexOf('=') + 1);
      Serial.println(qpass);
      Serial.println("");
      String owner;
      owner = req.substring(req.lastIndexOf('=') + 1);
      Serial.println(owner);
      Serial.println("");

      Serial.println("writing eeprom ssid:");
      for (int i = 0; i < qsid.length(); ++i)
      {
        EEPROM.write(i, qsid[i]);
        Serial.print("Wrote: ");
        Serial.println(qsid[i]);
      }
      Serial.println("writing eeprom pass:");
      for (int i = 0; i < qpass.length(); ++i)
      {
        EEPROM.write(32 + i, qpass[i]);
        Serial.print("Wrote: ");
        Serial.println(qpass[i]);
      }
      Serial.println("writing eeprom owner:");
      for (int i = 0; i < owner.length(); ++i)
      {
        EEPROM.write(96 + i, owner[i]);
        Serial.print("Wrote: ");
        Serial.println(owner[i]);
      }
      EEPROM.commit();

To summarize, my questions are:

-what is causing the code to skip over my PASS field and save a duplicate of OWNER into both PASS and OWNER?

-is one \r\n pair required for every field on the html form?  If I used 100 fields would I need 100 * \r\n pairs after  tag?

If you're interested in seeing the whole shebang, chriscook8 has graciously posted the Access Point sketch for the ESP8266 [here][1] (~250 lines).  There is also a very helpful discussion about this sketch [here][2].

  [1]: https://github.com/chriscook8/esp-arduino-apboot
  [2]: http://www.esp8266.com/viewtopic.php?f=29&t=2520

-----
Edit: 3 July 2016
-----

I've amended the code:

    s += "<form method='get' action='a'>SSID: <input name='ssid' length=32>
PASS: <input name='pass' length=64>
OWNER: <input name='owner' length=32>

<input type='submit'></form>";
    s += "\r\n\r\n\r\n";
    Serial.println("Sending 200");
    }
        else if ( req.startsWith("/a?ssid=") ) {
          Serial.println("clearing eeprom");
          for (int i = 0; i < 128; ++i) {
            EEPROM.write(i, 0);
          }
          String qsid = server.arg("ssid");
          String qpass = server.arg("pass");
          String owner = server.arg("owner");
        }
        Serial.println("writing eeprom ssid:");
        for (int i = 0; i < qsid.length(); ++i)
        {
          EEPROM.write(i, qsid[i]);
          Serial.print("Wrote: ");
          Serial.println(qsid[i]);
        }
        Serial.println("writing eeprom pass:");
        for (int i = 0; i < qpass.length(); ++i)
        {
          EEPROM.write(32 + i, qpass[i]);
          Serial.print("Wrote: ");
          Serial.println(qpass[i]);
        }
        Serial.println("writing eeprom owner:");
        for (int i = 0; i < owner.length(); ++i)
        {
          EEPROM.write(96 + i, owner[i]);
          Serial.print("Wrote: ");
          Serial.println(owner[i]);
        }
        EEPROM.commit();
        s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\nHello from ESP8266 ";
        s += "Found ";
        s += req;
        s += "
 saved to eeprom... reset to boot into new wifi\r\n\r\n";
      }
      else
      {
        s = "HTTP/1.1 404 Not Found\r\n\r\n";
        Serial.println("Sending 404");
      }
    }

I also made the following replacement per your recommendations:

    //WiFiServer server(80);
    ESP8266WebServer server ( 80 );

...and receive an error on this line:

    WiFiClient client = server.available();

'class ESP8266WebServer' has no member named 'available'

I'm sure that there is a simple replacement for this.  Any idea what it might be?

Otherwise, I think I see where you're going with this and it seems much cleaner than I anticipated.

Thank you!

body:
A code snippet for you - will expand later (just got tied up)

    ESP8266WebServer server ( 80 );
    ...

    else if ( req.startsWith("/a?ssid=") ) {
      Serial.println("clearing eeprom");
      for (int i = 0; i < 128; ++i) {
        EEPROM.write(i, 0);
      }
      String qsid = server.arg("ssid");
      String qpass = server.arg("pass");;
      String owner = server.arg("owner");

      Serial.println("writing eeprom ssid:");
      ... rest of your code


message:
Modbus RTU over TCPip

I have developed my arduino code using below library. I tested code working fine over modbus RTU slave. Now i am planning to use RS485 to wifi instead of wire connection. In order to get data over web apllication i need to add another layer of modbus TCP-IP. can some one suggest me is it possible to without changing any hardware add library function which can acts like MODBUS RtU over TCP-IP protocol.

if any library avilable please share it
I am using WIFI device like below.
[rs485 to wifi][1]

[MODBUS RTU][2]

  [1]: http://www.usriot.com/p/rs485-to-wifi-converters/
  [2]: http://arduino-experience.blogspot.in/2014/02/modbus-slave-example.html

body:
Modbus TCP simply put is a Modbus packet wrapped in a TCP packet.

There is no 'additional layer of Modbus' added on top. If we look at the osi model pictured below you can see there is only one Modbus application layer (i.e modbus slave/server)

[![Modbus OSI Layer (stolen from http://www.protoconvert.com/][1]][1]

Essentially if the wifi->RS485 gateway strips the payload from the TCP packets and simply spits it out the serial side then no modifications are necessary (apart from the obvious RS485 transceiver you will need to interface the arduino with the gateway).

What you will need to make sure is that the gateway will only send packets directed to port 502 to the arduino (502 is the Modbus TCP port) as it is possible other IP traffic could cause some drama for the modbus slave.

Additionally, you will have to ensure that you set the slave ID of the arduino to be what is specified by the master. Are you also building the Modbus TCP client? If not it is very possible that the required slave ID is 255 which is not supported by the modbus library you have linked.

Modbus (serial) slave IDs can only be between 1 and 247 for traditional reasons when Modbus was first standardised as it was only envisioned to be on serial, however when Modbus TCP was introduced an additional addressing layer (TCP / IP) meant that the unit ID (slave ID when using Modbus TCP) could be anything from 0 - 255. It is common for some vendors (at least in industrial automation) to use a unit ID of 255 for standard Modbus transactions scanning IO and diagnostic or configuration transactions to be send to other unit IDs (essentially making the TCP server a modbus router, forwarding packets to one of the multiple Modbus servers running on that single slave device)

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


message:
use more then one timer

I'm working on Arduino uno and trying to use more then one timer.
I'm using timer1 for my software watchdog (I needed bigger interval for that, so my program won't reset itself after 8 seconds).
In addition, I'm using timer2 for regular interrupt like turn off pin after 8 seconds.
The problem is that the timer1's interrupt override timer2's interrupt.

Is it possible to to use both of them?

body:
In general, once an embedded processor's interrupt fires, the interrupt routine clears the interrupt.  Usually inside the interrupt routine.  Failure to clear the interrupt normally inhibits further interrupts.

That said, in the Arduino paradigm, this is "taken care of" by the Arduino Timer library described [here][1].  In the example code:

    /*
     *  Timer1 library example
     *  June 2008 | jesse dot tane at gmail dot com
     */

    #include "TimerOne.h"

    void setup()
    {
      pinMode(10, OUTPUT);
      Timer1.initialize(500000);         // initialize timer1, and set a 1/2 second period
      Timer1.pwm(9, 512);                // setup pwm on pin 9, 50% duty cycle
      Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
    }

    void callback()
    {
      digitalWrite(10, digitalRead(10) ^ 1);
    }

    void loop()
    {
      // your program here...
    }

...you can see that the example does not actually contain "the" Timer interrupt routine but rather a callback() routine which the Timer library calls when the Timer interrupt occurs.  Code to clear the Timer interrupt is missing and assumed to be in the Timer library.

Consider this if you are writing you own interrupt routine instead of using the Arduino's Timer library.

*I'm going to have to call foul on myself.  Clearing interrupts in their own interrupt routine is very common.  But looking at [this page][2], where the Atmel timer hardware is directly controlled (that is, the normal Arduino Timer library is not being used) and the real interrupt handler exists in the sketch, I see where this is not done.  So, for the Atmel, there must be at least one timer mode where the timer interrupt does not have to be clear for the interrupt to happen again.*

If you are using the Arduino's Timer library consider this warning from the Timer's library web page linked to above:

> Be careful about trying to execute too complicated of an interrupt at
> too high of a frequency, or the CPU may never enter the main loop and
> your program will 'lock up'.

Finally, hardware timed interrupts are normally reserved for operations which are time sensitive and occur much faster than executing code can handle.  For events that happen on the order of seconds, most applications setup 1 timed interrupt to count off a convenient interval.  Say 1 second.  Code is used to keep count and call the proper functions at the intended time.

  [1]: http://playground.arduino.cc/Code/Timer1
  [2]: https://oscarliang.com/arduino-timer-and-interrupt-tutorial/


message:
Power arduino from 5v rail of pc molex

I'm building a small device using arduino that should be connected to my pc via a usb header to exchange data with the PC.

What I'd like to achieve is that arduino turns on when the pc is on, whereas it shuts down when the pc is turned off. If I rely on the usb port to provide power to the arduino that might not happen, since some motherboards still provide power to the usb connections even when the pc is off.

Therefore I'd like to power the arduino using the 5v rail directly from a Molex. I know that theoretically I can connect that rail straight to the 5v pin, but what about power spikes? How can I be sure that the 5v input voltage is properly filtered and stabilized? Would it be better to use a LM317 and transform the 12v rail into 7.5v to feed arduino from the vin?

body:
The 5v of an ATX power supply will be perfectly adequate for powering an Arduino.

It will already be very heavily filtered and stabilised.


message:
How to call class A's method from class B?

I wish to access methods and fields, as well as change them, of class A from class B. Since the main Arduino sketch is not a class, but a list of fields and methods, I created a separate MainClass with a method printStuff() that I want to call from class DoClass. This is how I go about it:

The main sketch:

    #include "MainClass.h"
    MainClass m;
    void setup() {
      m.setup();
    }
    void loop() {
      m.loop();
    }

MainClass.h:

    /*
      MainClass.h
    */
    #ifndef MainClass_h
    #define MainClass_h
    #include "Arduino.h"
    class MainClass
    {
      public:
        MainClass();
        void setup();
        void loop();
        void printStuff();
    };
    #endif

MainClass.cpp:

    /*
      MainClass.cpp
    */

    #include "Arduino.h"
    #include "MainClass.h"
    #include "DoClass.h"
    MainClass::MainClass()
    {
      d DoClass(this);
    }
    void MainClass::setup(){
      Serial.begin(9600);
    }
    void MainClass::loop(){
      d.callMainClassFunct();
    }
    void MainClass::printStuff(){
      Serial.println("printing stuff");
    }

DoClass.h:

    /*
      DoClass.h
    */
    #ifndef DoClass_h
    #define DoClass_h

    #include "Arduino.h"
    #include "MainClass.h"
    class DoClass
    {
      public:
        DoClass(MainClass m);
        void callMainClassFunct();
      private:
        MainClass _m;
    };
    #endif

DoClass.cpp:

    /*
      DoClass.cpp
    */

    #include "Arduino.h"
    #include "MainClass.h"
    #include "DoClass.h"

    DoClass::DoClass(MainClass m)
    {
      _m = m;
    }

    void DoClass::callMainClassFunct(){
      _m.printStuff();
    }

This produces a myriad of errors. Each time I change something, a new kind of error appears, as though I was in a vicious cycle. Clearly, I am unfamiliar with C++. It would greatly help me if you could alter my code so that it works, keeping in mind that I would like to both access methods and fields of class MainClass from class DoClass and change those fields from class DoClass.

For reference, in Java, I would achieve the same in the following way:

MainClass.java:

    public class MainClass{
        DoClass d;

        public MainClass(){
            d = new DoClass(this);
    }

        public void setup(){

    }

    public void loop(){
        d.callMainClassFunct();
    }

    public void printStuff(){
        Serial.println("print stuff");
    }

    }

DoClass.java:

    public class DoClass{
           MainClass _m;
           public DoClass(MainClass m){
              _m = m;
           }
           public callMainClassFunct(){
             _m.printStuff();
    }

    }

Passing this to the constructor od DoClass passes the value of the reference pointing to MainClass instantitated in the main sketch file. Then, by prepending the name of the instantiated object (in this case, "m"), followed by a dot, I can simply access and change all values of that object from DoClass (provided those methods and fields are visible to DoClass, which is the case here).

I have posted before about this issue, but did not receive any answers to my specific question and could not comment because I do not have enough reputation. Thank you to those who tried to answer me, but the answers did not pertain to my specific question. This time I have included more information to show my problem more clearly. Thank you in advance for your help.

body:
In your Java version, you define `MainClass` like this (my comments added):

    public class MainClass{ // Define a new Class
        DoClass d;          // Add a member variable to the class
        public MainClass(){
            d = new DoClass(this); // Initialise the member variable
        } // MainClass()
    } // MainClass

In your C++ you don't do the same thing - but you should! The class needs a `DoClass` member so that you can use it in other `MainClass` functions:

    // MainClass.h
    ...
    #include "DoClass.h" // Need the .h here - remove it from the .cpp
    class MainClass
    {
      public:
        MainClass();
        void setup();
        void loop();
        void printStuff();
      private:
        DoClass _d; // Create a private member variable to use
    };
and

    // MainClass.cpp
    MainClass::MainClass() : // MainClass constructor (note colon)
               _d(*this) // Initialise member
    {
    } // MainClass::MainClass()
Now, you want `DoClass` to be able to use `MainClass`, so you passed it into `DoClass`'s constructor. But `DoClass` cannot have a `MainClass` inside it - `MainClass` already has a `DoClass` inside it! Infinite impossibility! So you need `DoClass` to merely contain a _reference_ to the `MainClass` that it sits inside. That's the C++ unary `&` operator (different from the binary `&` operator), which is used similar to the pointer `*` operator:

    // DoClass.h
    ...
    // Need to advise compiler MainClass exists...
    // but can't #include MainClass.h! Infinite loop!
    class MainClass;

    class DoClass
    {
    public:
        DoClass(MainClass &m); // Reference to MainClass
        void callMainClassFunct();
    private:
        MainClass &_m; // Reference to MainClass
    };
and

    // DoClass.cpp
    DoClass::DoClass(MainClass &m) : // DoClass constructor - note colon
             _m(m) // Initialise member variable
    {
    }


message:
How to send Serial.Print only If Serial Connection is open?

So I looked through the Arduino Mega2560 documentation and searched the web for a solution, and so far I haven't had any success.

What I'm trying to accomplish is fairly simple. I need to send a serial command over serial, ONLY if there is a serial connection between the PC and the Arduino. I've tried:

    If(Serial){
       Serial.Println("COMMAND");
    }

That doesn't work, and I think it's because the Arduino cannot distinguish between listening to the Serial port versus establishing a Serial connection.

Any help would be appreciated.

Cheers!

body:
The Arduino Mega's "serial" connection comes from an external chip implementing USB-serial conversion.  While this chip knows if a session is open with a host, the standard design has no way to share that information with the main ATmega.

In contrast, on a Leonardo type board the main processor implements the USB interface, so it does know.

Your options include changing the requirement, having the PC program send some data to the Arduino, changing the processor to an ATmega or ARM with integrated USB, or perhaps modifying the USB implementation.


message:
Problems returning char array from function, value gets messed up

I use the Base64 library for Arduino (but I don't think the problem is related to the library) and have the following function definition:

    char* decodeImage(char inputString[], unsigned int inputStringLength) {
      int decodedLength = Base64.decodedLength(inputString, inputStringLength);
      char decodedString[decodedLength];
      Base64.decode(decodedString, inputString, inputStringLength);
      Serial.printf("%s",decodedString); // prints "Base64DecodeExample"
      return decodedString;
    }

Later on, I use the following snippet to access the function:

      char inputString[] = "QmFzZTY0RGVjb2RlRXhhbXBsZQA=";
      char* output = decodeImage(inputString, sizeof(inputString));
      Serial.printf("%s",output); // prints garbage

The problem is, that the result of the decoding INSIDE the function seems to be correct, but when I return the value to the calling code, the value get garbled somehow.

I suppose this has something to do with pointer magic or "decaying" of references. Has someone a suggestion?

body:
Your variable `decodedString[]` is created inside the function, used inside the function - and destroyed inside the function before it returns.

See how your function `decodeImage()` returns a `char *`? That's a _pointer_ to a character array, not the whole array - and you can't return a whole array. The pointer is successfully returned all right - but what it is pointing to is overwritten by future calls and future created variables.

This is the perennial problem of C programmers: how to return something created inside the function. You have four choices (each with their own problems):

1. You can make the variable global - put it outside the function and let anyone access it. Then you don't even need to return the string - it's already accessible.
2. You can make `decodedString` a permanent part of the function by making it `static`:

        static char decodedString[64];
> Note that the above two solutions have the same two problems:
 a. There is only one array. That means that if the same function is called again, it will _overwrite_ the results from last time - use it before you lose it!
 b. You can't calculate the length and then use it - it has to be created at the maximum possible size.

3. You can make the caller pass in the array to fill. Rather than return the array, have another parameter that is the array to fill - and for safety's sake, get them to pass in the size of the array too. You'll have to check that and return an error if it's not big enough - or do something else sensible.
4. You can allocate the memory from a different area that where it's currently being allocated from. That area is called the "heap" - it's just a heap o' memory that you can request chunks from - and don't forget to give it back!

To request memory from the heap, you call the function `malloc` and pass in the number of bytes that you want. It returns a pointer to that lump of memory:

    char *decodedString = (char *)malloc(decodedLength);

Note that `malloc` doesn't know what you're going to use the memory for, so you have to tell the compiler - that's what the `(char *)` before the call to `malloc` does.

But if you use `malloc`, at some stage you must give the memory back with a call to `free`:

    free(returnedString);

The function that did the `malloc` doesn't have to be the function that `free`s it - any function can, as long as some function does! Otherwise you'll run out of heap.

Another thing that you must NOT do is call `free` on the same block twice: that will corrupt the heap, since it will mark the same block on the heap twice, and hand it back out twice later, corrupting the data when it is used again.

### EDIT

There's a C++ version of `malloc` / `free` called `new` / `delete`. You use them similarly:

    char *decodedString = new char[decodedLength];
    ...
    // And later...
    delete [] returnedString;

It looks and behaves similarly to `malloc` and `free`, without the ugly `(char *)` type-cast. Note that since an array was allocated with the `new`, you need to call the array version of `delete` by adding the `[]` as shown.


message:
Arduino oscilloscope

I have been working on a recent project to build an Arduino Oscilloscope interfaced with a 4X4 keypad membrane with Nokia 5110 LCD display.I have successful individual code fragments/portions which
1)Generate waves interfaced with the keyboard
2)Display the same on the Nokia LCD 5110

i am using the Arduino Due and the 1st part of my code generates waves on DAC1 with the code as follows:-

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

    #include "Waveforms.h"
    #include <Keypad.h>
    #include <LiquidCrystal.h>

    //Set the desired duty cycle in percentage

    double dc,t,a,d;
    long d_milli,d_micro,a_milli,a_micro,m,n;
    int stage =0;

    int sample_delay1;
    LiquidCrystal lcd(A2, A3, A4, A5, A6, A7);
    float sample_delay;
    String num1,num2;
    int wave1;
    String wave_name;
    double duty_cycle,k;
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    //define the cymbols on the buttons of the keypads
    char hexaKeys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'.','0','#','D'}
    };
    byte rowPins[ROWS] = {23,25,27,29}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {31,33,35,37}; //connect to the column pinouts of the keypad
    int i = 0;
    int sample;
    //initialize an instance of class NewKeypad
    Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
    boolean in_setup = true;
    void setup()
    {
      Serial.begin(9600);
      analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
      analogReadResolution(12);
      lcd.begin(20,4);
      char key = customKeypad.getKey();
      lcd.setCursor(0, 0);
      lcd.print("choose wave: ");
      lcd.setCursor(0, 1);
      lcd.print("A=Sine");
      lcd.setCursor(8, 1);
      lcd.print("B=Triangular");
      lcd.setCursor(0, 2);
      lcd.print("C=Sawtooth");
      lcd.setCursor(11, 2);
      lcd.print("D=Square");

      while( true)
      {
            char key = customKeypad.getKey();
            if(stage == 0)
            {
                  Serial.println("in stage 0");
                  if(key == 'A' )
                  {
                    wave1 = 0;
                    lcd.clear();
                    lcd.setCursor(0,0);
                    lcd.print(" Sine?      ");
                    wave_name ="Sinusoidal";
                    Serial.println(wave_name);

                  }
                  else if(key == 'B')
                  {
                    wave1 = 1;
                    lcd.clear();
                    lcd.setCursor(0,0);
                    lcd.print("Triangular?");
                    wave_name ="Triangular";
                    Serial.println(wave_name);
                  }
                  else if(key == 'C')
                  {
                    wave1 = 2;
                    lcd.clear();
                    lcd.setCursor(0,0);
                    lcd.print("Sawtooth?  ");
                    wave_name ="Sawtooth";
                    Serial.println(wave_name);
                  }
                  else if(key == 'D')
                  {
                    wave1 = 3;
                    lcd.clear();
                    lcd.setCursor(0,0);
                    lcd.print("Square?    ");
                    wave_name ="Square";
                    Serial.println(wave_name);

                  }
                  else if(key == '#')
                  {
                    stage++;
                    //lcd.clear();
                    lcd.setCursor(0,1);
                    lcd.print("Frequency=");
                    Serial.println("Frequency=");
                  }
            }
           else if(stage == 1)
            {
                  if(key != NO_KEY &&(key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'))
                  {
                    num1 = num1 + key;
                    //int numLength = num1.length();
                    //to adjust one whitespace for operator
                    lcd.setCursor(10,1);
                    lcd.print(num1);
                  }

                  else if(key == '#')
                  {
                        k = num1.toInt();
                        Serial.print(k);

                              int sample_delay_int = 1000000/(k*120);
                              float sample_delay_float = 1000000/(k*120);
                              float difference= sample_delay_float-sample_delay_int;
                              sample_delay1 = sample_delay_int - 6;
                              if(difference > 0.5)
                              {
                                sample_delay1++;
                              }

                              Serial.println(sample_delay1);
                              lcd.clear();
                              lcd.print(wave_name);
                              lcd.setCursor(0,1);
                              lcd.print("Frequency=");
                              lcd.print(num1);
                              lcd.print(" Hz");
                              break;
                      }
                  }
       }
    }

    void loop()
      {
      analogWrite(DAC1, waveformsTable[wave1][i] );
      i++;
      if(i == maxSamplesNum)  // Reset the counter to repeat the wave
        i = 0;
      else
        delayMicroseconds(sample_delay1);
      }

Next, I input these waves from DAC1 into analog input A0 to display on the LCD with code as below:-

    #include <Adafruit_GFX.h>
    #include <Adafruit_PCD8544.h>
    #include <SPI.h>

    #define DISPLAY_WIDTH 84
    #define DISPLAY_HEIGHT 48

    #define ARDUINO_PRECISION 1023.0
    Adafruit_PCD8544 display = Adafruit_PCD8544(8,9,10,12,11);

    //Analog Pins
    int channelAI = A0;      // probe

    #define DELAY_POTENTIMETER //disabled it I don't have it connected
    #ifdef DELAY_POTENTIMETER
    int delayAI = A1;       // delay potentiometer
    #endif

    float delayVariable = 0;
    float scale = 0;
    int xCounter = 0;
    int yPosition = 0;
    int readings[DISPLAY_WIDTH+1];
    int counter = 0;

    unsigned long drawtime = 0;
    unsigned long lastdraw = 0;
    int frames = 0;

    void setup(void)
    {
      display.begin();
      display.setContrast(30);// you might have a slightly different display so it might not be the optimal value for you
      display.clearDisplay();
    }

    void loop()
    {
      #ifdef DELAY_POTENTIMETER
      delayVariable = analogRead(delayAI);
      delayVariable = (delayVariable/100);
      #endif
      scale = (float)(DISPLAY_HEIGHT-1)/ARDUINO_PRECISION;

      //record readings
      for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
      {
        yPosition = analogRead(channelAI);
        readings[xCounter] = (yPosition*scale);
        #ifdef DELAY_POTENTIMETER
        delay (delayVariable);
        #endif
      }

      display.clearDisplay();

      //Draw Voltage Ref Lines
      display.drawLine( 10, 0, 10, DISPLAY_HEIGHT-1, BLACK);
      display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), BLACK);
      display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), BLACK);
      display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), BLACK);
      display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), BLACK);
      //display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), BLACK);

      //Draw Voltage Ref Numbers
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.2));
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.4));
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.6));
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.8));

      for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
      {
        display.drawPixel(xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
        if(xCounter>1){
          display.drawLine(xCounter-1, (DISPLAY_HEIGHT-1)-readings[xCounter-1], xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
        }
      }
      //Draw FPS
      display.setCursor((DISPLAY_WIDTH-1)-11,0);
      display.print(frames);

      //Draw Voltage
      display.setCursor(((DISPLAY_WIDTH-1)/2),0);
      display.print(analogRead(channelAI)/ARDUINO_PRECISION*5.0);

      display.display();

      //Calculate FPS
      drawtime = micros();
      frames=1000000/*a second*//(drawtime-lastdraw);
      lastdraw = drawtime;
    }

Now the problem arises when i try doing the 2 things on d same arduino due board.
I got perfect results when i used arduino due and arduino uno simultaneously but have not been able to generate waves on the LCD using the same board.
Is it possible to do the same. Can some1 help me incorporate the 2 programs into 1  ..Thanxx

I tried playing around with my setup() and loop() and have reached a point where my program does everything ,ie takes keypad input ,displays options on the LCD ,takes in freq and generates a splashscreen but the only thing i'm missing out on is d wave display on the LCD (I'm able to see the selected wave on the DSO) ..So i guess i'm pretty close, and the edited code is as follows:-

    #include "waveforms.h"
    #include <Keypad.h>
    #include <SPI.h>

    #include <Adafruit_GFX.h>
    #include <gfxfont.h>

    #include <Adafruit_PCD8544.h>

     //Set the desired duty cycle in percentage
    Adafruit_PCD8544 display = Adafruit_PCD8544(8, 9, 10, 12, 11);
    double dc,t,a,d;
    long d_milli,d_micro,a_milli,a_micro,m,n;
    int stage =0;

    int sample_delay1;
    float sample_delay;
    String num1,num2;
    int wave1;
    String wave_name;
    double duty_cycle,k,Z;
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    //define the cymbols on the buttons of the keypads
    char hexaKeys[ROWS][COLS] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'.','0','#','D'}
    };
    byte rowPins[ROWS] = {23,25,27,29}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {31,33,35,37}; //connect to the column pinouts of the keypad
    int i = 0;
    int t_sample;

    #define DISPLAY_WIDTH 84
    #define DISPLAY_HEIGHT 48

    #define ARDUINO_PRECISION 1023.0
    //Adafruit_PCD8544 display = Adafruit_PCD8544(8,9,10,12,11);

    //Analog Pins
    int channelAI=A0;

    #define DELAY_POTENTIMETER //disabled it I don't have it connected
    #ifdef DELAY_POTENTIMETER
    int delayAI = A1;       // delay potentiometer
    #endif

    float delayVariable = 0;
    float scale = 0;
    int xCounter = 0;
    int yPosition = 0;
    int readings[DISPLAY_WIDTH+1];
    int counter = 0;

    unsigned long drawtime = 0;
    unsigned long lastdraw = 0;
    int frames = 0;

    //initialize an instance of class NewKeypad
    Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
    boolean in_setup = true;
    void setup()
    {
      Serial.begin(9600);
      analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
      analogReadResolution(12);
      display.begin(20,4);

      char key = customKeypad.getKey();

      display.begin();
      display.display();
      display.setContrast(40);// you might have a slightly different display so it might not be the optimal value for you
      display.clearDisplay();

      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor(0, 0);
      display.print("choose wave: ");
      display.display();
      display.setCursor(1, 8);
      display.print("A=Sine");
      display.display();
      display.setCursor(1,16);
      display.print("B=Triangular");
      display.display();
      display.setCursor(1,24);
      display.print("C=Sawtooth");
      display.display();
      display.setCursor(1,32);
      display.print("D=Square");
      display.display();

      while( true)
      {
        char key = customKeypad.getKey();
        if(stage == 0)
        {
          Serial.println("in stage 0");
          if(key == 'A' )
          {
            wave1 = 0;
            display.clearDisplay();
            display.setCursor(0,0);
            display.print(" Sine?      ");
            display.display();
            wave_name ="Sinusoidal";
            Serial.println(wave_name);

          }
          else if(key == 'B')
          {
            wave1 = 1;
            display.clearDisplay();
            display.setCursor(0,0);
            display.print("Triangular?");
            display.display();
            wave_name ="Triangular";
            Serial.println(wave_name);
          }
          else if(key == 'C')
          {
            wave1 = 2;
            display.clearDisplay();
            display.setCursor(0,0);
            display.print("Sawtooth?  ");
            display.display();
            wave_name ="Sawtooth";
            Serial.println(wave_name);
          }
          else if(key == 'D')
          {
            wave1 = 3;
            display.clearDisplay();
            display.setCursor(0,0);
            display.print("Square?    ");
            display.display();
            wave_name ="Square";
            Serial.println(wave_name);

          }
          else if(key == '#')
          {
           stage++;
           display.clearDisplay();
           display.setCursor(20, 8);
           display.println("Freq=");
           display.display();
           Serial.println("Frequency=");
          }
        }
        else if(stage == 1)
        {
          if(key != NO_KEY &&(key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0'))
          {
            num1 = num1 + key;
            //int numLength = num1.length();
            //to adjust one whitespace for operator
            display.setTextSize(1);
            display.setTextColor(BLACK);
            display.setCursor(48, 9);
            display.print(num1);
            display.display();
          }
          else if(key == '#')
          {
            stage++;
            k = num1.toInt();
            Serial.print(k);
            display.setTextSize(1);
            display.setTextColor(BLACK);
            display.display();
            display.setCursor(10, 1);

            int sample_delay_int = 1000000 / (k * 120);
            float sample_delay_float = 1000000 / (k * 120);
            float difference = sample_delay_float - sample_delay_int;
            sample_delay1 = sample_delay_int - 6;
            if (difference > 0.5)
            {
              sample_delay1++;
            }

            display.display();
            Serial.println(sample_delay1);
            display.clearDisplay();
            display.print(wave_name);
            display.setCursor(1, 8);
            display.println("Freq=");
            display.print(num1);
            display.println(" Hz");
            break;
          }
        }
      }

      //record readings
      for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
      {
        yPosition = analogRead(A0);
        readings[xCounter] = (yPosition*scale);
        #ifdef DELAY_POTENTIMETER
        delay (delayVariable);
        #endif
      }

      display.clearDisplay();

      #ifdef DELAY_POTENTIMETER
      delayVariable = analogRead(delayAI);
      display.display();
      delayVariable = (delayVariable/100);
      #endif
      scale = (float)(DISPLAY_HEIGHT-1)/ARDUINO_PRECISION;

      //Draw Voltage Ref Lines
      display.drawLine( 10, 0, 10, DISPLAY_HEIGHT-1, BLACK);
      display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale), BLACK);
      display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale), BLACK);
      display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale), BLACK);
      display.drawLine( 0, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale), BLACK);
      //display.drawLine( 5, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), 10, (DISPLAY_HEIGHT-1)-(.84 *ARDUINO_PRECISION * scale), BLACK);

      //Draw Voltage Ref Numbers
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.2 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.2));
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.4 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.4));
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.6 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.6));
      display.setCursor(0,((DISPLAY_HEIGHT-1)-(.8 *ARDUINO_PRECISION * scale))-3);
      display.print((int)(5.0*0.8));

      for(xCounter = 0; xCounter <= DISPLAY_WIDTH; xCounter++)
      {
        display.drawPixel(xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
        if(xCounter>1){
          display.drawLine(xCounter-1, (DISPLAY_HEIGHT-1)-readings[xCounter-1], xCounter, (DISPLAY_HEIGHT-1)-readings[xCounter], BLACK);
        }
      }
      //Draw FPS
      display.setCursor((DISPLAY_WIDTH-1)-11,0);
      display.print(frames);

      //Draw Voltage
      display.setCursor(((DISPLAY_WIDTH-1)/2),0);
      display.print(analogRead(A0)/ARDUINO_PRECISION*5.0);

      display.display();

      //Calculate FPS
      drawtime = micros();
      frames=1000000/(drawtime-lastdraw);
      lastdraw = drawtime;
      display.display();
    }

    void loop()
    {
      analogWrite(DAC1, waveformsTable[wave1][i] );
      i++;
      if(i == maxSamplesNum)  // Reset the counter to repeat the wave
        i = 0;
      else
      delayMicroseconds(sample_delay1);

      analogWrite(DAC0, waveformsTable[wave1][i] );
      i++;
      if(i == maxSamplesNum)  // Reset the counter to repeat the wave
        i = 0;
      else
        delayMicroseconds(sample_delay1);
    }

Can some1 possibly tinker around with this ..It'll b a huge help!!

body:
You have two programs. One has a _very_ complicated `setup()`, but a very quick `loop()`. The other has a very small `setup()`, but a _very_ complicated `loop()`. And you want to merge the two programs?

That will be very, very difficult. Your first program `loop()` looks like this:

    void loop() {
       analogWrite(...); // Very quick code
       i++;              // Very quick code
       if (..)           // Very quick code
          i = 0;         // Very quick code
       else              // ***BUG!!!*** This shoud not be here!
       delayMicroseconds(...); // Very specific timing delay
    } // loop()

In other words, to produce the correct waveform it does very few instructions very quickly - and then waits a carefully calculated time.

Your other program's `loop()` does lots of things, and doesn't care about timing. The code is not time-sensitive at all - and writing to the display takes variable time anyway.

Your only choice is to set a timer to interrupt every `sample_delay1` microseconds, and inside the timer interrupt handler do the `analogWrite(...);` call instead of having the `loop()` function do it. That is Advanced Arduino programming!


message:
Connect GPS module (WeeBee) to Arduino Uno

This is my very first Arduino project. I want to learn about GPS navigation by exploring the [NMEA protocol](https://en.wikipedia.org/wiki/NMEA_0183)!

Therefore, I bought a WeeBee GPS module. After reading the datasheet, I have two questions:

1. The [official Arduino website][1] states
    > Note: if you are using an Arduino Uno, keep in mind that you can't use the GPS module at the same time as your computer is connected on the USB port.

   But I you go to the end of his tutorial, you will see he can transmit the GPS data to his computer. I don't understand why it would not be possible...

2. The GPS module datasheet ([download link here][2]) states that the maximum voltage is 5V. But it also states

> serial connections are 3.3V CMOS Logic Levels

and

> Suitable decoupling must be provided by external decoupling circuitry.

So, does it mean I need a logic level converter to prevent damage to the GPS module?

  [1]: http://playground.arduino.cc/Tutorials/GPS
  [2]: http://pan.baidu.com/s/1hsrWhoC#path=%2FWeBee%2FGP-001

body:
 - The article on the Arduino website means that you can't upload sketches from your PC to the Arduino or receive any sort of data, through the serial monitor or otherwise, from your PC, while the GPS module uses the RX pin. Any attempt to send data from PC to Uno in this condition would cause the Arduino to receive only corrupted data, since 2 devices (GPS module and PC) would be trying to send data *at the same time*, *with the same line*. This limitation is easily resolved by connecting the GPS module to a `SoftwareSerial` port instead; this keeps the `HardwareSerial` port (pins 0 & 1) free for bidirectional PC-Arduino communication.
 - The datasheet says that the maximum power supply voltage is 5 V. However, the serial connections are 3.3 V logic, so yes, you will need logic level shifters. A simple voltage divider will serve. However, 'external decoupling' refers to circuitry used in decoupling/smoothing out any spikes or dips that may occur in the supply voltage. An untamed spike could damage the device, while a dip (perhaps from large current draw) could cause the device to stop working, if the voltage falls low enough to be considered under-voltage. A 10uF electrolytic capacitor, connected from Vcc to GND close to the GPS module, should be okay.


message:
How to wire up and trigger this SPDT relay?

How do I connect a SPDT relay to an Arduino?

It's [a DC 5V Coil 6 Pin relay](https://www.amazon.com/uxcell®-HT4100F-General-Power-Relay/dp/B008MPK0VE) and ultimately what I want to do is have the Arduino trigger the relay to allow voltage to pass through.

I couldn't find a data sheet, but apparently this is the layout...

    ----------------------------------
    |....1......2..............3.....|
    |................................|
    |....4......5..............6.....|
    ----------------------------------

    2 and 5 are the 5v relay coil
    3 and 6 are shorted together
    3 and 1 are normally closed
    3 and 4 are normally open

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

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

body:
According to the link you've provided, the coil draws very little current, and the person posting that comment suggests that it can be directly driven by an arduino. I would hesitate to use more than one to a board without additional research in that respect.

The comment also suggests that a capacitor be placed across the coil terminals, which will also protect your circuit from excessive power draw causing drop outs.

The research I've done indicates that the digital pins can handle a maximum of 40 ma, but the recommendation is no more than 20 ma, which is lower than the specs for this relay.

If you are going to use more than one on a given arduino board, a shift register or equivalent would protect your board and give you reliable results. For a single relay, consider this resource:
https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/transistors

Some additional research may lead one to believe that even 20 ma is too much current to draw, so the transistor option is certainly the safer route.

Be certain to use pull-up or pull-down resistors, depending on your configuration with the digital pin selected.

You didn't indicate what you were going to be connecting to the N/O or N/C pins, but that won't matter if they are external to the arduino and do not exceed the specifications of the relay.


body:
Use a driver transistor (or MOSFET, with a 4K7 pull-down), and a flyback diode with the anode at the negative terminal, and cathode at positive terminal. I used some tiny ones, which failed, so now I use ones that can handle ~0.5A, but that's probably overkill.

If you want galvanic isolation, use an optocoupler instead of a transistor - I only do this for AC. I have never needed decoupling capacitors for this type of relay.

Edit:

- Wire 5V to relay positive terminal.

- Wire relay negative terminal to NPN transistor/MOSFET collector/drain.

- Wire NPN/MOSFET emitter/source to GND. Wire NPN/MOSFET base/gate to some digital pin. If using a transistor, do it across a 1000 ohms resistor.

- If using a N-channel MOSFET add a 4700 ohms pull-down from gate to GND.

- Wire diode cathode to relay positive terminal, and anode to relay negative terminal.

I would not use the decoupling cap, but if OP really wants it, go for 50-100V 10uF.


body:
You can use this connection diagram with your relay

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

**6 pin Relay pin out**

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

**Code**

    int Relay = 8;

    void setup()
    {
      pinMode(Relay, OUTPUT);
    }

    void loop()
    {
          digitalWrite(Relay, HIGH);  // turn on relay
          delay(2000);
          digitalWrite(Relay, LOW);   // turn off relay
          delay(2000);
    }

First check your relay with multi meter then find the Coil, Com, NO and NC points for correct connection.
Hope this will help you.

  [1]: https://i.stack.imgur.com/GR4cx.jpg
  [2]: https://i.stack.imgur.com/eywAE.png


message:
Serial.readString() not working becaue of outdated IDE?

I've searched google honestly but can't find an answer nor changelogs for Arduino that might be the answer.

Basically I'm trying to use Serial.readString() to input commands to the Serial Monitor but it shows an error that readString is not a member of 'HardwareSerial'.

I am using Arduino 1.0 as IDE because the device I'm using (Aceduino) seems to have a custom IDE derived from 1.0 so I'm not sure if it will work with newer IDE versions. Wondering if that was what's causing the eror

body:
`Stream::readString()` is available since version 1.0.1. See:

* the [changelog](https://github.com/arduino/Arduino/blob/master/build/shared/revisions.txt#L1038), and
* the [corresponding commit](https://github.com/arduino/Arduino/commit/39eed5a).


message:
Arduino Uno + cc3000 breakout board - read DOM instead of HTML

Is there a way to make the CC3000 read the DOM of a website instead of the HTML on the file?

I'm using the WebClient file which works fine and prints the HTML of the webpage, but the website I'm trying to read from has its HTML different from its DOM (ie: Javascript modifies the HTML once the page loads).

Can I use something other than `www.read()`?

body:
The DOM is something related to browsers. A web server merely serves up stored HTML and any accompanying JS to the client CC3000. It's up to a browser to parse the document, execute any JS to construct the DOM tree and finally render the webpage based on the DOM--not something an Arduino is built for.

I'm not an expert but you will have to forward the HTML from your Arduino to a browser and then somehow scrape the results after it renders the page. Or use a website that implements server-side rendering.


body:
To get a (programatically changed) DOM you need an HTML parser to construct the initial DOM (and something that runs Javascript to modify it).

The server only sends a file and does not store or send a DOM; a DOM is built by the receiving application, usually a browser.


message:
Can I connect my arduino ground to an external battery ground? Are they the same when said battery is powering the arduino?

I need to power my camera peripheral with an external power supply, since apparently I can't power both the camera and the camera's relay switch with my 5V out pin (My relays cut out and continually reset themselves if I try to run my 5V to both the camera relay switch and the relay board VCC.)

So I'm powering the camera with a 5V battery pack and my arduino with my PC, but I still need to communicate with it via UART, so I need the camera ground to be the same as my arduino ground. Can I connect the two? Is this a bad idea? Because I'm doing it now and it seems to work. I just don't want to cause a problem later on down the road, whether I'm connected to my computer or on battery power.Any advice would be greatly appreciated.

body:
A battery's ground is floating. That means that it's "happy" to take on any absolute value by simply connecting it to another ground - it just stops floating. This is why it's easy to connect a battery-powered phone directly to a computer to get the photos off or whatever.

The only time you shouldn't connect two grounds is if neither are floating. A good example would be the grounds of two different houses, which are physically connected to the Earth (as in the planet). It'd be difficult to budge the whole Earth's ground level!

But shouldn't they be the same? Unfortunately not. You could measure a distinct voltage difference (sometimes in the hundreds of volts) between two house earths due to the differences in their makeup.

One small note: if you do connect two grounds, only connect them in one spot. If you have two other ground pins a small distance away from the connected ones, there may be a voltage difference between them: now the two are explicitly relative to each other, so neither can be considered floating _relative to each other_. The pair as a system - if neither are earthed at least - is still floating.

These so-called "ground loops' can induce current where none is desired.


message:
What is the difference between running code with the scope of the void setup() or void loop() vs. outside their scope?

Good evening everyone,

I have bene playing around with making my own library, specifically for the controlling Timer1 on the Arduino Mega 2560. I'm sort of new to OOP but I am trying my hand at it here.

I wrote some code to generate a PWM wave with a 100 ms period and a 25% duty cycle, and I have Siglent SDS 1052DL, 50MHz oscilloscope that I'm using that verifies the code is successful. I am using clear-timer-on-compare-match mode and timer interrupts to generate the PWM wave. My code is below:

    #include "Timer1.h"

    Timer1 timer;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      timer.begin();
    }

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

I made a Timer1.cpp file and a Timer1.h to go along with this file. They are below.

Timer1.cpp

    #include "Arduino.h"
    #include "Timer1.h"

    float frequency = 10.0;
    float period_ms;
    float clock_pulse = 16.0;

    unsigned long opening_time = 25000;

    unsigned int ocr1a;
    unsigned int ocr1b;

    Timer1::Timer1() { // Object used to control 16-bit timer1

    }

    void Timer1::begin() {
      CRITICAL_SECTION_START; // Clear I bit
      CLEAR_TCCR1A; // Reset TCCR1A
      CLEAR_TCCR1B; // Reset TCCR1B
      SET_CTC_MODE; // Set to CTC mode
      DISABLE_TIMER1_INTERRUPTS; // Disable OCIE1A/B
      TCCR1B |= (1 << CS12); // 256
      period_ms = (1000.0f / frequency);
      ocr1a = 1000UL * (period_ms / clock_pulse);
      OCR1A = ocr1a;
      TIMSK1 |= (1 << OCIE1A);

      ocr1b = (unsigned int)float(opening_time) / clock_pulse;
      OCR1B = ocr1b;
      TIMSK1 |= (1 << OCIE1B);
      TCNT1 = 0; // Reset counter

      CRITICAL_SECTION_END; // Set I bit
    }

    ISR(TIMER1_COMPA_vect) {
      digitalWrite(13, HIGH);
    }

    ISR(TIMER1_COMPB_vect) {
      digitalWrite(13, LOW);
    }

Timer1.h

    #ifndef TIMER1_H
    #define TIMER1_H

    // ========== HANDY MACROS ========== //
    #define CLEAR_TCCR1A                  TCCR1A = 0
    #define CLEAR_TCCR1B                  TCCR1B = 0
    #define SET_CTC_MODE                  TCCR1B |= (1 << WGM12)
    #define DISABLE_TIMER1_INTERRUPTS     TIMSK1 &= ~((1 << OCIE1B) | (1 << OCIE1A))
    #define CLEAR_CLOCK_SELECT_BITS       TCCR1B &= ~((1 << CS12) | (1 << CS11) | (1 << CS10))

    #define CRITICAL_SECTION_START unsigned char _sreg = SREG; cli()
    #define CRITICAL_SECTION_END   SREG = _sreg

    class Timer1{
      public:
      // Constructor:
      Timer1();
      // Begin:
      void begin();

    };

    #endif // TIMER1_H

This code works exactly as I would expect. I originally had placed the whole block of code found in the Timer1::begin() method in the Timer1::Timer1() constructor method. When I did this, I was getting a completely different signal (2.04 ms period with about an 80% duty cycle). Is there a simple explanation for what is occurring?

body:
I believe you should be able to put your code back into the constructor if you move all the variable you defined with file scope in Timer1.cpp:

    float frequency = 10.0;
    float period_ms;
    float clock_pulse = 16.0;

    unsigned long opening_time = 25000;

    unsigned int ocr1a;
    unsigned int ocr1b;

...to the Timer1 class definition (either in the public or private section).  This way all the variables will have the scope of the class and the code should work the same regardless where in the class it is.


body:
In your test code, you declare `Timer1` in global scope. This means its
constructor will be called right when the program starts, even before
`main()` is called. The first thing the [Arduino `main()`][main] does is
to call [`init()`][init], which configures all the timers for PWM
operation, as expected by `analogWrite()`. Then, any initialization of
Timer1 done by the constructor will be undone by `init()`. That's why
you want to defer that initialization until `setup()`.

[main]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/main.cpp#L33
[init]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L241

**Edit**: I took the liberty to do a code review on your post. Below are
a few suggestions. I hope some of them might be useful.

1.  Put the empty constructor in the .h file, this avoids it being
    compiled into a real empty function.
2.  Qualify `frequency`, `clock_pulse` and `opening_time` as `const`,
    and make `period_ms` local to `Timer1::begin()`. This way all the
    floating point operations are performed at compile time and you
    don't get all the floating point support compiled into your program.
3.  Your `CRITICAL_SECTION_*` macros are redundant with
    [`ATOMIC_BLOCK(ATOMIC_RESTORESTATE)` from avr-libc][atomic]. But
    then, do you really need to block the interrupts the whole time?
4.  I don't find the other macros in Timer1.h really useful either: just
    put comments next to each access to a hardware register.
5.  I would set `TCCR1B` last: the timer starts counting the moment you
    set this register.
6.  You should subtract 1 from the values you set in `OCR1A` and
    `OCR1B`: the period and HIGH time are `OCR1A+1` and `OCR1B+1`
    respectively.
7.  You may want to round the period and HIGH time to the nearest
    integer. It may make no difference here but you users may want to
    change `frequency` and `opening_time`.
8.  Your variables `ocr1a` and `ocr1b` serve no useful purpose, they
    just needlessly eat RAM.
9.  You casting `opening_time` to `float`, then back to `unsigned int`,
    serves no useful purpose either.
10. You may want to replace `digitalWrite()` with direct port access, as
    this function is really slow and you are calling it from an ISR.

[atomic]: http://www.nongnu.org/avr-libc/user-manual/group__util__atomic.html

Below is my throw at Timer1.cpp. Note that `port` and `bit` could be
made private data of the class, and the pin number could be a parameter
to the `begin()` method.

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

    #include "Arduino.h"
    #include "Timer1.h"

    /* The three constants below can be tuned to taste:  */

    const float frequency    = 10;  // hertz
    const float opening_time = 25;  // milliseconds
    const int   pin          = 13;

    /* Nothing should need to change below this line. */

    const uint16_t prescaler = 256;
    const float f_timer = float(F_CPU) / prescaler;
    static volatile uint8_t *port;
    static uint8_t bit;

    void Timer1::begin() {
        // Prepare the output.
        port = portOutputRegister(digitalPinToPort(pin));
        bit = digitalPinToBitMask(pin);
        pinMode(pin, OUTPUT);

        // Configure Timer 1.
        TCCR1A = 0;  // undo the configuration done by...
        TCCR1B = 0;  // ...the Arduino core library
        TCNT1  = 0;  // reset counter
        OCR1A  = round(f_timer / frequency) - 1;
        OCR1B  = round(f_timer * opening_time * 1e-3) - 1;
        TIMSK1 = _BV(OCIE1A)   // enable TIMER1_COMPA interrupt
               | _BV(OCIE1B);  // enable TIMER1_COMPB interrupt
        TCCR1B = _BV(WGM12)    // CTC mode
               | _BV(CS12);    // prescaler = 256
    }

    ISR(TIMER1_COMPA_vect) {
        *port |= bit;
    }

    ISR(TIMER1_COMPB_vect) {
        *port &= ~bit;
    }