body:
In the past I uploaded the code below:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <DHT.h>

    #define DHTTYPE DHT22     // DHT 11
    #define DHTPIN D5
    DHT dht(DHTPIN, DHTTYPE);

    const char *ssid = " Hello_IOT";
    const char *pass = "12345678";
    String command;
    ESP8266WebServer server(8080);

    void respond(){
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      server.send(200, "text/html", "
Hello from Wemos R1 Mini
");
    }

    void outputJson(){
      char temp[400];
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      int tf = dht.readTemperature(true);
      snprintf(temp, 400, "{\"wittyCloud\" : [{\"location\" : \"any\" ,\
        \"temperatureInC\" :%d ,\
        \"temperatureInF\" :%d ,\
        \"humidity\":%d,\
        \"ldr\":%d\
        }]}",
      t, tf, h, analogRead(A0));
      server.send(200, "text/json", temp);
    }

    void setup(){
      Serial.begin(115200);
      pinMode(BUILTIN_LED, OUTPUT);
      Serial.println("Connect to access Point");
      WiFi.softAP(ssid, pass);
      IPAddress IPserver = WiFi.softAPIP();
      Serial.println(" IP address server : ");
      Serial.println(IPserver);
      server.on("/", respond);
      server.on("/json", outputJson);
      server.begin();
      server.onNotFound([](){
        command = server.uri();
        server.send(200, "text/plain", command);
      });
    }

    void loop(){
      server.handleClient();
      if(command.equals("/mati")){
        digitalWrite(BUILTIN_LED, HIGH); //turn off BUILTIN LED
      }
      if(command.equals("/hidup")){
        digitalWrite(BUILTIN_LED, LOW); //turn on BUILTIN LED
      }
    }

For learning purpose it worked, however when I modified it to the code below for WeMOS, to connect to my home wifi router, it creates instead an access point, and on opening the URL after connecting to the WeMOS access point it displays the web page of the updated code.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266mDNS.h>
    #include <ESP8266WebServer.h>
    #include "control.h"
    #include "webpage.h"
    #include <DHT.h>

    ESP8266WebServer server(80);
    const char* sid = "router+ssid";
    const char* passwd = "ssid_password";

    #define DHTTYPE DHT22     // DHT 22
    #define DHTPIN D5
    DHT dht(DHTPIN, DHTTYPE);
    const char* host = "nodemcu";

    void outputJson(){
      char temp[400];
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      int tf = dht.readTemperature(true);
      snprintf(temp, 400, "{\"wemos\" : [{\"location\" : \"bangalore\" ,\
        \"temperatureInC\" :- ,\
        \"temperatureInF\" :- ,\
        \"humidity\":-\
        }]}",
      t, tf, h);
      server.send(200, "text/json", temp);
    }

    void handleRoot(){
      const int nsize = 2300;
      char temp[nsize];
      delay(200);
      int h = dht.readHumidity();
      int t = dht.readTemperature();
      snprintf(temp, nsize,
        "%s\n</\div>\n\
        ",webpage::html);
      server.send(200, "text/html", temp);
    }

    void handleNotFound(){
      String message = "File Not Found\n\n";
      message += "URI: ";
      message += server.uri();
      message += "\nMethod: ";
      message +=(server.method()== HTTP_GET)? "GET" : "POST";
      message += "\nArguments: ";
      message += server.args();
      message += "\n";
      for(uint8_t i = 0; i < server.args(); i++){
        message += " " + server.argName(i)+ ": " + server.arg(i)+ "\n";
      }
      server.send(404, "text/plain", message);
    }

    void setup(void) {
      Serial.begin(9600);
      // config static IP
      IPAddress ip(192, 168, 1, 88);
      IPAddress gateway(192, 168, 1, 1);
      IPAddress subnet(255, 255, 255, 0);
      IPAddress dns(192, 168, 1, 1);
      WiFi.config(ip, dns, gateway, subnet);
      WiFi.begin(sid, passwd);
      Serial.println("");
      EEPROM.begin(512);

      // Wait for connection
      while(WiFi.status()!= WL_CONNECTED){
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(sid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());
      if(MDNS.begin(host)){
        Serial.println("MDNS responder started");
      }
      MDNS.addService("http", "tcp", 80);
      server.on("/", handleRoot);
      server.on("/json", outputJson);
      server.on("/control", control::toggleRelay);
      server.onNotFound(handleNotFound);
      server.begin();
      Serial.println(F("HTTP server started"));
    }

    void loop(void){
      server.handleClient();
    }

title: WeMOS creating soft access point from old code even when new code doesn't have it

Answers: 2

body: I had this issue with one of my chips. I eventually fixed it by using the SPIFFS uploader tool and uploading a blank "data" folder.

body:
> it creates instead an access point

Did you use setmode() to put it in station mode?

**wifi.setmode()**

Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

 - Station mode, where the NodeMCU device joins an existing network.
 - Access point (AP) mode, where it creates its own network that others can join.
 - Station + AP mode, where it both creates its own network while at the same time being joined to another existing network.
 - WiFi off.

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.

NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.

**Syntax**

    wifi.setmode(mode)

**Parameters**

mode value should be one of

 - wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
 - wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
 - wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
 - wifi.NULLMODE to switch off WiFi

**Returns**

current mode after setup

> WeMOS access point it displays the web page of the updated code

I think @Ciasto answered that part.


body:
I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.

Arduino code

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      rfid.init();
    }

    void loop() {
      if(rfid.isCard()) {
  if(rfid.readCardSerial()) {
          Serial.print(rfid.serNum[0], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[1], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[2], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[3], HEX);
          Serial.print(" ");
          Serial.print(rfid.serNum[4], HEX);
          Serial.println("");
          delay(1000);
        }
      }
      rfid.halt();
    }

C# code

    private void button1_Click(object sender, EventArgs e) {
      try {
        serialPort1.Open();
        serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
        textBox2.Text = "connected";
        serialPort1.Close();
      }
      catch(Exception ex) {
        textBox2.Text = "Com port disconnected";
      }
    }

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
      SerialPort sp = (SerialPort)sender;
      string indata = sp.ReadExisting();
      textBox1.Text = indata;
    }

title: Getting RFID tag data using C#

Answers: 1

body:
You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line

    serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use [`Invoke()`][1].

    private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
         SerialPort sp = (SerialPort)sender;
         //string indata = sp.ReadExisting();
         string indata = sp.ReadLine();
         //textBox1.Text = indata;
         Invoke(new Action<string>(
             (s) =>
             {
                 textBox1.Text = s;
             }
         ), indata);
    }

  [1]: https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx


body:
I am trying to send numeric data using ESP8266 to local network python server. Before that I am collecting data from sensors using Arduino UNO and then send it to ESP using hardware serial.

ESP8266 code:

    #include <ESP8266WiFi.h>

    const char* ssid     = "ssid";
    const char* password = "pass";

    const char* host = "192.168.1.103";

    String serial_data;

    WiFiClient client;

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

      // We start by connecting to a WiFi network

      Serial.println();
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());

       delay(5000);

      Serial.print("connecting to ");
      Serial.println(host);

      // Use WiFiClient class to create TCP connections

      const int port = 8888;
      if (!client.connect(host, port))
      {
        Serial.println("connection failed");
        return;
      }

    }

    void loop() {

      delay(200);

      while(Serial.available() <= 0)
      {
        //wait for arduino serial data
      }

      if(Serial.available()>0)
      {
        // This will send data to client via TCP
        Serial.println("Sent..");
        serial_data = String(Serial.read());
        client.print(serial_data);
      }
    }

Python Server code:

    import socket
    import sys
    from thread import *
    from peewee import *

    db = SqliteDatabase("data.db")

    class post(Model):
        timestamp = DateTimeField()
        current = TextField()

        class Meta:
            database = db

    #connecting to database
    def initialize_db():
        db.connect()
        db.create_tables([post], safe = True)

    initialize_db()

    HOST = '192.168.1.103'
    PORT = 8888 # Arbitrary non-privileged port

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print 'Socket created'

    try:
        s.bind((HOST, PORT))
    except socket.error , msg:
        print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
        sys.exit()

    print 'Socket bind complete'

    s.listen(10)
    print 'Socket now listening'

    #keep talking with the client
    #Function for handling connections. This will be used to create threads
    def clientthread(conn):
        #Sending message to connected client
        conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

        #infinite loop so that function do not terminate and thread do not end.
        while True:

            #Receiving from client
            data = conn.recv(1024)
            print data

            #send data to database
            post.create(
                current = data
            )

            reply = 'OK ->' + data
            if not data:
                break

            conn.sendall(reply)

        #came out of loop
        conn.close()

    #keep talking with the client
    while 1:
        #wait to accept a connection - blocking call
        conn, addr = s.accept()
        print 'Connected with ' + addr[0] + ':' + str(addr[1])

        start_new_thread(clientthread ,(conn,))

    s.close()

 After powering up ESP it successfully connects to server and then simulating arduino esp serial communication I am using serial monitor to send some numbers. Before I send anything server outputs number 240:

    Connected with 192.168.1.100:26137
    240

Then I am sending number 1 but on server terminal I get numbers 49 and 13. Sending numbers some 2 - 3 times and no more data are outputted to server terminal. Should I parse data received from serial to some form I can transmit it via TCP or data should be processed on server side?

title: Data transmission Serial to TCP

Answers: 1

body:
The numbers are ASCII Codes (here is [a chart](https://www.arduino.cc/en/Reference/ASCIIchart) from the Arduino website). 49 is the number 1, and 13 is a carriage return ('\n'). There should be a setting in the bottom right corner of Serial Monitor to change line ending, this should be set to "no line ending." If it is, than `client.print()` must be adding the carriage return, so you will need to remove it in Python. If you are only sending integers, replace

    serial_data = String(Serial.read());

with:

    serial_data = String(Serial.parseInt());

In the Python code I suggest adding a print statement to check if the connection is closed after

    #came out of loop
        conn.close()


body:
I installed UECIDE from Majenko but I couldn't register nor email him so I try it here.

When trying in install the MIDI library from 47 effects (https://github.com/FortySevenEffects/arduino_midi_library/releases/tag/4.3.1) I get the following error:

    Compiling Failed
    Analyzing Arduino_MIDI_Library_v4.3.1.zip ...
    Unable to detect any valid libraries in the archive.
    You may need to manually install it or re-package it properly.

How to solve this?

I tried install manually by copying files but that didn't result in anything.

title: Problems with installing MIDI library in UECIDE

Answers: 1

body:
The auto-install method only (currently) works with old single-arch style libraries. This one is a new multi-arch style library (though it doesn't use the multi-arch facilities).

You need to install it manually.  Simply that means extracting the zip file into "libraries" within your "UECIDE" folder in your documents (My Documents/UECIDE/libraries on Windows, or ~/Documents/UECIDE/libraries on Linux / OS X).

If UECIDE is open at the time you can use "Help -> Debug -> Rebuild internal structures" to re-scan the available libraries, or just close it and re-open it.


body: I am trying to install the Teensy loader software but I need to know where Arduino is installed. Does anyone know where in Fedora the Arduino files are?

title: Where is Arduino on Fedora?

Answers: 2

body:
It depends how you installed it.

If you downloaded the tarball and extracted it then it's wherever you extracted it.

If you used a package manager to install it then they could be anywhere - you should look at the package manager software fedora uses (yum? it's been a while) to see how to find what files a package installs.

If you are running a modern version of Arduino (I know Debian based packages are from the stone age) then the board manager installs will be in `~/.arduino15`

body:
Assuming you have installed the tool from the Fedora repositories (that is, using yum/dnf or from the Software tool), the command to run the IDE will be installed at `/usr/bin/arduino` and you can run it from the command line just by typing `arduino` — or do the same in the search box in GNOME Shell.

Most of the package itself, including examples and libraries, will be installed under `/usr/share/arduino`.

And, once you run that program, it will create a new "sketchbook location" at `~/Arduino` — that is, a folder named "Arduino" in your home directory. If you've run the IDE already, that folder will already exist.


body:
I have a constructor which looks like this:

    Preset::Preset(char* presetName, MIDICommand* MIDICommands[])
      _presetName = presetName;
      _MIDICommands = MIDICommands;
    }

`_MIDICommnads` is declared like this: `MIDICommand* _MIDICommands[];`.

When run, this throws the error below on the second line in the constructor:

`incompatible types in assignment of 'MIDICommand**' to 'MIDICommand* [0]'`

Why do I need to declare `_MIDICommands` as `MIDICommands**`, and not `MIDICommand* _MIDICommands[]`?

The array I pass is declared like this:

    MIDICommand* one =  new MIDICommand(1, 2);
    MIDICommand* two =  new MIDICommand(2, 2);

    MIDICommand* MIDICommandsA[] = { one, two };

EDIT:
When I pass in an array, should I just use `MIDICommand* MIDICommands`, or do I need the `[]` at the end?
Now I've taken them off, but then I get trouble with passing the array.

It doesn't find a matching function to call. Basically, this `MIDICommand* MIDICommandsA[] = { one, two };` doesn't match this `MIDICommand* MIDICommands` parameter.

EDIT 2:
So, I've solved the problem of passing the array. I changed the parameter in the constructor to `MIDICommand** MIDICommands`, and I just pass a pointer to the array.

Now the constructor looks like this:

    Preset::Preset(char* presetName, MIDICommand** MIDICommands)
    {
      Serial.println(MIDICommands[0]->getProgramChange());

      _presetName = presetName;
      _MIDICommands = *MIDICommands;

      Serial.println(_MIDICommands[0]->getProgramChange());
    }

I'm getting an error on the second `Serial.println`, telling me it is a non-pointer type. I'd like it to be a pointer, so that's what I am looking at now.

`_MIDICommands` is now declared like this: `MIDICommand* _MIDICommands`.

EDIT 3: When I try to loop through the array now, it seems I have lost the second element, and have only the first.

title: Set array to array passed as parameter in constructor

Answers: 1

body:
> _MIDICommnads is declared like this: MIDICommand* _MIDICommands[];.

This is the major error. That is an incomplete array type. The number of elements (and storage) is unknown.

To solve this you have decide on how the elements should be stored. Should the class allocate storage and copy the values given to the constructor or should a pointer to the vector be used.

One alternative is to use a template class and provide the max element size as a template class parameter.

Cheers!


body:
I currently working on my system that automatically water the plant based on the water requirement of the plant for one day . I have a java application that let the user input the water requirement of the plant and then the java application send it to arduino the arduino will receive the data and put it inside the variable and it will be use .. I use the following sensor/module ..

 - SOIL MOISTURE 2 PCS.
 - WATER FLOW SENSOR 2 PCS.
 - SOLENOID VALVE 2PS
 - WATER LEVEL SENSOR 1 PCS.
 - HUMIDITY SENSOR 1 PCS.
 - REAL TIME CLOCK DS3231

The data that the java app will send is the water requirements for 1 day for example 400ml , the 400ml will be used by the water flow sensor if the sensor reads that its already 400ml has pass in the tube the solenoid will close the pipe . And my system has a water tank the water sensor is attach to it and will check if the water in the tank is not low if low the arduino will send that data into the java app .. All the sensors reading will be save into database using the java application ..

Here is My Whole code for arduino , its not finish yet because i'm stuck thinking on how to arrange my code blocks . Sorry for my English please bear with me ..

    #include <DS3231.h>

    //PINS
    #define MOISTURE1 A15
    #define MOISTURE2 A14
    #define WATERFLOW1 A13
    #define WATERFLOW2 A12
    #define HUMIDITY A11
    #define RELAY1 9
    #define RELAY2 8
    #define ALARM 2

    DS3231  rtc(SDA, SCL);
    int DELAYNI = 1000;
    void setup() {
      // put your setup code here, to run once:
    pinMode(MOISTURE1, INPUT);
    pinMode(MOISTURE2, INPUT);
    pinMode(WATERFLOW1, INPUT);
    pinMode(WATERFLOW2, INPUT);
    pinMode(HUMIDITY, INPUT);
    pinMode(RELAY1, OUTPUT);
    pinMode(RELAY2, OUTPUT);

    rtc.begin();

    Serial.begin(9600);
    }

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

      //Some Code here to get the data send by java app and then assign it to each variable

      readMoistureStatus();
      readWaterLevel();
    }
    void readWaterLevel(){
      ///Some code here
    }

    void readMoistureStatus(){

     int  moistureOneSensorValue = analogRead(MOISTURE1);
     int  moistureTwoSensorValue = analogRead(MOISTURE2);

       // checking the moisture range for the first soil moisture
      if(moistureOneSensorValue >= 700){
        // in case of dry soil:
        RelayOne();

         delay(DELAYNI);
      }
      if((moistureOneSensorValue < 700) && (moistureOneSensorValue >= 300)){
        // in case of moist soil:

        delay(DELAYNI);
      }
      if(moistureOneSensorValue < 300){
        // in case of soggy soil:

        delay(DELAYNI);
      }
       //
       //
       // Checking the moisture range for the second soil moisture

      if(moistureTwoSensorValue >= 700){
        // in case of dry soil:
        RelayTwo();

         delay(DELAYNI);
      }
      if((moistureTwoSensorValue < 700) && (moistureTwoSensorValue >= 300)){
        // in case of moist soil:

        delay(DELAYNI);
      }
      if(moistureTwoSensorValue < 300){
        // in case of soggy soil:

        delay(DELAYNI);
      }

    }

    void RelayOne(){
      //Close or Open the Solenoid

      //Read the water flow if the set point is reach it will close the solenoid using the relay
    }

    void RelayTwo(){
      //Close or Open the Solenoid

     //Read the water flow if the set point is reach it will close the solenoid using the relay
    }

title: How to arrange my code block to make it work smooth and correct

Answers: 1

body:
I think that overall your code looks good but I don't understand why you need to log data every 1 seconds (DELAYNI = 1000; is approx 1 sec).
Although there's nothing wrong in placing the

    if(moistureOneSensorValue >= ...)
    ...
    ...
codeblock in your readstatus(), it's best to separate this out into a dosomething function. Alternatively, you can read the moisture status in the `void loop()` itself and then place a `switch` case in the `doSomething()` function.

You can also use the data from the RTC to check moisture and do something:

    void setup(){
    ...
    time = DS3231.time(); //Time at the beginning
    }

    void loop(){

    timeElapsed = now() - DS3231.time();//seconds elapsed

    if (timeElapsed >= DELAYNI){
        moisture1 = analogRead(MOISTURE1); // Read ADC value
        moisture2 = analogRead(MOISTURE2); // Read ADC value
        updateDatabase(time, moisture1, moisture2, relay1, relay2); //update the moisture values and statuses of the relays to the database
        switchRelays(moisture1,moisture2); // switch relay1 and relay2 depending on vals
    time = DS3231.time(); // Update the time

        }

    }


body: I'm working on a project where my arduino is receiving a voltage 0-5V, I need the output to be 10V always. Is there a way to do that?

title: Multiplying the voltage output

Answers: 1

body:
Assuming the 0-5 Volts is supposed to switch the output, in which case you want a program to control your output, then you will want to use a digital output pin to either switch a relay or a transistor that controls the 10 Volts put out to whatever it is that you are controlling.

Perhaps you want PWM which indicates a transistor circuit.  Hard to tell what you want from the way this is worded.

Taking your words literaly, "I need the output to be 10V always" then that simply means hard-wiring to a 10V power supply.   ;-)


body:
I am currently designing a hexapod with a total of 18 servos. I come from a computer science background and know little about electronics, so there is one thing which puzzles me.
Adafruit is selling this [servo shield][1]. It can power up to 16 servos while only using two pins. But it's quite expensive as it would cost me ~30€. Add the cost of an Arduino Uno and you are at >50€. At the same time I could just buy an Arduino Mega and power all Servos for a lower price.

I like to think that Adafruit wouldn't sell a uselessly overpriced product, so would there be any advantage to using this shield?

Bonus question: If I'd end up buying the shield, could I just power 16 Servos with the shield and 2 via the Arduino? Would there be any problems with that? Like a delay in the 16 motors or similar issues which could through my kinematics over bord? Would I have to buy two shields (which is not really an option at that price)? Any other suggestions I have not heard of are also very welcome!

If it is of any relevance, I am planning to buy [these servos][2] as they are pretty strong and come super cheap in bulk.

  [1]: https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/overview
  [2]: https://www.amazon.de/gp/product/B01KNWN8LW/ref=ox_sc_act_title_3?smid=AVYNBB3B5GFFF&psc=1

title: Arduino Mega vs servo shield

Answers: 3

body:
The idea of that particular servo shield is that it provides 16 PWM (pulse width modulation) channels. These are all operated simultaneously with no additional processing overhead on the Arduino.

The Arduino Uno itself does not offer 16 (or 18) hardware PWM channels but only 6 (see [here](https://www.arduino.cc/en/Main/arduinoBoardUno)). So driving 18 servos without an additional shield would require software PWM which requires some of the Arduino's ressources to be devoted doing the calculations. This may or may not interfere with the rest of your program.

Furthermore the Uno does only provide 14 dedicated digital GPIO pins in total (+6 multiplexed digital/analog pins, as [ZS6JMB's answer](https://arduino.stackexchange.com/a/37827/17196) points out), so additional hardware would* be required either way - or using an Arduino with more pins (such as the suggested Mega). The Mega however offers only 15 hardware PWM channels, leaving you with soft PWM again. (* assuming some pins will be needed for sensors or user interfacing).

An alternative is this [board](https://www.adafruit.com/product/815) or, uhm, well, cheaper clones if you like. It features the same chip as the shield but with a PCB half the size and thus skipping the "free use area". I expect it to behave the same way like the shield and operate with the same libraries as the both the shield and this board communicate only via I2C. Both can be chained (or stacked for the shield if you will) for up to 992 PWM outputs (62 boards).

body:
Most of those pen controllers or shields are o.o expanded or own generators. In this case, the resolution maxes out to be just shy of 8 bits.

There are better ways to do it. I can post the link later but I explored quite a few ways to drive multiple servos off of a timer on a pic or avr. The number of servos it can drive is determined by the length of off-duration a servo can tolerate, and number of gpio pins on a mcu.

here is the link: https://dannyelectronics.wordpress.com/2017/02/18/driving-multiple-servos-off-a-pic-timer2-ranged-extended/

it provides a few examples for its implementation on PIC and AVR. But the basic concept is the same.

No shield used and it runs in the background so it is full transparent to the user code.

body:
I need to correct an earlier poster: the number of PWM pins is irrelevant, since the servo library can control servos on any pins, even analog. That said, the servo library can only control 12 servos, but that has nothing to do with servo pins being PWM or not.

Same poster is also wrong on the number of pins, since the analog pins are fully capable of digital io just like the so-called digital pins. So an Uno has the 14 pins mentioned (0-13, although personally I never include 0 and 1 in that count since life's easier if they are left for serial) and 6 analog pins for a total of 20 (or 18 if you discount the serial Tx and Rx pins).


body: I want to run 4 microgear motor for an RC car with Arduino. Should I use L293d motor driver/L298n motor driver/L293d motor driver shield?? I am using N20 microgear motor with following rating: 6 V, 200 RPM and 120 mA with no load, 40 oz-in (2.9 kg-cm) and 1.6 A at stall.

title: Should I use motor driver or Motor driver shield?

Answers: 2

body:
The key differences between the [L293D](http://www.ti.com/lit/ds/symlink/l293.pdf) and the [L298](http://www.st.com/en/motor-drivers/l298.html) are these:

 - the L298 supports higher currents (up to 4 A with proper heat sink), the L293D is limited to 600 mA
 - the L298 has a higher operating voltage (up to 46 V), the L293D is limited to 36 V
 - the L298 is a dual full bridge driver whereas the L293D is a quadruple half bridge driver

Ok, what's the difference of two full bridges vs. four half bridges - it somehow sounds to be equal? In fact, when driving a DC motor that requires to reverse the polarity to reverse rotation a full bridge is required. This full bridge could now be provided by either of the L293D (two half bridges) or the L298 (one full bridge). If you on the other hand want to drive a four winding stepper motor (two phase bipolar) the L293D would be more helpful as it could drive two such steppers (using two separate half bridges) whereas the L298 would need to use both its full bridges and could therefore only operate one such stepper.

But since steppers are not part of this question this difference does not really matter and you could pick either chip with respect to the required current rating. A stall current of 1.6 A would be a serious problem for the L293D:

> Peak output current, I_O (nonrepetitive, t ≤ 100 μs): 1.2 A

Whether to use the chip or a driver board or a shield, to be honest, is mainly personal preference. Shields and driver boards come ready-to-use on a pretty printed circuit board which is probably their main benefit.

body:
The right driver module or shield depends on the motor. Do you know the voltage and the stall current of the motors ?

The L293D uses bipolar transistors for the output stage inside the chip and can only drive 600mA. It has a large voltage drop: the motor gets less voltage than the power voltage applied to the driver. Therefor it can be used with small 12V motors, but it does not work very well with 6V.
The L298N also uses bipolar transistors and also has a large voltage drop.
A mosfet driver like the DRV8833 works better with 6V, because it has a low voltage drop.

In small RC toys with four AA batteries, sometimes a H-bridge is made is transistors instead of using a special driver chip.

The very cheap motor shield with two L293D chips (originally designed by Adafruit) can drive four motors, but it uses many pins.

Bottom line: Everything depends on your motors. I suggest to use a mosfet driver.


body:
I was coding a class for "a kind of gun". I have this code for the classes:<br>
*Gun.h:*

    #ifndef Gun_h
    #define Gun_h

    #include "Arduino.h"

    class Gun
    {
      public:
        Gun(String identifier, String name, int teamIRCodes[]);
        String getIdentifier();
        String getName();
        int getIRCode();
      private:
        String _identifier;
        String _name;
        int _teamIRCodes[];
    };

    #endif
*Gun.cpp:*

    #include "Arduino.h"
    #include "Gun.h"

    Gun::Gun(String identifier, String name, int teamIRCodes[])
    {
      _identifier = identifier;
      _name = name;
      _teamIRCodes = teamIRCodes;
    }

    String Gun::getIdentifier(){
      return _identifier;
    }
    String Gun::getName(){
      return _name;
    }
    int Gun::getIRCode(){
      return _teamIRCodes[1];
    }
It returns me this error while compiling:

    sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

    Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

       _teamIRCodes = teamIRCodes;

                    ^

    exit status 1
    incompatible types in assignment of 'int*' to 'int [0]'

Answers: 2

body:
Ok, using this worked:<br>
Replace

    _teamIRCodes = teamIRCodes;
For

    for(int i = 0; i < (sizeof(teamIRCodes)/sizeof(int)) ;i++)
        _teamIRCodes[i] = teamIRCodes[i];
Needed to iterate through array, cannot copy full array.

body:
The issue is with flexible array `int _teamIRCodes[];` This is an old technique which I don't recommend. But if you want to use it, you need you use `malloc` to create a class object, adding on enough space for the array:

    // Allocate space for the class AND the array
    Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:

    for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
        gun->_teamIRCodes[i] = teamIRCodes[i];
    }

I think it's much simpler to use a pointer:

    int* _teamIRCodes;

Then you can make your ctor:

    Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
        _teamIRCodes = new int[numberOfCodes];
        // memcpy does the same thing as the for loop - copies the array
        memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
    }

And don' forget to add a dtor:

    ~Gun() {
        delete [] _teamIRCodes;
    }

Or, if `teamIRCodes` is persistent throughout the lifetime of the object, you can just use a pointer to it:

     class Gun {
         public:
         int *_teamIRCodes;
         int _numberOfCodes;
         Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
             _teamIRCodes = teamIRCodes;
             _numberOfCodes = numberOfCodes;
       };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).


body:
I have an LED project for which i'm using a 9v power supply. For part of the project I'm using an off the shelf LED driver that is compatible with 9v however I have one LED component that I want to drive with the attiny85 (random blinking pattern), which is not compatible with 9v.

Does it make any sense to power the attiny85 separately with say a 3v coin cell, while allowing my LEDs to draw from 9v? The attiny85 would only be tripping transistors. I assume the attiny85 itself doesn't consume much power so hopefully I wouldn't be changing out the coin cell too often.

I have a couple 5v buck converters on hand but they take up more space than a coin cell would.

P.S. It's a Guy Manuel Daft Punk Helmet.

title: Powering the attiny85 with a separate power source

Answers: 1

body:
> Does it make any sense...

Well, actually it does make sense and you already rationalize it in your question: less space consumed, expected life time of the coin cell is ok for your intended use case (though you could/should confirm the assumption about power consumption with the AVR's data sheet).

There is nothing wrong in powering the microcontroller with a different voltage than the "power" circuitry, assuming the ground lines are connected and the transistors mentioned are operated in a suitable mode, e.g. [open collector/open drain](https://en.wikipedia.org/wiki/Open_collector) type.


body:
I am trying to create a sketch that utilizes two arrays, one array to hold five buttons as input, assigned to pins, and another array to hold five musical notes.  I have attached a RGB LEDs with pull-down resistors and attached a 8 ohms resistor speaker.

The code is as followed:

     //Pentatonic Piano
     // C D E G A

     #define NOTE_C   262 //HZ
     #define NOTE_D   294 //HZ
     #define NOTE_E   330 //HZ
     #define NOTE_G   392 //HZ
     #define NOTE_A   440 //HZ

     const int SPEAKER = 9;   //speaker on pin 10
     const int BLED = 10;      //Blue LED on pin 9
     const int GLED = 6;      //Green LED on pin 6
     const int RLED = 5;      //Red LED on pin 3

     int buttonState = 0;

     //Button Array
     int Buttons[]= {11, 8, 7, 4, 3};

     //Tone Note Array
     int Notes[] = {NOTE_C, NOTE_D, NOTE_E, NOTE_G, NOTE_A};

     void setup()
     {
     pinMode(BLED, OUTPUT);
     pinMode(GLED, OUTPUT);
     pinMode(RLED, OUTPUT);
     pinMode(Buttons, INPUT);
     }

     void loop()
     {

       buttonState = digitalRead(Buttons);

       if (buttonState = Buttons[0])
       { tone(SPEAKER, Notes[0]);
        digitalWrite(BLED, LOW);
        digitalWrite(GLED, LOW);
        digitalWrite(RLED, HIGH);

       }
       else if (buttonState = Buttons[1])
       {tone(SPEAKER, Notes[1]);
        digitalWrite(BLED, LOW);
        digitalWrite(GLED, HIGH);
        digitalWrite(RLED, LOW);
       }
       else if (buttonState = Buttons[2])
       {tone(SPEAKER, Notes[2]);
        digitalWrite(BLED, HIGH);
        digitalWrite(GLED, LOW);
        digitalWrite(RLED, LOW);

       }
       else if (buttonState = Buttons[3])
       {tone(SPEAKER, Notes[3]);
        analogWrite(BLED, 127);
        analogWrite(GLED, 0);
        analogWrite(RLED, 127);

       }
       else if (buttonState = Buttons[4])
       {tone(SPEAKER, Notes[4]);
        analogWrite(BLED, 0);
        analogWrite(GLED, 127);
        analogWrite(RLED, 127);

       }

       else
       {
        digitalWrite(BLED, LOW);
        digitalWrite(GLED, LOW);
        digitalWrite(RLED, LOW);
        noTone(SPEAKER);
       }
     }

The problem is no matter what button I press, the RGB only emits a green light and there is absolutely no sound coming from the speaker.  I am truly stumped.

title: Utilizing Array with RGB

Answers: 1

body:
First, these statements:

    if (buttonState = Buttons[0])

are doing an assignment, not a test for equality. You want:

    if (buttonState == Buttons[0])
    //               ^Notice

Next, `pinMode` takes two integers, but you are passing an array. You can use a loop to call `pinMode` multiple times:

    for (int i = 0; i < sizeof(Buttons) / sizeof(Buttons[0]); i++) {
         pinMode(Buttons[i], INPUT);
    }

Same goes for `digitalRead()`. You need to read the state for each button:

    buttonState = digitalRead(Buttons[0]);
    if (buttonState == HIGH) {
       ....
    }
    buttonState = digitalRead(Buttons[1]);
    if (buttonState == HIGH) {
       ....
    }
    //etc


body:
I was working on an Arduino quadcopter project. I setup all my hardware and was having balancing problems with my software end. I am using an MPU-6050 gyro and accelerometer. I have calculated the angle of the quad in relation to the ground and was trying to implement these values by adjusting the output values to each of the four motors.

Here is some of my code:

        x=(-computedGyroAngleX-3.5)*10;
        y=(-computedGyroAngleY-2)*10;
        esc1.writeMicroseconds(rc_values[RC_CH1]+x-y);
        esc2.writeMicroseconds(rc_values[RC_CH1]+x+y);
        esc3.writeMicroseconds(rc_values[RC_CH1]-x-y);
        esc4.writeMicroseconds(rc_values[RC_CH1]-x+y);

If the quad is leaning forward I increase the power at the front of the quad and reduce it at the back. I do the same for the y axis. But I run into problems when I test out the quad. It flips over to the side or forward. How would I fix this?

title: How do you balance an Arduino quadcopter using calculated gyro values?

Answers: 1

body:
That was happening with me too. Check if the weight distribution of the drone is perfect. Lets say if the battery is placed a little more to one side of the frame than the other side, your drone will try to hover from the other side.
The center of gravity should be taken care of when the drone is not balancing properly.


body:
I'm trying to read the battery voltage using Arduino, using a 9V battery. I keep getting the same voltage (4.99). I connected my Arduino to Matlab so I'm only using the command `voltage=readVoltage(a,'pin')`. I'm very new to this, so any help would be appreciated.

 [![thats my circuit][1]][1]

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

title: Voltage transfer

Answers: 1

body: Analog inputs on the arduino will measure 5v maximum. If you want to mesure higher voltage you will have to use a voltage divisor circuit (resistors).


body:
I'm fairly new to Arduino (and C), but not to embedded electronics and programming.

I'm using an MFRC522 module (the common one) with a Nano, and getting some strange results. They are on a very simple custom PCB I've made (the only parts on it, except for a couple of LEDs on D4 & D5)
I'm using SS_PIN on 8, and RST_PIN on 7, which is changed from 10 & 9, because the board will also be using an NRF24L01 module on the SPI bus (not fitted yet).

And I'm using the MFRC522 library.
The DumpInfo example in the library works fine, but not the ReadNUID example.

When I bring a tag/card near the reader, the sketch (sometimes) gets some of its output to the serial monitor, but then (always) the board reboots and the startup messages appear again. This happens continuously while the card is near.

I have the RFID IRQ connected to pin D3, and while thinking that may be causing the problem, and trying all sorts of stuff, I found that it wasn't. In the process I did get the sketch to work, and have distilled the fix down to two seemingly superfluous lines of code:-

Added a null if statement at the start of loop:-
<!-- language-all: lang-cpp -->

    if (GotIRQ) {}

and defined a volatile variable for it to test:-

    volatile boolean GotIRQ=false;

Doesn't work if it's not volatile. (A clue?)

What Gives? Some dumb newbie mistake?

(I could post the entire code if required, but I've started again from the original source, and only made the 2 changes and 2 additions described above)

Here is the code:-

    /*
     * --------------------------------------------------------------------------------------------------------------------
     * Example sketch/program showing how to read new NUID from a PICC to serial.
     * --------------------------------------------------------------------------------------------------------------------
     * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
     *
     * Example sketch/program showing how to the read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
     * Reader on the Arduino SPI interface.
     *
     * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
     * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
     * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
     * will show the type, and the NUID if a new card has been detected. Note: you may see "Timeout in communication" messages
     * when removing the PICC from reading distance too early.
     *
     * @license Released into the public domain.
     *
     * Typical pin layout used:
     * -----------------------------------------------------------------------------------------
     *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
     *             Reader/PCD   Uno           Mega      Nano v3    Leonardo/Micro   Pro Micro
     * Signal      Pin          Pin           Pin       Pin        Pin              Pin
     * -----------------------------------------------------------------------------------------
     * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
     * SPI SS      SDA(SS)      10            53        D10        10               10
     * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
     * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
     * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
     */

    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN 8   //QQ This changed from 10
    #define RST_PIN 7   //QQ This changed from 9

    MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

    MFRC522::MIFARE_Key key;

    volatile boolean GotIRQ=false; //QQ needed for null if statement

    // Init array that will store new NUID
    byte nuidPICC[3];

    void setup() {
      Serial.begin(9600);
      SPI.begin(); // Init SPI bus
      rfid.PCD_Init(); // Init MFRC522

      for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
      }

      Serial.println(F("This code scan the MIFARE Classsic NUID."));
      Serial.print(F("Using the following key:"));
      printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
    }

    void loop() {
      if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

      // Look for new cards
      if ( ! rfid.PICC_IsNewCardPresent())
        return;

      // Verify if the NUID has been readed
      if ( ! rfid.PICC_ReadCardSerial())
        return;

      Serial.print(F("PICC type: "));
      MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
      Serial.println(rfid.PICC_GetTypeName(piccType));

      // Check is the PICC of Classic MIFARE type
      if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
        piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
        piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
        Serial.println(F("Your tag is not of type MIFARE Classic."));
        return;
      }

      if (rfid.uid.uidByte[0] != nuidPICC[0] ||
        rfid.uid.uidByte[1] != nuidPICC[1] ||
        rfid.uid.uidByte[2] != nuidPICC[2] ||
        rfid.uid.uidByte[3] != nuidPICC[3] ) {
        Serial.println(F("A new card has been detected."));

        // Store NUID into nuidPICC array
        for (byte i = 0; i < 4; i++) {
          nuidPICC[i] = rfid.uid.uidByte[i];
        }

        Serial.println(F("The NUID tag is:"));
        Serial.print(F("In hex: "));
        printHex(rfid.uid.uidByte, rfid.uid.size);
        Serial.println();
        Serial.print(F("In dec: "));
        printDec(rfid.uid.uidByte, rfid.uid.size);
        Serial.println();
      }
      else Serial.println(F("Card read previously."));

      // Halt PICC
      rfid.PICC_HaltA();

      // Stop encryption on PCD
      rfid.PCD_StopCrypto1();
    }

    /**
     * Helper routine to dump a byte array as hex values to Serial.
     */
    void printHex(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
      }
    }

    /**
     * Helper routine to dump a byte array as dec values to Serial.
     */
    void printDec(byte *buffer, byte bufferSize) {
      for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], DEC);
      }
    }

OK, trying to cut down to a minimal example has proved useful. It seems the problem is caused by the loop that stores the NUID, but not if the superfluous if statement is present. The code is :-

    // Cut down version of MFRC522 library ReadNUID example that exhibits strangle
    // problem of rebooting the board when a card is near the reader.
    // But only if:-
    // * the Store NUID loop is included
    // and
    // * the superfluous "if" statement at start of loop() is NOT present.
    // Changes from original example are indicated by comments starting with "//QQ"
    // (plus a lot of removed code)

    #include <SPI.h>
    #include <MFRC522.h>

    #define SS_PIN 8   //QQ This changed from 10
    #define RST_PIN 7   //QQ This changed from 9

    MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

    MFRC522::MIFARE_Key key;

    volatile boolean GotIRQ=false; //QQ needed for null if statement

    // Init array that will store new NUID
    byte nuidPICC[3];

    void setup() {
      Serial.begin(9600);
      SPI.begin(); // Init SPI bus
      rfid.PCD_Init(); // Init MFRC522

      for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
      }

      Serial.println(F("This code scan the MIFARE Classsic NUID."));
    }

    void loop() {
    //  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

      // Look for new cards
      if ( ! rfid.PICC_IsNewCardPresent())
        return;

      // Verify if the NUID has been readed
      if ( ! rfid.PICC_ReadCardSerial())
        return;

      Serial.print(F("PICC type: "));
      MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
      Serial.println(rfid.PICC_GetTypeName(piccType));

      // Store NUID into nuidPICC array //QQ does not fail if this loop is excluded
      for (byte i = 0; i < 4; i++) {
        nuidPICC[i] = rfid.uid.uidByte[i];
      }

      // Halt PICC
      rfid.PICC_HaltA();

      // Stop encryption on PCD
      rfid.PCD_StopCrypto1();
    }

title: MFRC522 ReadNUID example reboots unless I include a null if statement

Answers: 2

body: I'm assuming that the extra byte in the array is needed, possibly for a null terminator or whatever, and that the example code has a bug. I've had no further problems since changing the NUID[3] to NUID[4], so I'll leave this at that.

body:
You've defined this array to have three elements:

    byte nuidPICC[3];

those three elements are numbered 0, 1, and 2.

In this for loop:

    for (byte i = 0; i < 4; i++) {
        nuidPICC[i] = rfid.uid.uidByte[i];
      }

you are writing to position 3, which is out of bounds for that array.

Once you write out of bounds on an array the behavior is undefined.  Resetting is one common result.  But anything could happen.


body:
I am doing a school project and saw someone use an Arduino and a piece of wire as an antenna here: https://forum.arduino.cc/index.php?topic=88422.0

I've tested this experiment and it works, but I have searched the internet for some time now for some background knowledge or theory on why this works, and how does it?

If anyone knows anything about the arduino creating simple AM waves, could you please let me know about it or redirect me to another source.

For some context, in this school project I've got to explain the theory behind creating basic AM waves and amplitude modulation in general, then prove the theory by conducting this experiment which I prove it correct.

title: What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz

Answers: 2

body:
Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.

Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.

The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.

The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.

To understand more about *why* it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).

body:
It works because everything is wrong. A perfect sine wave of 800 kHz would not transmit very well with such a small wire as antenna.

The output signal is a digital pulse (PWM signal) with very sharp edges. Those edges create many harmonics as Majenko wrote. It is those high harmonic frequencies that can use that small wire as antenna. The receiver might get help of those harmonic frequencies to combine them with the base signal to be able to receive the base signal of 800kHz. The receiver might also receive the electrical field coupling (capacitive coupling) instead of really receiving radio signals. The electrical (capacitive) coupling might even be main part of what is received.

You could add a large antenna or a large open coil or a tuned circuit of a coil with a capacitor. That should increase the range, because that will transmit real radio signals.

The Arduino board with the wire can not be used to explain AM radio signals, because it is not a AM radio signal. You can also not use it to explain AM modulation, because there is no modulation (only on/off).
Do you know someone who has equipment to make modulated AM signals ?

Last but not least: it is illegal to transmit at 800kHz.


body:
In my recent project, I'm working with Arduino with JSON.

I made software on JSON. Now, I want to send data from this software to my Arduino. Serial communication is done between Arduino and JSON. But somehow, I can't able to get proper data from JSON to my Arduino. So, I google out and find library named `ArduinoJson`. And here, I found out example code. So, I tried out that code and modified based on my requirement.

Here, below is my code.

Now, Software sends me value. And I split it out into three variable MAP_Json, TPS_Json, and LOAD_Json.
In Arduino side, I have already the value of MAP, TPS, and LOAD.

So, now my main intention is to compare `MAP_Json with MAP` & `TPS_Json with TPS`. If they are matched then `LOAD_Json is added to LOAD`. But, when I try it out, then `LOAD_Json not added to LOAD`. I don't understand why this happened?

     #include <ArduinoJson.h>

    //----------------------------For MAP calculation----------------------------//
    float MAP_MIN = 0.85;
    float MAP_MAX = 1.90;

    int LOAD_MIN_MAP[] = {1, 2};
    int LOAD_MAX_MAP[] = {3, 4};

    float mMAP[2] = {};
    float yMAP[2] = {};

    int i, j, a;
    float MAP, mFinalMAP, yFinalMAP;

    //----------------------------For TPS calculation----------------------------//
    float TPS_MIN = 0.00;
    float TPS_MAX = 5.00;

    int LOAD_MIN_TPS[] = {1, 3};
    int LOAD_MAX_TPS[] = {2, 4};

    float mTPS[2] = {};
    float yTPS[2] = {};

    int k, l, b;
    float TPS, mFinalTPS, yFinalTPS;

    //----------------------------For LOAD calculation---------------------------//
    int LOAD_MIN = 2;
    int LOAD_MAX = 100;

    float injTime_MIN_LOAD[] = {8.00, 9.06};
    float injTime_MAX_LOAD[] = {10.60, 11.86};

    float mLOAD[2] = {};
    float yLOAD[2] = {};

    int m, n, c;
    float LOAD, mFinalLOAD, yFinalLOAD;

    //------------------------------ Variable ---------------------------------//

    float load;

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

    void loop()
    {
      //----------------------ARDUINO DATA-------------------------//

      //----------------------------MAP----------------------------//

      MAP = analogRead(A0) * (5.0 / 1023.0);

      for(a = 0; a < 2; a++)
      {
        mMAP[i] = (LOAD_MIN_MAP[a] - LOAD_MIN_MAP[a]) / (MAP_MAX - MAP_MIN);
        yMAP[j] = mMAP[i] * (MAP - MAP_MIN) + LOAD_MIN_MAP[a];
      }

      //----------------------------TPS----------------------------//

      TPS = analogRead(A1) * (5.0 / 1023.0);

      for(b = 0; b < 2; b++)
      {
        mTPS[k] = (LOAD_MAX_TPS[b] - LOAD_MIN_TPS[b]) / (TPS_MAX - TPS_MIN);
        yTPS[l] = mTPS[k] * (TPS - TPS_MIN) + LOAD_MIN_TPS[b];
      }

      //----------------TPS/MAP CALLIBRATION / LOAD----------------//

      mFinalTPS = (yMAP[1] - yMAP[0]) / (TPS_MAX - TPS_MIN);
      yFinalTPS = mFinalTPS * (TPS - TPS_MIN) + yMAP[0];

      mFinalMAP = (yTPS[1] - yTPS[0]) / (MAP_MAX - MAP_MIN);
      yFinalMAP = mFinalMAP * (MAP - MAP_MIN) + yTPS[0];

      LOAD = (yFinalTPS + yFinalMAP) / 2;

      Serial.print("T : ");
      Serial.print(TPS);
      Serial.print("\t");
      Serial.print("M : ");
      Serial.print(MAP);
      Serial.print("\t");
      Serial.print("L : ");
      Serial.print(LOAD);
      Serial.print("\t");

      while(!Serial)
      {
        // wait serial port initialization
      }

      StaticJsonBuffer<200> jsonBuffer;

      char json[] = "{\"TPS\":1.67, \"MAP\":1.83,\"LOAD\":30}"; // JSON DATA

      JsonObject& root = jsonBuffer.parseObject(json);

      // Test if parsing succeeds.
      if(!root.success())
      {
        Serial.println("parseObject() failed");
        return;
      }

      // Splitted JSON DATA

      float TPS_Json = root["TPS"];
      float MAP_Json = root["MAP"];
      float LOAD_Json = root["LOAD"];

      Serial.print("T_J : ");
      Serial.print(TPS_Json);
      Serial.print("\t");
      Serial.print("M_J : ");
      Serial.print(MAP_Json);
      Serial.print("\t");
      Serial.print("L_J : ");
      Serial.print(LOAD_Json);
      Serial.print("\t");

      //Compare JSON DATA and ARDUINO DATA

      if(TPS_Json == TPS && MAP_Json == MAP) //If matched
      {
        load = LOAD_Json + LOAD;            // Add LOAD_Json and LOAD
      }

      Serial.print("Final Load :");
      Serial.print(load);
      Serial.print("\n");
    }

**EDIT 1:** Improve question formatting

**EDIT 2:** Upload Complete code

title: Not able to add JSON data to Arduino data

Answers: 1

body:
Comparison of floating point values is nigh on impossible. They aren't as accurate as you may think anyway, and two values have to be precisely the same to be considered equal - not something that is easy to achieve (23.4893782 != 23.4892480).

Instead you should either round them to a specific precision, or take the difference between the two values and decide if they are "close enough".

E.g.:

    float diff = abs(TPS - TPS_Json);
    if (diff < 0.5) {
        // do something
    }


body:
I'm making a -12 to +12V DC regulated power supply, on which I want to measure voltage and current with Arduino (through a voltage divider, of course).

I'm not sure, how to either detect nor measure negative voltage. I could "detect" it via a Schottky diode, but I'd get about 0.3V voltage drop, but that's not what I want, because any voltage between 0.0V and -0.3V wouldn't be measured. I want also to be able to measure positive and negative voltage on the same Arduino analog input pin.

And furthermore, how to measure current, flowing into both ways? (not an AC current, but will change during operation).

I will make additional PCB for this application, so size and number of components isn't important at all.

title: Measuring voltage from -12 to +12 VDC

Answers: 1

body:
Measuring voltage
-----------------

Use the following interfacing circuit for measuring voltage:

[![Voltage translator][1]][1]

Resistors R1, R2, R3 (1% tolerance or better recommended) will map the voltage input range (-12 to +12V DC) to an output range that can be read will the Arduino ADC  (+0.5 to +4.5V DC, in order to have some slack from the top and bottom end of the ADC range). The actual theoretical input range would be -15 to 15V DC.

The optional (but recommended) Schottky diodes D1 and D2 will protect the Arduino analog IN pin that you connect to Vout from any input under/overvoltage outside the -15 to +15V DC range.

This is the resulting input to output voltage translation curve:

[![Voltage translator curve][2]][2]

Measuring current
-----------------

For measuring current, use a current shunt (i.e., a very low resistance resistor, in the milliohm range) and measure the voltage drop on it via a high input impedance differential amplifier, then sample the output of the amp with the Arduino ADC.

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

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

<!-- End schematic -->

Follow [this link][3] to an article in EE Times to learn more about the main options available for current measurements using a shunt.

  [1]: https://i.stack.imgur.com/9D0Kd.png
  [2]: https://i.stack.imgur.com/friCM.png
  [3]: http://www.eetimes.com/document.asp?doc_id=1279415


body:
I'm attempting to make a sensor that will record the duration and frequency of a pump going off. It always fires for at least 4 seconds, but the duration can be up to 7 days.  The vibration sensor I have is a SW-420, which I think will work. I'm fairly new at this, and I don't mind figuring out the actual code myself, but I'm running into newb problems.

 1. Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub? Is there a better solution?
 2. Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".
 3. The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

Bonus points if I can accomplish this without any additional libraries. I'd love to put this on an ESP8266.

Thanks for your help, I appreciate it.

title: Smooth out digital signal from SW-420 vibration sensor in order to record duration?

Answers: 1

body:
> Should I approach this as an interrupt that uses a callback while loop, or would it be better to look at it as a typical debounce sub?

No. If you want to use interrupts then just record the start time on one edge of the signal and subtract it from the current time on the other edge (not sure which edge is which on that sensor).

> Since the duration can (very rarely) exceed running for more than a few minutes, I'm wondering if I need an RTC module. The time is not very important, it just needs to be "close".

It depends how you define "close".  An RTC can give you better accuracy over long periods, yes, and the Arduino struggles with > 49 days by itself.

> The duration info will be fed to node-red via MQTT. I can count frequency in that system... I'm trying to decide if I should do remote frequency calculations, or try and wrap it into the firmware on the Arduino. Any suggestions for this?

What kind of frequency are you wanting? The frequency of the vibration itself, or the frequency at which some vibration occurs?  If the former the sensor you have won't do the job - that just tells you when there is vibration above a certain threshold.

To sense the actual frequency of vibration you need a more hands-on approach by the MCU. Either use the raw HDX-2 vibration sensor as used on the SW-420 (that's the blue tube at one end), or do it properly and use an accelerometer which you sample over time and perform an FFT on the sampled signal to isolate the different frequencies.


body:
    #include <LiquidCrystal.h>
    #define trigPin 12              // the trig pin to digital pin 12
    #define echoPin 13              // the Echo pin to digital pin 13
    #define led 8
    #include <Servo.h>
    Servo servoMain; // Define our Servo

    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup() {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led, OUTPUT);
      Serial.begin(9600); // Starts the serial communication
      lcd.begin(16, 2);
      servoMain.attach(11); // servo on digital pin 11
    }

    void loop() {
      servoMain.write(5);  // Turn Servo Left to 5 degrees
      delay(1000); // Wait 1 second
      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      if (distance < 3) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("PLEASE REFILL!");
        lcd.setCursor(0, 1);
      } else {
        digitalWrite(led, LOW);
      }
      if (distance < 6) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("U May Refill Now");
        lcd.setCursor(0, 1);
      } else {
        digitalWrite(led, LOW);
      }
      if (distance < 8) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Take it easy");
        lcd.setCursor(0, 1);
      }
      if (distance <= 16) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("FULL!!");
        lcd.setCursor(0, 1);
      }
      if (distance > 16 || distance <= 0) {
        Serial.println("Out of range");
      } else {
        Serial.print(distance);
        Serial.println(" cm");
      }
    }
    delay(1000);
  }
    }

title: Error compiling: expected unqualified id before token {

Answers: 1

body:
At line 82 you have the closing bracket of the loop function. Then after that you have:

      delay(1000);

    }
    }

Which is invalid.

If you format your code properly it's easy to see. Fix that and it will compile. Will it do what you want is an other question...

    #include <LiquidCrystal.h>
    #define trigPin 12        // the trig pin to digital pin 12
    #define echoPin 13        // the Echo pin to digital pin 13
    #define led 8
    #include <Servo.h>
    Servo servoMain; // Define our Servo

    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

    void setup()
    {
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(led, OUTPUT);
      Serial.begin(9600); // Starts the serial communication
      lcd.begin(16, 2);
      servoMain.attach(11); // servo on digital pin 11

    }
    void loop()
    {
      servoMain.write(5); // Turn Servo Left to 5 degrees
      delay(1000);     // Wait 1 second

      long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;

      if (distance < 3) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("PLEASE REFILL!");
        lcd.setCursor(0, 1);
      }
      else {
        digitalWrite(led, LOW);
      }

      if (distance < 6) {
        digitalWrite(led, HIGH);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("U May Refill Now");
        lcd.setCursor(0, 1);
      }
      else {
        digitalWrite(led, LOW);
      }

      if (distance < 8) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Take it easy");
        lcd.setCursor(0, 1);
      }

      if (distance <= 16) {
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("FULL!!");
        lcd.setCursor(0, 1);
      }

      if (distance > 16 || distance <= 0) {
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.println(" cm");
      }
    }
    delay(1000);

    }
    }


body:
I'm looking to have a button that, when pressed down, will mean that the script loaded on the Arduino doesn't run. So far I have:

    void setup() {
      pinMode(3, INPUT_PULLUP);
      if (digitalRead(3) == LOW) {
        while(1);
      }
      // Beginning the Keyboard stream
      Keyboard.begin();
      // then the rest of the code.

I have a push button soldered to the ground and 3 pin. Could you see what is wrong with the code?

title: Button to not run script

Answers: 2

body:
You need to move the code that checks the button into `loop()`. Put the code that you want to pause in the `if` block.

    void loop() {
        // Only execute if not pressed
        if (digitalRead(3) != LOW) {
            // Do stuff
        }
    }

body:
I would do it this way:

    void setup () {
        pinMode(3, INPUT_PULLUP);
    }
    void loop () {
        while (digitalRead(3)==LOW) {}; //do nothing, wait for release button
        // do all my stuff
    }

or even better I would use some LED to indicate, that the button is pressed (or released) to have some visual state indicator (or another stuff to do while the button is pressed

    void setup () {
        pinMode(3, INPUT_PULLUP);
        pinMode(13, OUTPUT);
        digitalWrite(13,LOW);
    }
    void loop () {
        while (digitalRead(3)==LOW) {
           digitalWrite(13,HIGH); // let it shine
           };
        digitalWrite(13,LOW);
        // do all my stuff
    }

eventually

    void setup () {
        pinMode(3, INPUT_PULLUP);
        pinMode(13, OUTPUT);
        digitalWrite(13,LOW);
    }
    void loop () {
        if (digitalRead(3)==LOW) {
           digitalWrite(13,HIGH); // let it shine
           while (digitalRead(3)==LOW) {
              // do some other stuff
           };
        digitalWrite(13,LOW); // switch indicator off
        // do my regular stuff
    }


body:
Is here some easy way to control bipolar motor
 without using any other external devices, drivers or shields? I have small motor from CD-ROM so I expect it's low voltage. By control I mean just turning clockwise  and anti-clockwise and speed. I'm looking for easy to make circuit not just direct control from Arduino.

title: Easy bipolar motor control?

Answers: 2

body:
No. You cannot directly drive any bare motor directly from an Arduino without any external components. To do so will damage the Arduino.

You need a motor driver (or at least some transistors and diodes etc) to control the motor.

body:
Taking a guess here, the current this motor requires will be exceeding the safe operation limits of the Arduino's GPIO pins. Furthermore without a [flyback diode](https://en.wikipedia.org/wiki/Flyback_diode) the voltage spike across the motor (an inductive load) when the current is reduced/switched off might kill the GPIO pin.

You will need a motor driver or transistor with flyback diodes to operate it.

[This](http://www.instructables.com/id/Run-A-CDROM-Brushless-Motor-With-Arduino/) is a nice tutorial that has it sorted out for a CD ROM brushless motor.


body:
I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.

    // timer interrupt 20Hz
    // reading sensors to buffer
    ISR() {
     int a = analogRead(A0);
     buffer.push(a);
    }

    void loop(){
     if buffer.isFull() {
      myFile.open("data.csv", FILE_WRITE);
      myfile.print(buffer.getData());
      myFile.close();
     }
    }

    // possibility of blocking data collection process
    RFduinoBLE_onConnect() {
     int freeSpace = SD.vwd()->fileSize();
        // other operations for monitoring data collection process
     RFduinoBLE.sendInt(freeSpace);
    }

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.

What is the recommended technique to make sure that data collection process will not be affected?

UPDATE:

The actual usage is that RFduinoBLE_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE_onConnect requests?

title: Avoid blocking from bluetooth callbacks

Answers: 1

body:
Well, one easy, but effective improvement is to use 2 buffers for writing data - while you are writing the one full to file, your interrupt can safely push values to the other and then after the other is full, your ISR would go to first one, while the second will be written. So even long open/seek/write/close loop does not get hit by new data arrival.

Then the main problem - RF - I would bet, that the on_connect() is called from interrupt too, as it is not mentioned anywhere in the loop(). In that case you would like to have it as small and fast as possible. So if you are only providing data, I would collect all the data in the main loop() in some variable (structure, class, what you need), get it thread safe as much as possible (atomic operations, or have two instancies, one actually enabled for the callback, the other opened for filling new data, then pointers to point which is which and just reassigning those pointers in atomic way (means disable interrupts, swich two pointers, enable interrupts - interrupts can wait for time need to two pointers be changed - on other hand you have no chance do anything in main loop (as disabling interrupts), while interrupt is actually running)

So (I know, it is just example, but) you know, that fileSize() is changed only after file is written - so save its value to some (volatile, of course) variable each time you write to the file and use that variable in onConnect.

So more like this (did not tested it, just idea):

    volatile buffs[2];
    volatile actBuff;
    // timer interrupt 20Hz
    // reading sensors to buffer
    ISR() {
        int a = analogRead(A0);
        buffs[actBuff].push(a);
    }

    volatile int freeSpace;
    void loop(){
        if buffs[actBuff].isFull() {
            int fullBuff=actBuff;
            cli();             // disable global interrupts
            actBuff = 1 - actBuff; // switch actual Buffer between 0 and 1
            sei();// enable global interrupts
            // ISR have nice free buffer to fill, we will write and empty the old one
            myFile.open("data.csv", FILE_WRITE);
            myfile.print(buffs[fullBuff].getData());
            myFile.close();
            buffs[fullBuff].empty()
            int tempval = SD.vwd()->fileSize();
            cli();             // disable global interrupts
            freeSpace = tempval;
            sei();// enable global interrupts:
        }
    }

    // possibility of blocking data collection process
    RFduinoBLE_onConnect() {
        // int freeSpace = SD.vwd()->fileSize();
        // do the same trick here // other operations for monitoring data collection process
        RFduinoBLE.sendInt(freeSpace); // use the value from loop
    }


body:
I'm working with I2C to work with my LCD 1602 and the I2C adapter.

This module has 16 pins and I don't know how to communicate with it.

I2C sends 8-bit packets. What are the commands to deal with this module, because it has 16 pins?

This is my current code:

<!-- language: lang-cpp -->

    void I2C_init(void);
    void I2C_start(void);
    void I2C_stop(void);
    void I2C_tx(uint8_t data);
    void I2C_TWSR_Check(void);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      I2C_init();
      I2C_TWSR_Check();
      I2C_start();
      I2C_TWSR_Check();
      I2C_tx(0x20);
      I2C_TWSR_Check();
    }

    void loop() {
      uint8_t i;

      for (i = 0; i < 5; i++)
      {
        I2C_tx(0xff);
        I2C_TWSR_Check();
        _delay_ms(500);
      }
    }

    void I2C_init(void) {
      //set SCL to 100kHz
      TWSR = 0x00;
      TWBR = 0x48;
      //enable TWI
      TWCR = (1 << TWEN);
    }

    void I2C_start(void) {
      TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
      while (!(TWCR & (1 << TWINT)));
    }

    void I2C_stop(void) {
      TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
    }

    void I2C_tx(uint8_t u8data) {
      TWDR = u8data;
      while (!(TWCR & (1 << TWINT)));
    }

    void I2C_TWSR_Check(void) {
      uint8_t Status;
      Status = TWSR & 0xF8;
      switch (Status)   {
        case 0x08:    // start OK
          Serial.println("Start is OK");
          break;
        case 0x10:    // Re start
          Serial.println("Re start");
          break;
        case 0x18:        // SLA+W OK ACK
          Serial.println("SLA+W OK ACK");
          break;
        case 0x20:        // SLA+W no ACK
          Serial.println("SLA+W no ACK");
          break;
        case 0x28:        // data OK ACK
          Serial.println("data OK ACK");
          break;
        case 0x30:        // data OK no ACK
          Serial.println("data OK no ACK");
          break;
        case 0x38:        // arbitration lost in SLA+W or data TX
          Serial.println("arbitration lost in SLA+W or data TX");
          break;
        default:
          Serial.println("Error");
          break;
      }
    }

I don't know I get first case working all the time. I can't proceed to sending the data.

This is the most I got from google images:
[PCF8574 I2C backpacks for HD44780 Compatible LCD Module Arduino Raspberry][1]

  [1]: http://www.wtihk.com/image/cache/catalog/arduino/module/I2C_LCD/I2C_backpack_for_LCD_modules_layout-500x500.png

title: How to find the pin map for the LCD 1602 I2C adapter module?

Answers: 1

body:
The ￼[tronixstuff page about PCF8574-based backpacks for LCD modules and Arduino](http://tronixstuff.com/2014/09/24/tutorial-serial-pcf8574-backpacks-hd44780-compatible-lcd-modules-arduino/) (with [material that also appears in an instructable](http://www.instructables.com/id/Using-PCF8574-backpacks-with-LCD-modules-and-Ardui/)) includes a sketch that most likely will work with that backpack.

Once you've identified which I2C library to use, and the appropriate object instantiation, most of the general API description (that is, “the commands to deal with this module”) as shown at [arduino.cc's *LCDi2c Library*](http://playground.arduino.cc/Code/LCDi2c) page and at [arduino.cc's *LCD API 1.0*](http://playground.arduino.cc/Code/LCDAPI) page will apply.

The I2C library-include and the appropriate object instantiation for the backpack shown in your link probably will look much like:

    #include <LiquidCrystal_I2C.h>
    ...
    LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);

For documentation of what the numbers mean, see lines 82 to 90 of LiquidCrystal_I2C.h:

    @param      lcd_Addr[in] I2C address of the IO expansion module. [...]
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d4[in] LCD data 0 pin map on IO extender module
    @param      d5[in] LCD data 1 pin map on IO extender module
    @param      d6[in] LCD data 2 pin map on IO extender module
    @param      d7[in] LCD data 3 pin map on IO extender module

Briefly, 0x27 is the I2C address of the PCF8574 chip on the backpack.  Note, if your backpack has a PCF8574A, its address is 0x3F.

The other seven numbers describe which PCF8574 output pin is connected for each designated purpose.  Most PCF8574/PCF8574A I2C backpacks are wired the same and numbers 2,1,0,4,5,6,7 are appropriate.

---

*Edit 1:* If you write an LCD-with-backpack library of your own and expect to publish it, it is reasonable to comply with the [LCD API mentioned earlier](http://playground.arduino.cc/Code/LCDAPI).  By using standard interface functions, you will make it possible for users to plug in your library in place of others with the same interface.  In addition, the availability of sketches using the LCD API provides you with a range of test material to verify your drivers.

In writing an LCD-with-backpack library, start by solidifying your understanding of each of the parts – LCD and backpack – separately.

**LCD:**  Get some HD44780-based LCD units; hook one up using direct wiring or a shield rather than a backpack; install a known-good library and sketch; run tests to verify the wiring.  With the wiring known to work, develop an LCD control library.  This may require detailed study of the Hitachi HD44780U data sheet or other HD44780 data sheets.  The necessary timing for LCD control is picky enough that it would be a fool's errand to not verify the wiring using known-good software before writing your own.

**Backpack:**  Plug the 16 pins of a backpack into a breadboard, and attach LED cathodes to all the breadboard pins that connect to PCF8574 output pins.  Use appropriate resistors to V+ on the anode sides of the LEDs.  Connect the backpack's SDA, SCL, V+, and ground to that of your Arduino.  Write simple test software using `Wire.h` calls to send data to the PCF8574, verifying proper operation using the LEDs.  This may require detailed study of the Texas Instruments *PCF8574 Remote 8-Bit I/O Expander for I2C Bus* data sheet.  Write your PCF8574 control library.  Adapt your LCD control software to send data via the PCF8574 library instead of via direct wiring.


body:
The task I need to accomplish is as follows:

I have an analog/digital converter that sends out a 10-bit signal. This signal needs to be transferred to an Arduino Uno using the SPI protocol. Because the SPI protocol works with a 16 bit pattern I need to expand the incoming signal. The slave Arduino then needs to put out the transferred number in decimal.

I imitated the ADC with another Arduino Uno, setting it as master, but unfortunately at the time I only had one Arduino so I couldn't test my code. Furthermore, I don't really have a clue how to "expand" a 10-bit signal to a 16-bit one. Can someone please explain it to me and have a look at my code?

Code for the master Arduino:

    #include <SPI.h>
    #define SS 10
    #define MOSI 11

    void setup() {
      pinMode(SS, OUTPUT);
      pinMode(MOSI, OUTPUT);
      SPI.beginTransaction(SPISettings(62500, LSBFIRST, SPI_MODE0));
    }

    void loop() {
      byte x=0000001101;
      byte y=0011111111;
      digitalWrite(SS,LOW);
      SPI.transfer(x,y);
      digitalWrite(SS,HIGH);
      delay(1000);
    }

Code for the slave Arduino:

    #include <SPI.h>
    #define SS 10
    #define MOSI 11

    void setup() {
      pinMode(SS, INPUT);
      pinMode(MOSI, INPUT);
    }

    void loop() {
      byte x=SPDR;
      byte y=SPDR;
      printf(x,DEC);
      printf(y,DEC);
      delay(1000);
    }

title: Transfer 10-bit via Arduino-to-Arduino SPI protocol

Answers: 1

body:
A byte is only 8 bits, so your code:

      byte x=0000001101;
      byte y=0011111111;

won't do what you think it does.

A 10 bit value will be stored as an int (which is 16 bits) or 2 bytes.

Assuming it is an int then this will convert it to two bytes.

     const int adcData = 0x03FF;  // From ADC
     byte dataToSend[2] = {0, 0}; // Initialise it to zeros
     dataToSend[0] = (adcData & 0xFF00) >> 8;  // didn't really need the bit mask just to make it clearer.
     dataToSend[1] = (adcData & 0x00FF);
     // Now send dataToSend via the SPI bus.

To reassemble the data on the otherside:

     byte dataReadFromSPI[2];  // Filled with the data read from the SPI
     int adcData = 0;
     adcData = (dataReadFromSPI[0] << 8) | (dataReadFromSPI[1]);


body:
Hi I am trying to make `Arduino Uno` on local network with the help of ESP8266 wifi module.

I tried to search on internet, found mostly they are making `ESP8266` as web server.http://circuits4you.com/2016/12/16/esp8266-web-server-html/

Can anyone help me how to add `Arduino Uno` on network with the help of `ESP8266`.
[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/sVmx8.jpg
  [2]: https://i.stack.imgur.com/ceO4o.jpg

title: How to connect an Arduino to WIFI using an ESP8266

Answers: 2

body:
It depends on how you want to approach it.  I know of two options:

1. Use AT commands.
2. Program the ESP.

When you are using AT commands you need to program the Arduino to open a serial line to the ESP (ensuring rx and tx are crossed over).  You tell the Arduino to send the AT commands you need to the ESP and wait for each one to be acknowledged.  Then the Arduino sends its network data via the serial connection, to the ESP and the ESP will forward it to the network.

You can program the ESP in EXACTLY the same way as you would the Arduino.  You could write some code to accept data from the Arduino over either Serial, SPI, I2C or your own proprietary communication method.  The ESP has libraries to be a DHCP client, DNS, HTTP client, etc. (most of which you have probably seen already).  If you then write a simple application that establishes the connection to the network and then waits for a packet of data from either the Arduino or the network and forwards it as appropriate.

I can't tell you which option is best, because I have never tried either method.  I just program the ESP to do everything that the Arduino would have done anyway and simplify the code.

body:
Sending the following commands to the ESP should get you started:

    AT+RST                         # Reset
    AT+CWMODE=1                    # Set to station-mode as a client
    ATE0                           # turn off command echo
    AT+CWLAP                       # optional: list access points
    AT+CWJAP_DEF="SSID","PASSWORD" # Always connect to this SSID

(I made-up the comment syntax; don't try to send those.) The full
[ESP8266 AT Instruction Set][1] has the complete set of commands and a functional description of each one.

Update:
> ... do I need to connect RX of ESP8266 to RX of Arduino, TX of ESP8266 to
> TX of Arduino, Ground of Arduino to RESET ?

Rx & Tx must be cross-connected with the corresponding Arduino pins and the ESP's reset pulled high (3.3v).

  [1]: https://espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf


body:
I want to know if it is possible to set an alarm in DS3231.
I want to set the alarm every 6 AM in the morning. Is this possible?

title: How to set alarm on DS3231 sensor?

Answers: 2

body:
Yes it is (see datasheet [datasheet][1]) ... the DS3231 has 2 alarms.

There is also a library for the Arduino, see: [library][2].
The alarm(s) can be set (repeatedly) via one of the following functions:

    Alarm.alarmRepeat(hours, minutes, seconds, function);
    Create an alarm that will call a function every day at a particular time.

    Alarm.alarmRepeat(dayofweek, hours, minutes, seconds, function);
    Create an alarm that will call a function every week on a specific day at
    a particular time.

     "dayofweek" can be dowSunday, dowMonday, dowTuesday, dowWednesday,
     dowThursday, dowFriday, or dowSaturday.

Detailed info and more functions: [link][3]

  [1]: https://datasheets.maximintegrated.com/en/ds/DS3231.pdf
  [2]: http://playground.arduino.cc/Code/Time
  [3]: https://www.pjrc.com/teensy/td_libs_TimeAlarms.html

body:
I find the answer to my question .
I just add `Time  t;` and `t = rtc.getTime();` into my code then an if statement like this `if (t.hour == 11 && t.min == 59 && t.sec == 00)`

ref http://www.instructables.com/id/Setup-for-DS3231-AlarmTimer-Function/


body:
Could someone give me a hint regarding what would be the best practice to save memory: should I `#define` strings or use local `static const char` arrays?

Code example, option #1:

    #define    LCD_LIMIT "Number of hours"
    ...
    setup(){
        DisplayData(LCD_LIMIT, actual_Data);
    }
    ...
    void DisplayData(const char *theme, String data){
    }

Code example, option #2:

    setup(){
        DisplayData(actual_Data);
    }
    ...
    void DisplayData(String data){
        static const char theme[] = "Number of hours";
    }

Cheers

title: #define VS local static const char

Answers: 2

body:
I think they both are similar with respect to memory stored in the heap.

However, since you pass one extra pointer, it cost 2 of 4 bytes extra on the stack (temporary space).

To save more memory use the F() function to store it in FLASH (32 KB on Arduino Uno) instead of the heap (only 2 KB). By using

    static const char theme[] = F("Number of hours");

body:
The #define will be substituted in at compile time. So as far as memory usage goes

    #define MYSTRING "hello world"
    DisplayData(MYSTRING);

and

    DisplayData("hello world");

are completely identical.

but

    static const char theme[] = "hello world";
    DisplayData(theme);

Will store the text in memory and then call DisplayData with a pointer to that memory location. This will require one memory pointers worth of memory extra (unless that is the compiler is being smart that day and realizes it can substitute in the string and save a few bytes).

However if you are using the same string twice or more then things are different.

The static const will only include the string once and then point to it each time, each reference to the string adds only a couple of bytes to the code size.
If you #define the string then every time it is referenced the whole string is inserted into the code at a cost of n+1 bytes where n is the string length.


body:
We need to read two readings of Humidity and Temperature from 2 different locations. We can run each of them separately but we don't know how we can make them work simultaneously in one program. We are using a TH02 sensor that we connect to I2C and DHT11 that is connected to one of the Analog port.

We are connecting them to Grove base shield V2, which is on top of Arduino uno wifi.

TH02 Code:

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

    Serial.println("****TH02_dev demo by seeed studio****\n");
    /* Power up,delay 150ms,until voltage is stable */
    delay(150);
    /* Reset HP20x_dev */
    TH02.begin();
    delay(100);

    /* Determine TH02_dev is available or not */
    Serial.println("TH02_dev is available.\n");
    }

    void loop()
    {
    float temper = TH02.ReadTemperature();
    Serial.println("Temperature: ");
    Serial.print(temper);
    Serial.println("C\r\n");

    float humidity = TH02.ReadHumidity();
    Serial.println("Humidity: ");
    Serial.print(humidity);
    Serial.println("%\r\n");
    delay(1000);
    }

DHT11 Code:

    byte read_dht11_dat()
    {
    byte i = 0;
    byte result=0;
    for(i=0; i< 8; i++){

        while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
        delayMicroseconds(30);

        if(PINC & _BV(DHT11_PIN))
        result |=(1<<(7-i));
        while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
    }
    return result;
    }

    void setup()
    {
    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    Serial.begin(9600);
    Serial.println("Ready");
    }

    void loop()
    {
    byte dht11_dat[5];
    byte dht11_in;
    byte i;
    // start condition
    // 1. pull-down i/o pin from 18ms
    PORTC &= ~_BV(DHT11_PIN);
    delay(18);
    PORTC |= _BV(DHT11_PIN);
    delayMicroseconds(40);

    DDRC &= ~_BV(DHT11_PIN);
    delayMicroseconds(40);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(dht11_in){
        Serial.println("dht11 start condition 1 not met");
        return;
    }
    delayMicroseconds(80);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(!dht11_in){
        Serial.println("dht11 start condition 2 not met");
        return;
    }
    delayMicroseconds(80);
    // now ready for data reception
    for (i=0; i<5; i++)
    dht11_dat[i] = read_dht11_dat();

    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
    // check check_sum
    if(dht11_dat[4]!= dht11_check_sum)
    {
        Serial.println("DHT11 checksum error");
    }

    Serial.print("Current humdity = ");
    Serial.print(dht11_dat[0], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[1], DEC);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(dht11_dat[2], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[3], DEC);
    Serial.println("C  ");

    delay(2000);
    }

title: Combining code for two sensors in one programming

Answers: 1

body:
This example combines both codes but uses a single `delay`. If you want readings at two different times you should use two `unsigned long` global variables to store the `millis()` of the last time the functions were called. Then you use an `if` statement to only call `readTH02()` or `readDHT11()` when the last `millis` is less than the `<= current-interval`.

It is better to use `millis` interval checking instead of delays but I have not made significant changes to your code to implement that. Take a look at the Arduino IDE example called `BlinkWithoutDelay` to understand how to use intervals instead of `delay()`

    void setup()
    {
      setupTH02();
      setupDHT11();
    }

    void loop()
    {
      readTH02();
      readDHT11();

      delay(1000);
    }

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

    Serial.println("****TH02_dev demo by seeed studio****\n");
    /* Power up,delay 150ms,until voltage is stable */
    delay(150);
    /* Reset HP20x_dev */
    TH02.begin();
    delay(100);

    /* Determine TH02_dev is available or not */
    Serial.println("TH02_dev is available.\n");
    }

    void readTH02()
    {
    float temper = TH02.ReadTemperature();
    Serial.println("Temperature: ");
    Serial.print(temper);
    Serial.println("C\r\n");

    float humidity = TH02.ReadHumidity();
    Serial.println("Humidity: ");
    Serial.print(humidity);
    Serial.println("%\r\n");
    //delay(1000);
    }

    byte read_dht11_dat()
    {
    byte i = 0;
    byte result=0;
    for(i=0; i< 8; i++){

        while(!(PINC & _BV(DHT11_PIN)));  // wait for 50us
        delayMicroseconds(30);

        if(PINC & _BV(DHT11_PIN))
        result |=(1<<(7-i));
        while((PINC & _BV(DHT11_PIN)));  // wait '1' finish
    }
    return result;
    }

    void setupDHT11()
    {
    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    Serial.begin(9600);
    Serial.println("Ready");
    }

    void readDHT11()
    {
    byte dht11_dat[5];
    byte dht11_in;
    byte i;
    // start condition
    // 1. pull-down i/o pin from 18ms
    PORTC &= ~_BV(DHT11_PIN);
    delay(18);
    PORTC |= _BV(DHT11_PIN);
    delayMicroseconds(40);

    DDRC &= ~_BV(DHT11_PIN);
    delayMicroseconds(40);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(dht11_in){
        Serial.println("dht11 start condition 1 not met");
        return;
    }
    delayMicroseconds(80);

    dht11_in = PINC & _BV(DHT11_PIN);

    if(!dht11_in){
        Serial.println("dht11 start condition 2 not met");
        return;
    }
    delayMicroseconds(80);
    // now ready for data reception
    for (i=0; i<5; i++)
    dht11_dat[i] = read_dht11_dat();

    DDRC |= _BV(DHT11_PIN);
    PORTC |= _BV(DHT11_PIN);

    byte dht11_check_sum = dht11_dat[0]+dht11_dat[1]+dht11_dat[2]+dht11_dat[3];
    // check check_sum
    if(dht11_dat[4]!= dht11_check_sum)
    {
        Serial.println("DHT11 checksum error");
    }

    Serial.print("Current humdity = ");
    Serial.print(dht11_dat[0], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[1], DEC);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(dht11_dat[2], DEC);
    Serial.print(".");
    Serial.print(dht11_dat[3], DEC);
    Serial.println("C  ");

    //delay(2000);
    }


body:
I'm trying to make a lamp that fades when it reacts with surrounding light. I've installed a library from github  that doesn't require the delay (). The serial monitor doesn't refresh.
The lamp is supposed to fade from 0-255 when in the dark and fade 255-0 when in light. It's supposed to happen only once so I can't put it in loop().

The LED is connected to PWM pin 10. The LDR sensor is connected to A0.

    #include <LEDFader.h>
    int sensorvalue = analogRead(A0);
    LEDFader led = LEDFader(10);

    void setup(){

      if(sensorvalue<=380){
        led.set_value(0);
        led.fade(255, 3000);
      }
      if(sensorvalue>=555){
        led.set_value(255);
        led.fade(0,3000);
      }
    }

    void loop() {
      Serial.begin(9600);
      Serial.println(sensorvalue);
      led.update();
   }

title: Serial monitor isn't updating in while loop

Answers: 1

body:
Arduino does not work that way. You only try to read a sensor value outside of a function, so will happen once only, if it works at all. You need to read the sensor more often and always read from within a function.

`Serial.begin()` is used once when the code starts, so that will be in the setup()

Your LED fade values are only set one time, when the cpu starts because you have the fade in the `setup()`.

In the following example we do all fade code in the `loop()` but change the fade values only when the sensor reading changes.

    #include <LEDFader.h>
    LEDFader led = LEDFader(10);

    int sensorValue = 0;
    int sensorValueLast = 0;

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

    void loop()
    {
      sensorValue = analogRead(A0);
      Serial.println(sensorValue);

            if (sensorValueLast!=sensorValue)
            {
              sensorValueLast = sensorValue;
              if(sensorvalue<=380)
              {
                 led.set_value(0);
                 led.fade(255, 3000);
              }
              if(sensorvalue>=555)
              {
                led.set_value(255);
                led.fade(0,3000);
              }
            }

      led.update();
    }

This example only calls `led.fade()` when the sensor value changes but uses the same sensor reading that was found during startup. The sensor is read just once time and the fade values are set just one time.

    #include <LEDFader.h>
    LEDFader led = LEDFader(10);

    int sensorValue = 0;
    int sensorValueLast = 0;

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

    void loop()
    {
      sensorValue = analogRead(A0);
      Serial.println(sensorValue);

            if (sensorValueLast!=sensorValue)
            {
              sensorValueLast = sensorValue;
              if(sensorvalue<=380)
              {
                 led.set_value(0);
                 led.fade(255, 3000);
              }
              if(sensorvalue>=555)
              {
                led.set_value(255);
                led.fade(0,3000);
              }

              led.update();
            }
    }

This example does everything just one time, when the cpu starts

    #include <LEDFader.h>
    LEDFader led = LEDFader(10);

    int sensorValue = 0;

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

       sensorValue = analogRead(A0);
       Serial.println(sensorValue);

              if(sensorvalue<=380)
              {
                 led.set_value(0);
                 led.fade(255, 3000);
              }
              if(sensorvalue>=555)
              {
                led.set_value(255);
                led.fade(0,3000);
              }

              led.update();

    }

    void loop()
    {
       //we will always see the same value
       Serial.println(sensorValue);
    }