body:
I'm using an Arduino to control an experimental setup and read analogue signals from some sensors. But there are [other sensors][1] for which I need a DAQ for. I have a National Instrument USB-6259. On my PC I use LabView or NI SignalExpress to read data from DAQ connected via USB. Considering that I want the read data from different sensors to be synced, I was wondering if I could somehow read the DAQ directly on the Arduino?

Some other points:

 1. I also have Arduino Ethernet Shield, if required.
 2. The final goal is to have logged data synced so out of the box solutions are also acceptable for me.
 3. If I'm not mistaken there are some versions of Arduino which you can install Linux on, just like a Rasppbery pi. There are even OSes for normal Arduino boards. There is a [Low Cost USB DAQ Driver for use with Raspberry Pi for NI USB-6008/6009 devices][2]. Is it possible to install this driver on Arduino?
 4. I prefer not use a Raspberry pi because analogue/PWM read and write there is not as straight forward. So if there are other boards which are as easy as an Arduino with an OS compatible with current driver please suggest.

  [1]: http://www.ati-ia.com/products/ft/ft_models.aspx?id=Mini45
  [2]: https://forums.ni.com/t5/NI-Labs-Toolkits/Low-Cost-USB-DAQ-Driver-for-use-with-Raspberry-Pi/ta-p/3533944

title: How to read data from an NI DAQ?

Answers: 2

body:
Unlikely.

First you would need a USB shield to be able to plug it in.

Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.

body:
The main answer for your question is already given by Majenko, and is "no". These protocols are much more complicated than you can think, so no way.

However, if I correctly interpret your point 2 (which is The final goal is to have logged data synced so out of the box solutions are also acceptable for me), you don't need to do this. Just use your PC (or raspberry) to collect all the data and make a synchronization inside it. For instance, connect the arduino to the PC via bluetooth, add a serial connection in the labview program and then send all the data the arduino records to the serial peripheral; you will get all the infos in the labview program.

If for any reason this is not possible, you can use a common signal to sync the acquisitions. For instance, when you start the measurements you let the DAQ generate a long pulse (let's say 100ms), then every second or minute it will generate a shorter pulse (let's say 10ms); the arduino also records this signal, so you will have a way to sync acquisitions. Or you can do the opposite: the arduino generates and the DAQ records.

To sum up, the arduino is not capable of doing what you request, but maybe what you need is not what you asked for...


body:
I am new to the world of Arduino and picked up an Uno R3. I have run into a situation where I have two components that specifically need digital pin 11, 12, 13 as specified by the libraries used to interact with them.

Each component also uses other pins that were able to be specified as different with the libraries but for those 3 the libraries say I cannot change them. What do you do in a situation like this? Is it somehow possible for two components to use the same pins? Any help is appreciated.

The two libraries I am trying to use are https://github.com/nRF24/RF24 (Wifi Receiver & Transmitter using component nrf24l01+) and https://github.com/steigeia/RFID_UNID_LOGGER/blob/master/libraries/AddicoreRFID/AddicoreRFID.h (RFID Reader/Writer using component RC522).

title: Sharing a Digital Pin / What to do when two components need a specific Digital Pin?

Answers: 1

body:
It seems probable that both libraries use SPI which connects to the SPI hardware on the chip via those pins. See https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino/

You haven't said what libraries, nor what hardware, but you possibly may be able to share those pins between the two devices. They would both need *separate* slave select pins. Often D10 (digital pin 10) is used as a default for slave select.

Another possible solution is to use "bit-banged" SPI for one device. I have a [page on my forum](http://www.gammon.com.au/spi) about SPI which includes a bit-banged software implementation.

The library is at <https://github.com/nickgammon/bitBangedSPI> and is quite short.


body:
I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). For example, if the input is 4 V then the stepper motor should move forward 4 steps. If the input is 3 V then it should come backward 1 step. Please suggest a command in Arduino to keep record of the previous sensor value and steps taken by stepper motor.

This is the code I have written for simple rotation of the motor:

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

    const int stepPin = 8;
    const int dirPin = 9;
    int sensorValue=A0;
    int i;

    void setup() {
      Serial.begin(9600);
      pinMode(sensorValue, INPUT);
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
    }

    void loop() {
      sensorValue = analogRead(A0);
      float voltage = sensorValue * (5.0 / 1023.0);
      if(voltage==1) {
        digitalWrite(dirPin, HIGH);
        for(int x = 0; x < 200; x++) {
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(5000);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(5000);
        }
        delay(1000); // One second delay
      }
      digitalWrite(dirPin, LOW);
      for(int x = 0; x < 200; x++) {
        digitalWrite(stepPin, HIGH);
        delayMicroseconds(500);
        digitalWrite(stepPin, LOW);
        delayMicroseconds(500);
      }
      delay(1000);
      while(1);//only once
    }

title: How to record steps a stepper motor takes and how to rotate it backward and forward with analog input?

Answers: 1

body:
I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.

I cannot test this code, because I don't have your hardware. Treat it as pseudo code.

    #include <Stepper.h>
    // change this to the number of steps on your motor
    #define STEPS 200
    #define NOISE 0.1

    Stepper stepper(STEPS, 8, 9);
    int previous = 0;
    void setup() {
      // set the speed of the motor to 30 RPMs
      stepper.setSpeed(100);
    }

    void loop() {
      // get the sensor value
      float val = analogRead(A0);

      float difference = previous - val;

      if(difference < -NOISE || difference > NOISE)
      {
        stepper.step(val - previous);
        previous = val;
      }
    }


body:
I've created a custom board in `boards.txt` and changed the `upload.tool` to a nonsense value, and yet when I do an upload the IDE still calls `avrdude`.

For example, In boards.txt I've changed the line...

    tile.upload.tool=avrdude

...to...

    tile.upload.tool=nogood

...and added these lines to platform.txt...

    # NOGOOD programmer

    tools.nogood.cmd="dir"
    tools.nogood.program.pattern="dir"
    tools.nogood.upload.pattern="dir"

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.

(Note that my board ID is `tile`)

I've verified that I am editing the correct boards.txt by changing the `cores` key to `nogood` and this does generate an error.

Is `boardid.upload.tool` not the right place to change the recipe called when upload is hit?

How/where does the `boardid.upload.tool=toolname` key in boards.txt get mapped to the `tools.toolname.upload.pattern` key in platforms.txt?

I am using Arduino IDE version 1.8.3.

The custom boards.txt is in the directory `Arduino\hardware\Move38\avr`.

This full custom platform package is here...

https://github.com/bigjosh/Move38-Arduino-Platform

Thanks!

title: upload.tool not used in custom boards.txt?

Answers: 3

body:
Custom tools for the Arduino build process are documented in the Boards Manager Package Index spec here...

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#tools-definitions

So it would seem that it i not possible to use custom tools with a manually installed board since there is no package index file.

body:
From https://github.com/bigjosh/Move38-Arduino-Platform#programmers:
>Since there is no bootloader in a tile, all code must be programmed rather than downloaded.

When you do an "Upload Using Programmer", the tool is specified in the `{programmerID}.program.tool` property in programmers.txt. The `{boardID}.upload.tool` value is only used for a standard upload.

Since programmers.txt is not in your hardware package, this makes it very inconvenient to customize. What's worse is that the platform.txt associated with the selected programmer is used, rather than the one in your hardware package, for "Upload Using Programmer". For this reason, [some popular hardware packages include their own copies](https://github.com/MCUdude/MightyCore/commit/777c5d6a373180c36d08c885c66690ccf2bd5a09#diff-d277425b7f2c4e00ec2a6a653169aa21) of all standard programmers. The downside of this is it really clutters up the **Tools > Programmer** menu if you have multiple of these packages installed.

body:
If you leave the `protocol` unset in the `boards.txt`, then the current version of the Ardunio IDE (1.8.12) will then use the `program` recipe rather than the `upload` recipe in `platform.txt`. The `program` recipe can use the `{protocol}` key to get the programmer selected in the IDE menus.

Relevant source in Arduino IDE `SerialUploader.java`...

    if (usingProgrammer || prefs.get("upload.protocol") == null) {
      return uploadUsingProgrammer(buildPath, className);
    }


body:
I meet a terrible problem. I can't compare two string!

My job is simple, every 1ms use `SoftwareSerial read_card(2, 3);`to check if i read a id card.And don't read a card twice.Here are my code:

    bool CardReader::check()
    {
     String str= read_card.readString();
     if (str.length() == 0 ) return false;
     //Log("card:%s", str);
     Serial.println("card_id");
     Serial.println(str);
     Serial.println(card);
     Serial.print("cmp:"); Serial.println(str == card);
     if (str.length() == card.length())
     {
      uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();
      for (int i = 0; i < card.length(); i++)
       if (p1[i] != p2[i])
        break;
      return false;
     }
     card = str;
     return true;
    }

Let's see output:

    card_id
     Rq
     僐R
    cmp:1

The hex are:

    00 01 52 71 02
    00 83 52 52 00

Why the two string is equal?

Bugs are fixed.If string begin with '\0',`==` can't work and `=` can't work either.

    bool CardReader::check()
    {
     String str = read_card.readString();
     if (str.length() == 0) return false;
     if (str.length() == card.length())
     {
      uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
      for (int i=0; i < card.length(); i++)
      {
       Log("%d:%d", p1[i],p2[i]);
       if (p1[i] != p2[i])
        goto find_card;
      }
      return false;
     }
    find_card:
     for(int i=0;i<5;i++)
      card[i]=str[i];
     return true;
    }

title: How to compare two string?

Answers: 3

body:
Because both strings are empty. In fact, calling the method c_str() will give a an array, which has at its first position ([0]) the null terminator (0x00 or '\0'). What follows the 0x00, is just rubbish.

In fact, check the card length, it will be 0.

(btw, there are some bugs in the code too. It always return false if the string have the same length, and it will always return true otherwise. EDIT: following the Nick Gammon's answer I also noticed that you get the pointer of the same string :). I corrected also this).

I think the code should be rewritten to:

    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
        for (int i = 0; i < card.length(); i++)
            if (p1[i] != p2[i])
                return false;
    }
    else
        return false;
    return true;

EDIT:

I add there what I wrote in the comments, for future reference, and explained in details.
The problem lies on the String class, which on one hand, it allows adding '\0' characters, through the method concat(char*), but on the other, it uses the strcmp (and other C standard functions) to perform compare between strings. This leads to unpredictable results. Maybe this is a bug in the String class.

In particular, SoftwareSerial extends Stream. Stream::readString() (which is used in the program to get str), is implemented as follows:

    String Stream::readString()
    {
      String ret;
      int c = timedRead();
      while (c >= 0)
      {
        ret += (char)c;
        c = timedRead();
      }
      return ret;
    }

The line `ret += (char)c;` uses operator +=, which is implemented in WString.h as:

    String & operator += (char c)   {concat(c); return (*this);}

**Note that readString() also allows adding any non negative value of c, including 0, i.e. '\0' - see while (c >= 0) in its code above**

In turn, concat(char c) is implemented in WString.cpp as:

    unsigned char String::concat(char c)
    {
     char buf[2];
     buf[0] = c;
     buf[1] = 0;
     return concat(buf, 1);
    }

And concat(const char *cstr, unsigned int length) is implemented as:

    unsigned char String::concat(const char *cstr, unsigned int length)
    {
     unsigned int newlen = len + length;
     if (!cstr) return 0;
     if (length == 0) return 1;
     if (!reserve(newlen)) return 0;
     strcpy(buffer + len, cstr);
     len = newlen;
     return 1;
    }

In the above method, length (instead of strlen) is used to determine the length of the string to add, and the new length is calculated using it:

    newlen = len + length;

**That's the bug**: you can add a '\0' char to the string, and this will also result in an increased length of the string. They should have checked if length <= strlen(cstr), before performing this concat operation.

Now, if you call the method String::equals or use the operator == (it is the same, as it is defined in WString.h as  `unsigned char operator == (const String &rhs) const {return equals(rhs);}`), you call this code:

    unsigned char String::equals(const String &s2) const
    {
     return (len == s2.len && compareTo(s2) == 0);
    }

Which, in turn, calls:

    int String::compareTo(const String &s) const
    {
     if (!buffer || !s.buffer) {
      if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
      if (buffer && len > 0) return *(unsigned char *)buffer;
      return 0;
     }
     return strcmp(buffer, s.buffer);
    }

And strcmp ends its compare operation if it first encounters a null operator (or when a compare mismatch occurs).

Therefore in your case, readString() added a null character to the "ret" String at first, and then some other characters. This created a String which begins with '\0'. Such string is equal to any other string beginning with a '\0', regardless what follows '\0'. But if you call length(), you'll get "len" (which String::concat() does not correctly calculate, and it will be non 0), as you can find in WString.h:

    inline unsigned int length(void) const {return len;}

Disclaimer: future versions of WString.h and WString.cpp could have fixed this bug.

body:
> Why the two string is equal?

            uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();

Both p1 and p2 point to the same string so of course they will always compare equal.

---

Do you mean:

    if (str == card)
       // do something

body:
Try strcmp()

See if  it works.


body:
Good day, I have this problem with my simple project. I have a database with all RFID number of employee. What I want to do is to use an rfID to check if it is registered in the database. If it is, it would return a value of 1 else would be a value of 0.

I tried with arduino HanRun Ethernet shield. I was able to get a response from the php web server to the serial monitor. Tried the seeedrfid it successfully get the rfcard number. However, when i tried to combine the two, it would hang on Ethernet.begin(mac, ip) initialization. My code is below.

    #include <Ethernet.h>
    #include <SoftwareSerial.h>
    #include <SeeedRFID.h>

    #define RFID_RX_PIN 10
    #define RFID_TX_PIN 11

    SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);

    char state = '0';
    char c;
    byte mac[] = {0x60, 0xF8, 0x1D, 0xBA, 0x1D, 0x52};
    IPAddress ip(192, 168, 20, 228);

    EthernetClient client;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      Serial.println("Serial set up");

      Ethernet.begin(mac, ip);
      Serial.print("My IP Address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {

      long rfID;
      // put your main code here, to run repeatedly:

      if (RFID.isAvailable()) {
        rfID = RFID.cardNumber();
        Serial.println(rfID);
      }
    }

Serial.println(rfID) is not executed unless I remove the Ethernet.begin(mac, ip). Can anybody point me to the right direction?

title: RFID does not respond after Ethernet.begin(mac, ip) initialization

Answers: 1

body: The Arduino Ethernet shield uses pins 4, 10,11,12,13. You have a conflict with the RFID pins.


body:
is it my coding wrong or my board have problem because my lcd does not display anything.
here my coding

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    // set the LCD address to 0x27 for a 20 chars 4 line display
    // Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x27, 6, 2, 3, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C add 27 / 3F

    void setup()   /*----( SETUP: RUNS ONCE )----*/
    {
      Serial.begin(9600); //
      lcd.begin(16,2);         // initialize the lcd for 16 chars 2 lines, turn on backlight
      lcd.backlight();

    }

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
    {

      lcd.setCursor(0, 0);
      lcd.print("HELLO");

      delay(200);

      lcd.setCursor(0, 1);
      lcd.print ("HI");

      delay(2000);

      lcd.clear();

      delay(2000);

      lcd.setCursor(0, 0);
      lcd.print("NICE");

      delay(200);

      lcd.setCursor(0, 1);
      lcd.print ("GOOD ");

      delay(2000);

      lcd.clear();

      delay(2000);
    }

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

this is how i wirring it. what should i do?

  [2]: https://i.stack.imgur.com/xwUC4.jpg

title: lcd not display

Answers: 3

body:
The first thing you have to do is run the examples from the library. If that doesn't works, check your connections and components.

If example works, it have to be your sketch (programing problem).

Good practice: write short sketchs that test only one component in your project. Example: your project use a LCD, a temp sensor, and a button, you wrote three short tests. If something goes wrong with your project, you can use the test sketchs to identify where the problem is

body:
the black bars indicate that the lcd isn't correctly initialized.

check the hardware / connection and make sure that your software initializes it correctly.

body:
Well, I have the hardware, so I tested OP's configuration. It didn't work for me either. Same OP's problem.

The cause is the I2C address we are using (0x27). That's not my LCD address, probably neither your address. It's 0x3F in my case.

I discovered it I2CScanner, a short sketch that lists all I2C devices connected at that moment. So, run it (with the LCD connected) and watch with Serial Monitor for the address of your LCD.

Then replace all references to 0x27 (like `lcd(0x27, 16, 2)`) with your real address. Just change one value for the other.

[![Hello World][1]][1]

This is I2CScanner

    //
    // Version 1
    //    This program (or code that looks like it)
    //    can be found in many places.
    //    For example on the Arduino.cc forum.
    //    The original author is not know.
    // Version 2, Juni 2012, Using Arduino 1.0.1
    //     Adapted to be as simple as possible by Arduino.cc user Krodal
    // Version 3, Feb 26  2013
    //    V3 by louarnold
    // Version 4, March 3, 2013, Using Arduino 1.0.3
    //    by Arduino.cc user Krodal.
    //    Changes by louarnold removed.
    //    Scanning addresses changed from 0...127 to 1...119,
    //    according to the i2c scanner by Nick Gammon
    //    http://www.gammon.com.au/forum/?id=10896
    // Version 5, March 28, 2013
    //    As version 4, but address scans now to 127.
    //    A sensor seems to use address 120.
    // Version 6, November 27, 2015.
    //    Added waiting for the Leonardo serial communication.
    //
    //
    // This sketch tests the standard 7-bit addresses
    // Devices with higher bit address might not be seen properly.
    //

    #include <Wire.h>

    void setup()
    {
      Wire.begin();

      Serial.begin(9600);
      while (!Serial);             // Leonardo: wait for serial monitor
      Serial.println("\nI2C Scanner");
    }

    void loop()
    {
      byte error, address;
      int nDevices;

      Serial.println("Scanning...");

      nDevices = 0;
      for(address = 1; address < 127; address++ )
      {
        // The i2c_scanner uses the return value of
        // the Write.endTransmisstion to see if
        // a device did acknowledge to the address.
        Wire.beginTransmission(address);
        error = Wire.endTransmission();

        if (error == 0)
        {
          Serial.print("I2C device found at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.print(address,HEX);
          Serial.println("  !");

          nDevices++;
        }
        else if (error==4)
        {
          Serial.print("Unknown error at address 0x");
          if (address<16)
            Serial.print("0");
          Serial.println(address,HEX);
        }
      }
      if (nDevices == 0)
        Serial.println("No I2C devices found\n");
      else
        Serial.println("done\n");

      delay(5000);           // wait 5 seconds for next scan
    }

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


body:
I'm working on uploading to [Digispark board][1]. It uses [micronucleus][2] bootloader and i can see [uploader code][3]. I've modified it a bit to see interfaces and endpoints count:

        nucleus->device = usb_open(dev);

        // added by me - start
        int interfaces, endpoints, j;
        struct usb_interface_descriptor *interface = NULL;

        interfaces = dev->config->bNumInterfaces;
        fprintf(stderr, "Found interfaces: %i\n", interfaces);

        interface = &(dev->config->interface[0].altsetting[0]);
        fprintf(stderr, "Endpoints: %i\n", interface->bNumEndpoints);
        // added by me - end

        // get nucleus info
        unsigned char buffer[4];
        int res = usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);

I wonder how it's working because interface #0 has no endpoints:

    $./micronucleus --type intel-hex /tmp/Start.ino.hex
    > Please plug in the device ...
    > Press CTRL+C to terminate the program.
    Found interfaces: 1
    Endpoints: 0
    > Device is found!
    connecting: 40% complete
    > Device has firmware version 1.6
    > Available space for user applications: 6012 bytes
    > Suggested sleep time between sending pages: 8ms
    > Whole page count: 94  page size: 64
    > Erase function sleep duration: 752ms
    parsing: 60% complete
    > Erasing the memory ...
    erasing: 80% complete
    > Starting to upload ...
    writing: 100% complete
    >> Micronucleus done. Thank you!

Usually i expect interface to have 2 endpoints (in & out from [usb.h][4]):

    #define USB_ENDPOINT_IN   0x80
    #define USB_ENDPOINT_OUT  0x00

Can anyone explain me how `usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);` is working without endpoint?

  [1]: http://digistump.com/products/1
  [2]: https://github.com/micronucleus/micronucleus
  [3]: https://github.com/micronucleus/micronucleus/blob/master/commandline/library/micronucleus_lib.c
  [4]: https://github.com/libusb/libusb-compat-0.1/blob/master/libusb/usb.h

title: How is interaction with CDC device with no interface endpoints working?

Answers: 1

body:
Micronucleus uses control transfers to upload code (it's not a CDC device). You don't need an endpoint for control transfers - they use the implicit endpoint 0 that is always present whether you define one or not.

You only need to define endpoints for interfaces that want to communicate using bulk, interrupt or isochronous transfers.

    Bus 003 Device 073: ID 16d0:0753 MCS Digistump DigiSpark
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               1.10
      bDeviceClass          255 Vendor Specific Class
      bDeviceSubClass         0
      bDeviceProtocol         0
      bMaxPacketSize0         8
      idVendor           0x16d0 MCS
      idProduct          0x0753 Digistump DigiSpark
      bcdDevice            1.02
      iManufacturer           0
      iProduct                0
      iSerial                 0
      bNumConfigurations      1
      Configuration Descriptor:
        bLength                 9
        bDescriptorType         2
        wTotalLength           18
        bNumInterfaces          1
        bConfigurationValue     1
        iConfiguration          0
        bmAttributes         0x80
          (Bus Powered)
        MaxPower              100mA
        Interface Descriptor:
          bLength                 9
          bDescriptorType         4
          bInterfaceNumber        0
          bAlternateSetting       0
          bNumEndpoints           0
          bInterfaceClass         0 (Defined at Interface level)
          bInterfaceSubClass      0
          bInterfaceProtocol      0
          iInterface              0
    Device Status:     0x18c0
      (Bus Powered)
      Debug Mode

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

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


body:
I'm trying to perform a simple analogRead() and print out the result, as below:
<!-- language-all: lang-cpp -->

    void getVoltMeter() {

      readValue = analogRead(A2);
      readByte = readValue/4;
      Serial.println(readValue);
      Serial.println(readByte);

    }

But the output is:

    023
    255

The voltage input is 5V, so I would expect it to read:

    1023
    255

Why is the first digit being cut off?

title: Serial.println cuts off first digit

Answers: 0


body:
I am looking for an efficient (and safe) way to use the Arduino to switch a higher voltage device off and on. The first option would be a relay, but they are fairly bulky. I was wondering if I should use an Optoisolator instead ?

Here is a link to the Data sheet for the Optoisolator I am using..

http://www.everlight.com/file/productfile/el817.pdf
I think (if I am reading it correctly) it expects an input voltage of 1V at about 20mA ?

However, I think it may be more involved than I originally thought. Here is a sort of simulation of what I am trying to achieve.
http://tinyurl.com/y9xd7lzb

As you can maybe tell, I am using a voltage divider to reduce the output from the arduino (from 5V to 1V).
My concerns are ..

1. Is this the best approach ?
2. Is it efficient ?
3. are there any problems I should be aware of ? Precautions I need to take ?
4. Is the voltage divider a good approach to feed the input to the Optoisolator ?

Also, efficiency is an issue as the Arduino (probably a Nano) will be running off batteries.

The target device is a 20V DC motor. I am a novice when it comes to electronics, so I would be grateful of any help or advice you can give.

Many thanks..

Dave.

title: Arduino and Optoisolators

Answers: 2

body:
> Is this the best approach ?

Not really, no.

> Is it efficient ?

No, far from it.

> are there any problems I should be aware of ? Precautions I need to take ?

You don't want a voltage divider to power an opto-isolator. An opto-isolator won't be powerful enough to cope with the motor current. You need flyback protection.

> Is the voltage divider a good approach to feed the input to the Optoisolator ?

No, definitely not.

Unless you require galvanic isolation all you need is a simple NPN transistor or N-channel MOSFET circuit:

<!-- 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/bYmsg.png)

<!-- End schematic -->

body:
your optocoupler's 2ndary side isn't powerful enough to switch a load.

use the 2ndary side to switch a switcher, instead.


body:
I found hundreds of questions about display not working with arduino.
However, no matter how trivial this looks like I am having the same problem I cannot understand by reading the other posts.

I have an Arduino micro connected to a display from the adafruit kit

RGB LCD SHIELD KIT W/ 16X2 CHARACTER DISPLAY

I haven't been able to understand whether positive or negative, but I think from the picture is RGB positive.

I have connected everything as shown in the diagram in this page:

[LCD "Hello World!"][1]

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

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

Obviously changing the pins as I have

    RS at 8
    E at 7
    d4 = 12
    d5 = 11
    d6 = 10
    d7 = 9;

The potentiometer changes the contrast, if I saturate it I can see the black boxes.

In the code put this as

    const int rs = 8, en = 7, d4 = 12, d5 = 11, d6 = 10, d7 = 9;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

I checked with the multimeter whether the soldering is good and it carries the signal at the end of the wires.

and the rest as the example in the link,

This is my mess (please ignore the other arduino and the thermocople which is not connected, the other orange wire goes to GND of the Arduino).

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

Any ideas that might help?

  [1]: https://www.arduino.cc/en/Tutorial/HelloWorld
  [2]: https://i.stack.imgur.com/koS2x.png
  [3]: https://i.stack.imgur.com/7L1vz.png
  [4]: https://i.stack.imgur.com/rUJKd.jpg

title: Yet another display 16x2 not working with arduino

Answers: 1

body:
1. disconnect the E line, power up the system and adjust the contrast so you see 1 black bar on the first line;

2. reconnect the E line and see if your code is working.

3. go from there.


body:
I am building a circuit that has a button, which when pressed, should increment a counter. I want to store this counter so that when I power off my circuit, it can be read when I power it back on. However, I am worried about the lifetime of the EEPROM - apparently it is only rated to handle 100k writes.

I am using an Adafruit Trinket Pro. Should I cycle my writes through different addresses so as not to write to a single cell over and over? What other strategies are there? I don't expect to be pressing the button many times in a short period of time - maybe at most one press per minute.

Is there some other external storage option I should look at? I really don't want my little project to die randomly one day because I've exceeded ~100k button presses!

title: Storing a counter to EEPROM - how to extend the life?

Answers: 4

body:
If possible use a combination of wear-leveling like algorithm (as pointed out by Mikael Patel) and an power-down driven interrupt, to save onto EEPROM only when needed. At reset, load the last keypress count into a variable in RAM. Increment that variable in RAM on keypress, and save it to EEPROM only when a power down occurs (i.e. the interrupt is triggered). Optionally, when power down occurs, make sure to save the variable only if the new counter actually differs from the old value (i.e. if there actually were keypresses).

To implement the power-down driven interrupt use the built-in comparator to monitor a Vin (use a resistor divider!) against the internal Vref, and use the analog comparator interrupt to save the value. Remember to put enough capacitance between +5V and gnd, to make sure your arduino has enough time to save the state.

Alternatively, if you can afford errors (which might accumulate over time, and lead to a huge underestimation), save the value to EEPROM only every n keypresses.

body:
Cycling through the EEPROM is possible.

Is that button capable to last more than 100k presses ?

A button press every minute ? Really ? Is that during working hours ? That would take about year to get near the 100k writes (5 days per week, 8 hours per day, every minute).

If you want to count more than 100k key presses, then you probably store it in a 32-bit integer. That is 4 bytes. That means that when the Arduino is turned off while in the middle of writing that number to the EEPROM, that number is corrupted and lost forever.

With 1k EEPROM, you have 256 positions for the 32-bit integer. That means you can handle 25 million key presses.

My suggestion would be to store each new value of the 32-bit integer to the next location (circular). At startup you need code that interprets the numbers to find the last one and ignores a bad one and can handle a new Arduino with cleared EEPROM and even an Arduino that was used by you to develop the code. That means you need a command to clear the EEPROM.

body:
`maybe at most one press per minute.`

That's great! You can just make some sort of timer to save every 2 or 3 minutes automatically. You said `at most`, so that should work. Here is example of code that can allow you to do so!

    int cycleCnt = 0;    //Counter to count cycles
    int cnt = EEPROM.read(0);         //Your press counter
    bool currentlyCounting = false;   //Boolean to store if we are counting now or not
    bool pressedBefore = false;

    void loop() {
      if (digitalRead(button_pin) == HIGH) {    //You are holding the button
        if (!pressedBefore) {                   //And you didn't press it before
          //Here you do something you need with button
          currentlyCounting = true;       //After you pressed the button, we are starting to count time
          cycleCnt = 0;                        //and reset current counter (which would save us EEPROM writes!)
          cnt++;

          pressedBefore = true;                 //Mark button to be pressed so you don't do same code more then one time
        }
      }
      else pressedBefore = false;               //Mark, that you've unpressed the button

      delay(50);      //Delay in 50 mil won't affect speed of your button press, but it will allow us to count time
      if (currentlyCounting) cycleCnt++;          //Count cycles (every 50 mil)

      if (cycleCnt == 20 * 120) { //20 - amount of loop cycles to wait for one second. 120 - seconds in 2 minutes
        cycleCnt = 0;
        EEPROM.write(0, cnt);
        currentlyCounting = false;
      }
    }

This might help you as well!

In case I misunderstood you and you meant "1 minute is the highest delay time beetween presses" then you should save automatically every half of minute or so

body: Use brown out detection. Keep the count in ram until the mcu is losing power - only then save it to eeprom. Read the datasheet on bor.


body:
    //In order to connect,

    SoftwareSerial esp8266(2,3);

    // the TX pin of esp8266 is connected to pin 3 of
    // arduino uno and RX pin is connected to 2
    // we need to pass baud rate to begin function

    void setup()
    {
      Serial.begin(115200);
      esp8266.begin(???); // what should i do in order to make it work?
    }

What should i do in order to make it work?

title: How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)?

Answers: 1

body:
I encountered a similar situation where I accidentally set the baudrate to 8000 with the AT commands.

Thankfully I remembered the baud rate I set, so I used PuttY to create a serial communication with the port with the weird 8000 baud rate and changed the baud rate back to 9600.

The method can be found here: http://flower-platform.com/2015/12/16/esp8266-with-at-commands-connect-from-pc-with-putty/

The AT command I used to change the baud rate:
`AT+UART_DEF=9600,8,1,0,0`


body:
Hi I am using `Arduino Nano` to gamify my experience on Unity3D. I know that `Update()` in Unity3D runs every frame per second but I because I'm not an electronics guy I don't know how `loop()` function runs on Arduino.

Does it depends on number of CPU cycles(or micro processor chip in case of Arduino) or what? Please explain. I facing some lags in my game. I can fix them only if know how is loop() function running on Arduino

There ain't a lot of information about `loop()` in arduino [documentation][1]

  [1]: https://www.arduino.cc/en/Reference/Loop

title: how fast does loop() run in Arduino

Answers: 6

body: It depends on what's in the loop. From a few clock cycles to infinite hang.

body:
Loop runs as long as loop needs to run.

Instructions in a CPU run sequentially. The more instructions there are the longer it takes to run.

The more code you put in loop the longer loop will run.

There are two ways to know how long each iteration of loop will take:

1. Profiling: Actively time each iteration of loop, though be warned, the act of timing will affect the amount of time taken.
2. Cycle counting. Compile the source into assembly and total up the number of clock cycles needed for all the instructions (including calls to functions). Arduous for small loops, a gargantuan task for anything else.

Also note that many external factors can affect how long loop() takes to run - such as serial communication speed, etc.

body:
the instructions between the end of loop() and the next run of it are a ret, jmp and a call.

You can consider the main function to be effectively:

    void main(){

        init();
        while(1) loop();

    }

Though in reality there is some setup done before `init()` to make `millis()` and such work.

body:
try looking up arduino functions
micros()
and
delayMicroseconds()
If you might need your loop to wait longer than 16000 microseconds then also look up the other delay() function which does milliseconds.

By the way, the internal clock is very slightly off and varies with room temperature, so don't rely on it staying synchronised to your other device without a handshake.

body:
A look at main.cpp (for avr code in my installation) in file:

    C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\main.cpp

shows that the Arduino runs loop() alternately with serialEventRun() in an infinite loop:

    int main(void)
    {
     init();
        initVariant();
     #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

     for (;;) {
      loop();
      if (serialEventRun) serialEventRun();
     }

     return 0;
    }

Inspection of HardwareSerial.cpp shows that serialEventRun() simply calls serialEvent<n>(), if you have defined it in your sketch.

This means that you can write your own infinite loop within loop() perfectly safely, unless you have written serialEvent() code and are expecting it to run regularly.

This begs the question: if serialEvent() is called sequentially with loop(), will serialEvent() be called if loop() never returns? In other words, is serialEvent() interrupt-driven as well as being called when loop() returns?  A quick test -see below- shows that it is **not** interrupt-driven, so the previous paragraph is true.

    /*
      Serial Event Checker

      A sketch to see if serialEvent() is interrupt-driven.
      Will serialEvent() be called if loop() never returns?

      This code is based on Tom Igoe's SerialEvent example.

      On (at least) Arduino Uno we find that serialEvent() simply runs
      sequentially with loop().  When loop() never returns serialEvent()
      is never called.

      NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or
      other ATmega32U4 based boards.

      R Symonds-Tayler 2018-02-01

      This example code is in the public domain.

    */

    String inputString = "";         // a String to hold incoming data

    void setup() {
      // initialize serial:
      Serial.begin(115200);
      // reserve 200 bytes for the inputString:
      inputString.reserve(200);
    }

    // comment out this definition to allow loop() to return
    #define INFINITE_LOOP

    void loop() {
    #ifdef INFINITE_LOOP
        while(1);
    #endif

    }

    /*
      SerialEvent occurs whenever a new data comes in the hardware serial RX. This
      routine is run between each time loop() runs, so using delay inside loop can
      delay response. Multiple bytes of data may be available.
    */
    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.print("Got: '");
          Serial.print(inputString);
          Serial.println("'");
          // clear the string:
          inputString = "";
        }
      }
    }

This means that serialEvent() code might just as well go into your main loop() within a:

    if(serial.available()){
       // your code here...
    }

block.

body:
In [this article][1] [bri_huang][2] made a nice experiment using an oscilloscope and simple write functions.

He calculated the speed of the loop to be 117 kHz even though the microcontroller has a 16 MHz clock.

[https://learn.sparkfun.com/blog/1687][1]

  [1]: https://learn.sparkfun.com/blog/1687
  [2]: https://www.sparkfun.com/users/189969?_ga=2.124669005.630681230.1620644852-511729427.1602060651


body:
I have an Arduino Mega 2560 to which I have connected:

 - Arduino GSM Shield 2
 - Waveshare 10 DOF IMU sensor
 - Waveshare NEO-7M-C (B) GPS module
 - HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.

My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

title: Arduino Mega and other modules power consumption

Answers: 5

body:
**You should not try to power your arduino with more than 12 V**.  The barrel jack connector can take between 7 and 12 V and from there steps it down to the proper voltage for the Arduino (5V).  Anything being powered by the arduino is limited to how much current it can output, so if you have too many modules, you may need to have a separate power supply for those.  If you do this, there several things you need to consider:

 1. **What voltage does each module need?** (This is probably 5V, but you should check the datasheets or any documentation you have)
 2. **How much power does it consume?** You might find this in documentation, but you can also calculate it yourself: P = I*V  Once you know how much power each module/sensor consumes, you know how much your power supply needs to supply.

If you use a separate power supply for any of your modules/sensors,  make sure the ground pin is also tied to Arduino's ground.

body:
Power applied to the VIN pin is regulated down to 5V by the on-board regulator on the Mega. The minimum voltage is about 6.2V because of the regulator dropout (that is, the regulator needs at least 1.2V above it's 5V output in order to operate.) 9-12V is recommended.

Applying a higher and higher voltage will not provide any more power to the Mega and it's peripherals/shields. Instead, the excess power is dissipated in the regulator as heat.

If you experience low-power situations, the solution is to power the peripheral devices from a separate regulator than the one built-in to the Mega, which is really intended to power the Mega board/processor and maybe 1 shield.

You could obtain a high-current (3A or more) 5V supply, and connect the peripherals' power inputs to it, as well as power the Arduino in via the 5V pin (leaving VIN disconnected!). Be sure to tie the grounds of all peripherals and the arduino and power supply together.

Be sure also to pay attention to the voltages required by the peripheral modules, as it's common now to find modules that are rated for 3.3V and would be damaged by 5V. This is probably not the case for you, since your system is working sometimes.

body:
The Arduino GSM shield 2 demands 700mA-1000mA current. It is recommended to power the board with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current when the modem is in heavy use.

The modem can pull up to 2A of current at peak usage, which can occur during data transmission.

The GPS module takes only 35mA, so the fault is in the GSM shield.

body:
You can't fix it with more voltage. The board you are using ([schematic here][1]) uses a linear voltage regulator. All increasing the voltage does is make the regulator run hotter.

You could try running from around 7V, this will minimize the heat dissipation in the regulator and may allow you to pull more current through it but I suspect you've simply hit the design limits of the power supply circuits.

Instead of using the Arduino's built in power supply to convert from 12V to 5V you could try using an external 5V supply with a greater current capability connected directly to the Arduino 5V rail.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf

body:
arduino nano(5v usb)(3.3v).
arduino uno(12v dc jack)(5v).


body:
I am using nRF24L01 to communicate between two micro controllers. Both are Arduino Uno.

The question i have here is , even if i do not send any data from sender to receiver , the receiver device is constantly checking for the data, and the blank data is being received per second. And also no data is received by receiver which is sent by sender.

I am sharing the code for both sender and receiver.

Please suggest me what wrong i am doing.

Receiver Code :

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String response;
    boolean done = false;

    void setup() {

     delay(500);
     Serial.begin(9600);

     radio.begin();
     radio.setPALevel(RF24_PA_MIN);
     radio.openReadingPipe(0, 0xF0F0F0F0AA);
     radio.startListening();

    }

    void loop() {

       if (radio.available()) {

       radio.read(&response, sizeof(response));
       done = true;

    }

    if (done) {
      Serial.println(response);
    }

    done = false;
    delay(1000);

    }
Sender Code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String request;

    void setup() {

    delay(500);
    Serial.begin(9600);

    radio.begin();
    radio.openWritingPipe(0xF0F0F0F0AA);
    radio.setPALevel(RF24_PA_MIN);
    radio.stopListening();

    }

    void loop() {

       while ( Serial.available() > 0 )  {

       request = Serial.readString();

       Serial.println(request);
       radio.write(&request, sizeof(request));

       delay(1000);

     }
    }

title: NRF24L01 receiving even if no data sent

Answers: 2

body:
You may have reversed the wire:

    RF24 radio(7, 8); //  CE,CNS

body:
I've written a code for NRF24L01+ based on the datasheet.run them on your arduino and test them.CE pin is PIN7 in arduino and CSN is PIN8 in arduino.
NRF_monitorRegisters() shows all Registers of NRF.It's nice to test your NRF
maybe it helps:

for transmitter:

    #include <SPI.h>

    int sending = 1;
    int data = 7;

    void IRQ() {
      Serial.println("STATUS register from IRQ ISR :  ");
      digitalWrite(8, 0);
      SPI.transfer(0x07);
      delay(10);
      Serial.println(SPI.transfer(0xff), BIN);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x08);
      delay(10);
      Serial.println(SPI.transfer(0xff), BIN);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);
    }

    void NRF_transmitterBegin() {

      //reading
      /*digitalWrite(8, 0);
        SPI.transfer(0x00);
        delay(10);
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);*/

      pinMode(7, OUTPUT);  //CE
      pinMode(8, OUTPUT);  //CSN
      delay(100);
      digitalWrite(8, 1);
      digitalWrite(7, 0);

      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV4);
      SPI.begin();
      delay(1000);

      digitalWrite(8, 0);   //flush TX_FIFO
      SPI.transfer(0xe1);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);   //flush RX_FIFO
      SPI.transfer(0xe2);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xf0);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x00 + 0x20);
      delay(10);
      SPI.transfer(0x0e);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      /*digitalWrite(8, 0);
        SPI.transfer(0x11 + 0x20);
        delay(10);
        SPI.transfer(0x3f);
        delay(10);
        digitalWrite(8, 1);*/

      //Down for DYNPL
      digitalWrite(8, 0);
      SPI.transfer(0x1c + 0x20);
      delay(10);
      SPI.transfer(0x01);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x1d + 0x20);
      delay(10);
      SPI.transfer(0x04);
      delay(10);
      digitalWrite(8, 1);
      //Up for DYNPL

      digitalWrite(8, 0);
      SPI.transfer(0x01 + 0x20);
      delay(10);
      SPI.transfer(0x3f);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x02 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x03 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x04 + 0x20);
      delay(10);
      SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x05 + 0x20);
      delay(10);
      SPI.transfer(0x4c);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x06 + 0x20);
      delay(10);
      SPI.transfer(0x06);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x0a + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x10 + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

      attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);
      delay(10);

    }

    void NRF_transmit(int whatIsData , float data , float hum) {    //hum is used just for temp&humidity
      /*
         byte 0 says what is our data:  1 -> data and humidity    2 -> movement   3 -> gas

         1(float) :   byte 1 -> integer part of temp  byte 2 -> fractional part of temp   byte 3 -> integer part of humidity    byte 4 -> fractional part of humidity    byte 5 -> �ttery
         2(binary) :  byte 1 -> �ttery
         3(float) :   byte 1 -> integer part of gas   byte 2 -> fractional part of gas    byte 3 -> �ttery

         �ttery feature is in progress ...
      */

      int byte0 = 0 , byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
      float buf = 0;

      byte0 = whatIsData;

      switch (whatIsData) {
        case 1: {

            byte1 = data;
            buf = data - byte1;
            byte2 = buf * 10;

            byte3 = hum;
            buf = hum - byte3;
            byte4 = buf * 10;

            break;
          }
        case 2: {

            break;
          }
        case 3: {

            byte1 = data;
            buf = data - byte1;
            byte2 = buf * 10;

            break;
          }
        default: {
            break;
          }
      }

      digitalWrite(8, 0);
      SPI.transfer(0xe1);   //flush TX_FIFO empty
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0xa0);   //write on TX_FIFO
      delay(10);
      SPI.transfer(byte0);
      delay(10);
      SPI.transfer(byte1);
      delay(10);
      SPI.transfer(byte2);
      delay(10);
      SPI.transfer(byte3);
      delay(10);
      SPI.transfer(byte4);
      delay(10);
      SPI.transfer(byte5);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(7, 1);   //CE High
      delay(1);
      digitalWrite(7, 0);   //CE Low

    }

    void NRF_monitorRegisters() {

      for (int i = 0; i < 30; i++) {
        digitalWrite(8, 0);
        SPI.transfer(i);
        delay(10);
        Serial.print(i , HEX);
        Serial.print(" -> ");
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);
      }
      Serial.println("");

    }

    void setup() {

      Serial.begin(115200);

      NRF_transmitterBegin();
      NRF_monitorRegisters();

    }

    void loop() {

      NRF_transmit(3 , 15.1 , 0);

      delay(1000);
    }

for receiver :

    #include <SPI.h>

    long int lastTime = 0;

    void IRQ() {

      int whatIsData = 0;
      int byte1 = 0 , byte2 = 0 , byte3 = 0 , byte4 = 0 , byte5 = 0;
      float data = 0 , hum = 0 , buf = 0;

      /*Serial.println("STATUS register from IRQ ISR :  ");
        digitalWrite(8, 0);
        SPI.transfer(0x07);
        delay(10);
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);*/

      digitalWrite(8, 0);
      SPI.transfer(0x61);
      delay(10);
      whatIsData = SPI.transfer(0xff);
      delay(10);
      byte1 = SPI.transfer(0xff);
      delay(10);
      byte2 = SPI.transfer(0xff);
      delay(10);
      byte3 = SPI.transfer(0xff);
      delay(10);
      byte4 = SPI.transfer(0xff);
      delay(10);
      byte5 = SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);   //flush RX_FIFO
      SPI.transfer(0xe2);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xf0);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      switch (whatIsData) {
        case 1: {

            buf = byte2;
            data = byte1 + buf / 10;
            buf = byte4;
            hum = byte3 + buf / 10;

            Serial.print("Received data from DHT22 -> temp:");
            Serial.print(data);
            Serial.print("  humidity:");
            Serial.println(hum);

            break;
          }
        case 2: {

            Serial.println("Received data from PIR -> Move detected");

            break;
          }
        case 3: {

            buf = byte2;
            data = byte1 + buf / 10;

            Serial.print("Received data from gas sensor -> %gas:");
            Serial.println(data);

            break;
          }
        default: {

            Serial.println("a problem accured");

            break;
          }
      }

    }

    void NRF_receiverBegin() {

      //reading
      /*digitalWrite(8, 0);
        SPI.transfer(0x00);
        delay(10);
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);*/

      pinMode(7, OUTPUT);  //CE
      pinMode(8, OUTPUT);  //CSN
      delay(100);
      digitalWrite(8, 1);
      digitalWrite(7, 0);

      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV4);
      SPI.begin();
      delay(100);

      digitalWrite(8, 0);   //flush TX_FIFO
      SPI.transfer(0xe1);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);   //flush RX_FIFO
      SPI.transfer(0xe2);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x07 + 0x20);
      delay(10);
      SPI.transfer(0xf0);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      digitalWrite(8, 0);
      SPI.transfer(0x00 + 0x20);
      delay(10);
      SPI.transfer(0x0f);
      delay(10);
      digitalWrite(8, 1);
      delay(10);

      /*digitalWrite(8, 0);
        SPI.transfer(0x11 + 0x20);
        delay(10);
        SPI.transfer(0x01);
        delay(10);
        digitalWrite(8, 1);*/

      //Down for DYNPL
      digitalWrite(8, 0);
      SPI.transfer(0x1c + 0x20);
      delay(10);
      SPI.transfer(0x01);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x1d + 0x20);
      delay(10);
      SPI.transfer(0x04);
      delay(10);
      digitalWrite(8, 1);
      //Up for DYNPL

      digitalWrite(8, 0);
      SPI.transfer(0x01 + 0x20);
      delay(10);
      SPI.transfer(0x3f);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x02 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x03 + 0x20);
      delay(10);
      SPI.transfer(0x03);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x04 + 0x20);
      delay(10);
      SPI.transfer(0xff);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x05 + 0x20);
      delay(10);
      SPI.transfer(0x4c);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x06 + 0x20);
      delay(10);
      SPI.transfer(0x06);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x0a + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

      digitalWrite(8, 0);
      SPI.transfer(0x10 + 0x20);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      SPI.transfer(0xaa);
      delay(10);
      digitalWrite(8, 1);

    }

    void NRF_startListening() {

      attachInterrupt(digitalPinToInterrupt(2), IRQ, FALLING);

      digitalWrite(7, 1);   //CE High
      Serial.println("Listening started");

    }

    void NRF_monitorRegisters() {

      for (int i = 0; i < 30; i++) {
        digitalWrite(8, 0);
        SPI.transfer(i);
        delay(10);
        Serial.print(i , HEX);
        Serial.print(" -> ");
        Serial.println(SPI.transfer(0xff), BIN);
        delay(10);
        digitalWrite(8, 1);
      }
      Serial.println("");

    }

    void setup() {

      Serial.begin(115200);

      NRF_receiverBegin();
      NRF_startListening();
      NRF_monitorRegisters();

    }

    void loop() {

      /*if (millis() - lastTime > 20000) {
        NRF_monitorRegisters();
        lastTime = millis();
      }*/

    }


body:
I have an arduino UNO and when I connected the device through the USB to the PC (with windows 7 64 bit),

The default blinking sketch, which comes shipped with it, is working,

but the device recognition sound is not playing.

and the device driver installation dialog never appeared and no arduino entry in the device manager.

And when I tried to upload a successfully compiled sketch from the ide 1.8.4 ,

It just says, 'problem uploading to board'
More verbosely, **' avrdude: can't open device""\\.\COM1": the system cannot find the file specified'**

The device is getting power and running the sketch,
But device is not recognized, maybe it is connected charge only, can I install the drivers manually?

Thanks in advance for any help.

title: Default sketch working but arduino is not recognizing

Answers: 1

body:
Hahaha! I figured it out! The USB connector on the board's side was loose connected! It didn't felt like more pressable & when I pressed it enough, it firmly fitted.

When it loose connected, the board connects power only.

The drivers were installed automatically & it showed under COM6. I've got sketches running in no time.
I' ve tried a lot of knight rider patterns with a bunch of RGB LEDs then ;-)

Thank you @Majenko and the arduino stack exchage for your kind replies.


body:
I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:

    if ((analogRead(rain) < 650 || (Wind > 4)){
      motor_closed();
    }

    else if (analogRead(rain) < 650 && (Wind > 4)){
      motor_closed();
    }

    else if (analogRead(rain) < 650 && (Wind < 2)){
      motor_closed();
    }

    else if (analogRead(rain) > 900 && Wind > 4){
      motor_closed();
    }

    else if (analogRead(rain) > 900 && Wind < 2){
      motor_open();
    }

Did I make mistake when using `&&` boolean operator? Or its something else?

title: Issue with If statement and boolean logic

Answers: 3

body:
I ran a test with your original code, with rain and wind varying over all the range:

    (rain, wind) -> action
    ------------------------
    (600, 1) -> motor_closed
    (600, 2) -> motor_closed
    (600, 3) -> motor_closed
    (600, 4) -> motor_closed
    (600, 5) -> motor_closed
    (650, 1) ->
    (650, 2) ->
    (650, 3) ->
    (650, 4) ->
    (650, 5) -> motor_closed
    (700, 1) ->
    (700, 2) ->
    (700, 3) ->
    (700, 4) ->
    (700, 5) -> motor_closed
    (750, 1) ->
    (750, 2) ->
    (750, 3) ->
    (750, 4) ->
    (750, 5) -> motor_closed
    (800, 1) ->
    (800, 2) ->
    (800, 3) ->
    (800, 4) ->
    (800, 5) -> motor_closed
    (850, 1) ->
    (850, 2) ->
    (850, 3) ->
    (850, 4) ->
    (850, 5) -> motor_closed
    (900, 1) ->
    (900, 2) ->
    (900, 3) ->
    (900, 4) ->
    (900, 5) -> motor_closed
    (950, 1) -> motor_open
    (950, 2) ->
    (950, 3) ->
    (950, 4) ->
    (950, 5) -> motor_closed

So your logical expression reduces to this:

    if (analogRead(rain) < 650 || Wind > 4) {motor_close();}
    else if (analogRead(rain) > 900 and Wind == 1) {motor_open();}

It's that what you want?

What's that "limiting switch"? May be it's a physical problem (like installing sensor **under** de roof)

body:
Personally I like to force precedence in my `if` statements to ensure that things always work precisely as I intend.  Group your logical predicates with brackets:

    if ((analogRead(rain) < 650) || (Wind > 4)) {
        motor_close();
    } else if ((analogRead(rain) > 900) and (Wind < 2)) {
        motor_open();
    }

Using intermediate variables would make it more readable:

    bool tooWindy = (Wind > 4);
    bool notWindy = (Wind < 2);
    bool tooRainy = (analogRead(rain) < 650);
    bool notRainy = (analogRead(rain) > 900);

    if (tooWindy || tooRainy) {
        motor_close();
    } else if (notWindy && notRainy) {
        motor_open();
    }

Giving names to the logical conditions makes it far more obvious what is going on:

* If it is too window **or** it is too rainy then close the roof.
* Otherwise, if it's not too windy **and** it's not too rainy then you can open the roof.

And of course you have the time when it's between too rainy and not too rainy, or between too windy and not too windy, in which case nothing should happen. This is called *hysteresis* and is good to have since it stops the roof from opening and then immediately wanting to close.

You could also improve the logic of the system even more and implement a small Finite State Machine:

    enum {
        CLOSED, OPENING, OPEN, CLOSING
    };

    int state = CLOSED;

    switch (state) {
        case CLOSED:
            if ((analogRead(rain) > 900) && (Wind < 2)) {
                motor_open();
                state = OPENING;
            }
            break;

        case OPENING:
            if (digitalRead(limit_open) == HIGH) {
                motor_stop();
                state = OPEN;
            }
            break;

        case OPEN:
            if ((analogRead(rain) < 650) || (Wind > 4)) {
                motor_closed();
                state = CLOSING;
            }
            break;

        case CLOSING:
            if (digitalRead(limit_close) == HIGH) {
                motor_stop();
                state = CLOSED;
            }
            break;
    }

In that you only attempt to open the roof (and even check to see if you should open the roof) if the roof is actually closed. Similarly for checking for and closing the roof - it only happens when the roof is actually open.  Nothing happens in the way of checks while the roof is in the process of opening or closing, so it has to complete its open or close operation first before any more decisions are made as to whether the roof should be open or closed.

body:
> Did I make mistake when using && boolean operator? Or its something else?

use brackets liberally.

rather than

    if (x > 65 && y < 10)

instead,

    if ((x > 65) && (y < 10))


body:
I have an Arduino Mega 2560 to which I have connected:

 - Arduino GSM Shield 2
 - Waveshare 10 DOF IMU sensor
 - Waveshare NEO-7M-C (B) GPS module
 - HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.

My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.

title: Arduino Mega and other modules power consumption

Answers: 0


body:
I've used the example code for the Adafruit I2C FRAM breakout board, but I've made it even simpler by just writing the same thing to each byte location and then reading them all off, doing nothing with the data.

I can tell it works because I can read off any byte and get the expected value, but the problem is that it works way too slowly. writing and reading 512 bytes takes almost a full half a second. This just won't work for my application, but I suspect there's something fundamentally wrong with what I'm doing.

I tried calling `Wire.setClock(400000);`, which supposedly is the maximum speed my Nano can drive an I2c slave at, but no matter what argument I input, the operation takes the same amount of time (498616 microseconds, within about +/- 20 microseconds).

I also tried calling `Wire.begin(); TWBR = 10;`, because I read that somewhere. But again, I get no difference. Here's my whole code- It's pretty simple

    #include <Wire.h>
    #include "Adafruit_FRAM_I2C.h"

    /* Example code for the Adafruit I2C FRAM breakout */

    /* Connect SCL    to analog 5
    Connect SDA    to analog 4
    Connect VDD    to 5.0V DC
    Connect GROUND to common ground */

    Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C();
    uint16_t          framAddr = 0;

    byte p = 55;   //any old value- just write the same thing into all locations

    void setup(void) {
     Serial.begin(153600);
     //Wire.begin();
     //TWBR = 10;
     //Wire.setClock(400000);

     if (fram.begin()) {
      Serial.println("Found I2C FRAM");
     }
     else {
      Serial.println("I2C FRAM not identified ... check your connections?\r\n");
     }

    }

    void loop(void) {

     int i = 0;

     long a = micros();

     for (i ; i < 512; i++){  //write 512 bytes to the FRAM board
      fram.write8(i, p);

     }

     for (i = 0 ; i < 512; i++) {  //read 512 bytes from the FRAM board
      fram.read8(i);

     }

     long b = micros();

     Serial.println(b - a);
     Serial.println("");
    }

title: I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write

Answers: 1

body:
* You are running at 400000 bits per second, or 200000 per half second you say it takes.
* You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
* 200000/1000 = 200 bits per transaction.
* Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.

That makes 50 bits per transaction.

So yes, half a second to write then read it all is perfectly possible.

The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

----

Now I  am at my computer I can take a look at the datasheet and get some more accurate numbers.

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.

A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.

So for a read and write it's 38+48 = 86 bits.

Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.

At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.

If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

So not a bad guestimate of 25% transmission in my original surmising.


body:
As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me.
I have tried using PubSubClient library, but the problem is that to create an instance (`PubSubClient client(?????)`), I have to set a client. What should I put in there? Is there another library I must use?

title: Establishing an MQTT connection using Arduino Mega and ESP8266

Answers: 2

body:
You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).

Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.

body:
you have the AT firmware in the esp8266?
use [WiFiEsp library][1]

or if you can change the esp8266 firmware, you could try [JeeLabs esp-link][2]

  [1]: https://github.com/bportaluri/WiFiEsp
  [2]: https://github.com/jeelabs/esp-link


body: I am using wifi module esp8266 , what is easiest way to communicate arduino with desktop application and make a wireless communication between them. Please refer any useful resources

title: Connect arduino with C# Desktop application wireless using esp8266

Answers: 1

body:
Either use TCP or UDP to communicate. With TCP one end will be the server and will open a socket (your choice) and the other end will connect to it (much like communicating with a web server). With UDP both ends will open a socket and send discrete packets backwards and forwards.

How you would do either of those in C# is outside the scope of this website.

The ESP8266 has AT commands that perform the task for you - chiefly `AT+CIPSTART`.

The simplest to understand is probably TCP communication where you can just follow any of the myriad of website based examples. However instead of communicating with a website using HTTP you will be communicating with your own server software written in C# using your own custom designed protocol.

A simpler option may be to use a real web server as a "man in the middle" to which both the ESP8266 and your C# program communicate. That website could become a database back-end for your program.

Of course, what you decide to do depends entirely on how complex your program is and what data it is you want to transfer.


body:
I am working on a battery powered Arduino project, where I need to put a standalone Arduino in sleep mode (to save some battery).

My aim is to put Arduino in sleep mode by holding a button for 3 seconds or more on pin 2 (hardware interrupt) and wake it up by holding the same button by 3 seconds or more.

I can put the Arduino to sleep by holding button more than 3 seconds, but I can't wake it from it by holding the button for 3 seconds.

Below is my code:

    #include <avr/sleep.h>
    const int led1 = 44;
    const int led2 = 45;
    const int led3 = 46;
    const int usbState = 12;
    float pressLength = 0;
    const int button = 2;
    int optionOne = 100;
    int optionTwo = 3000;

    void setup() {
      pinMode(button, INPUT);
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(usbState, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      while (digitalRead(button) == LOW) {
        delay(100);
        pressLength = pressLength + 100;
        Serial.print("ms-");
        Serial.println(pressLength);
      }
      if (pressLength >= optionTwo) {
        digitalWrite(led1, LOW);
        digitalWrite(led2, LOW);
        digitalWrite(led3, LOW);
        sleepNow();     // sleep function called here
      } else if (pressLength >= optionOne) {
        digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        digitalWrite(led3, HIGH);
        while (1) {} //Keeps LEDS HIGH
      }
    }

    void sleepNow() {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
      sleep_enable(); // enables the sleep bit in the mcucr register
      attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
      sleep_mode(); // here the device is actually put to sleep!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
      while (digitalRead(button) == LOW) {
        delay(100);
        pressLength = pressLength + 100;
        Serial.print("ms-");
        Serial.println(pressLength);
      }
      if (pressLength >= optionTwo) {
        SleepNow(); //Back to sleep fucntion
      } else if (pressLength >= optionOne) {
        sleep_disable();
        // first thing after waking from sleep: disable sleep...
        resetFunc();//Resetting
      }
    }

    void wakeUpNow() {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up
    }
    void(* resetFunc)(void) = 0;

Please help. Thanks.

title: Waking Arduino from sleep by holding button for more than 3 seconds

Answers: 1

body:
You won't manage it without external circuitry.

The problem is the Arduino has to be awake to know you held the button for 3 seconds. You can only wake immediately you press the button. However you could then sleep again if the button is released within 3 seconds.

For external circuitry, you would need to arrange to charge (or discharge) a capacitor slowly through the button so that it reaches a threshold after 3 seconds and that threshold triggers the input to the Arduino. A HIGH input on the Arduino is 0.6×Vcc, so 3.3V for a 5V Arduino. If you arrange it that the capacitor reaches 3.3V after being charged for 3 seconds the input will see it at the right time.

<!-- 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/JVt4J.png)

<!-- End schematic -->

In this circuit, R1 and C1 form an RC network that charges the capacitor through the switch. C1 and R1+R2 form an RC network that discharges the capacitor all the time, so it is discharged when you release the button.

Discharge time will be slightly longer than charge time owing to the addition of R1 + R2.

To calculate the charge time, you can use T=RC which is how long (in seconds) it takes to charge the capacitor up to 63.2% of the supply voltage. That's fractionally over the 60% that the HIGH threshold is, so that's fine.

If you want T=RC to equal 3 seconds, you can rearrange the formula to suit your components. For instance if you have a 1000µF capacitor available you can rearrange to R=3/0.001 = 3kΩ. So a common 3.3kΩ resistor and 1000µF capacitor would give you (3300 × 0.001) 3.3 seconds.

R2 wants to be small enough that it doesn't slow down discharge too much, yet high enough that it doesn't draw too much current. Using about 10% of R1 is reasonable (330Ω), so with a 3.3 second charge time that resistor would increase the discharge time by 0.33 seconds.

This method is basically a very extreme form of debouncing.


body: I am working with RFID-RC522 and Arduino UNO. I have check pin configurations again and again tried different libraries. It is not reading card and red led on RC522 is consistently on.

title: RFID-RC522 not working, red led is on

Answers: 1

body:
Here's a picture of the card reader I have. If yours looks identical, then this library should work: https://github.com/ljos/MFRC522

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

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

The auth_read_write.ino sketch worked for me. Before you install the library, I recommend removing any other MFRC522 libraries from your arduino/library folder.

The only thing I did differently was used a 74HC4050 running at 3.3V between the Arduino and card reader. Some people claim you can connect the reader directly to the Arduino. I didn't want to take a chance of burning out the card reader so I used the 74HC4050.

Here's how I connected it:

    Component markings and connections

    |-------------------------------------------|
    |   SPI    |  UNO  | 74HC4050  | RFID-RC522 |
    |----------|-------|-----------|------------|
    | SDA (SS) |  10   |     7     |            |
    | SDA (SS) |       |     6     |    SDA     |
    | SCK      |  13   |     5     |            |
    | SCK      |       |     4     |    SCK     |
    | MOSI     |  11   |     3     |            |
    | MOSI     |       |     2     |    MOSI    |
    | MISO     |  12   |           |    MISO    |
    | IRQ      |  N/C  |    N/C    |    N/C     |
    | GND      |  GND  | 8,9,11,14 |    GND     |
    | RST      |   5   |           |    RST     |
    | 3.3V     |       |     1     |    3.3V    |
    |-------------------------------------------|


body:
I'm trying to send a set of data in Json format to a server I have set up which has a specific URL and an access token. The server requires a POST command. So my final URL is: http://myurl.com/myaccesstoken

The idea is that the Arduino UNO acquires some data from a sensor it then uses the ESP8266 to connect to wifi and send the acquired data to my server.

I do not understand why my server does not receive data

Thank you a lot in advance for your help.

I have used the following code:

--------

    #include "Arduino.h"
    #include "ESP8266.h"
    #include "SoftwareSerial.h"
    #include "ArduinoJson.h"

    #define ssid "mySSID"
    #define pw "myPW"
    #define IP "xxx.xxx.xxx.xxx"
    #define URL "http://myurl.com/myaccesstoken"

    int incomingByte;

    void setup() {//I connect to wifi
      Serial.begin(115200);
      Serial.println("AT");
      delay(5000);
      analogReference(INTERNAL);
      if(Serial.find("OK")){
        Serial.println("AT+CWMODE=3");
        delay(1000);
        String WF=String("AT+CWJAP=\"")+ssid+"\",\""+pw+"\"";
        Serial.println(WF);
        delay(5000);}
    }

    void loop() {
      //JSON data creation
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["flow"] = 2.54;
    root["measured"] = "2017-08-14T06:16:03.418Z";
    root.printTo(Serial);
    delay(5000);
     // I start communication with server
     Serial.println(String("AT+CIPSTART=\"TCP\",\"") + IP + "\",80");
     delay(5000);
     Serial.println("AT+CPSTATUS");
     // I use HTTP protocol to POST the data
        Serial.println("AT+HTTPINIT");
        delay(2000);
        Serial.println("AT+HTTPPARA=\"CID\",\"1");
        delay(2000);
        Serial.println("AT+HTTPPARA=\"URL\",\"http://myurl.com/myaccesstoken\"");
        delay(2000);
        Serial.println(String("AT+HTTPPARA=\"CONTENT\",\"application/json"));
        delay(2000);
        Serial.println("AT+HTTPDATA=\" + 81 + \",1000"); //81 is the computed length of my JSON
        delay(2000);
        Serial.println("AT+HTTPACTION=1");
        delay(2000);
        Serial.println("AT+HTTPREAD");
        delay(2000);
        if(Serial.available() > 0)
            {
                    // read the incoming byte:
                    incomingByte = Serial.read();
                    // say what you got:
                    Serial.print("I received: ");
                    Serial.println(incomingByte);
        }
        Serial.println();
        Serial.println("AT+HTTPTERM");

        delay(5000);
      }

title: POST to server using ESP8266 module- Arduino Uno- AT+ commands

Answers: 2

body:
Your code doesn't work because you start by sending ESP-specific AT commands to open a socket, then you suddenly switch to SIM800-specific AT commands, and the ESP goes "WTF dude?!"

I suggest you read some tutorials on accessing web sites with the ESP8266 not with the SIM800.

body:
I suggest you use computer based tools to start communication with ESP8266 module and test out sending and receiving data before you connect the module with Arduino.
If you are looking for tutorials for the same then I suggest you visit [this link][1] maybe it will solve your problem or give you a direction to work on

  [1]: http://absaransari.com/category/esp8266/


body:
I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.

Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.

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

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

title: Power consumption in Arithmetic Operation in Arduino UNO

Answers: 2

body: Why not just measure the current drawn by the board and an empty loop vs. a loop that does some multiplication? (other than 1,2,4,8..)

body:
The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.

The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.

Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

---

## Addition

### Test sketch

    volatile int foo = 100;
    int main (void)
      {
      DDRB = 0b00111111;  // all ports to output
      DDRC = 0b00111111;
      DDRD = 0b11111111;
      PORTB = 0;          // write LOW
      PORTC = 0;
      PORTD = 0;

      while (true)
        foo += 42;
      }

### Generated code

      a6: 80 91 00 01  lds r24, 0x0100
      aa: 90 91 01 01  lds r25, 0x0101
      ae: 8a 96        adiw r24, 0x2a ; 42
      b0: 90 93 01 01  sts 0x0101, r25
      b4: 80 93 00 01  sts 0x0100, r24
      b8: f6 cf        rjmp .-20      ; 0xa6 <main+0x10>

### Measured consumption

I measured an average of 7.00 mA.

---

## Multiplication

### Test sketch

    volatile int foo = 100;
    int main (void)
      {
      DDRB = 0b00111111;  // all ports to output
      DDRC = 0b00111111;
      DDRD = 0b11111111;
      PORTB = 0;          // write LOW
      PORTC = 0;
      PORTD = 0;

      while (true)
        foo *= 42;
      }

### Generated code

      a6: 4a e2        ldi r20, 0x2A ; 42
      a8: 20 91 00 01  lds r18, 0x0100
      ac: 30 91 01 01  lds r19, 0x0101
      b0: 42 9f        mul r20, r18
      b2: c0 01        movw r24, r0
      b4: 43 9f        mul r20, r19
      b6: 90 0d        add r25, r0
      b8: 11 24        eor r1, r1
      ba: 90 93 01 01  sts 0x0101, r25
      be: 80 93 00 01  sts 0x0100, r24
      c2: f2 cf        rjmp .-28      ; 0xa8 <main+0x12>

### Measured consumption

I measured an average of 6.32 mA.

---

## Conclusion

I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.

Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).

I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?

## Update

As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.


body:
I would like to measure a phase controlled 240Vac waveform as a digital PWM input for an arduino. The signal would look something like this:

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

My intent was to use a zener clipping circuit to limit the positive portion of the waveform to 5V, and measure that signal. However, I want to make sure I'm properly grounding these items. This is what my proposed circuit looks like, with all components inside a metal chassis.

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

  [1]: https://i.stack.imgur.com/UVC1i.jpg
  [2]: https://i.stack.imgur.com/9FywE.jpg

I feel like ideally I would isolate this waveform from the system controller/light with a 1:1 transformer, but I'm unsure if that is feasible given its irregularity. Can I safely connect the arduino ground to the system's neutral, or am I barking up the wrong tree?

Thanks!

title: Grounding for arduino, measuring phase controllled 240V

Answers: 2

body:
You shouldn't really connect the mains direct to the Arduino like that - even with a zener. The potential for disaster is somewhat large.

Instead you should galvanically isolate the mains from the Arduino. I would use something as simple as an opto-isolator:

<!-- 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/0wN00.png)

<!-- End schematic -->

Make sure that R1 is rated for at least 339V and can dissipate enough power (1W). The resistance of R1 needs to be small enough that the opto-isolator triggers properly, yet large enough that you don't need a great honking heater of a resistor to cope with the power. 150K seems a reasonable compromise.

D2 is needed to prevent the LED In the opto-isolator from being reverse biased with 339V in the reverse-swing portion of the waveform.

You can incorporate your zener as well if you want to "push down" the waveform to get a lower cross section of it (clip off the upper portion) instead of just reducing its amplitude:

<!-- 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/VCnrr.png)

<!-- End schematic -->

In this R1 is the same as the resistor you were planning to use before. The added R3 resistor is to limit the current through the LED (drop the 5V to the LED forward voltage at a suitable current for the LED).

body:
your circuit will work, and can be simplified a little bit further. But it will work.

it is safer to use isolation, however. there are multiple ways to go about doing it.

the key here is to detect zero crossing, and start counting from there.


body:
I'm looking for a way to swap servo 1 with a stepper motor to achieve a single direction circular motion with stops and delay. Instead, now I have the servo going back and forth to repeat the action.

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

This is the code I'm currently using to drive the servo:

    void loop() {
      topServo.write(115);
      delay(500);

      for(int i = 115; i > 65; i--) {
        topServo.write(i);
        delay(2);
    }

This is a schematic of my project:

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

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

Can anyone help me to configure this? or point me into the right direction.

Any help would be greatly appreciated!

title: How can I swap a servo with a stepper motor?

Answers: 1

body:
Firstly, I'm going to assume that you got a ULN2003 Motor driver board something like [this][1] along with your 28-BYJ48 stepper motor.

Secondly, I would always recommend using a separate power supply for your stepper motors. Even a small stepper motor like the 28-BYJ48 can draw up to 320mA, (160mA per winding).

<hr>

I've used the following code to test a setup using a 28-BYJ48 stepper motor and an Arduino. The connections to the driver board (IN1 - IN4) are mapped to pins 8-11 on the Arduino in this case. The code will cause the stepper to rotate 1 full revolution in one direction, pause for 1 second and then rotate one full revolution in the other direction.

(I've often found this simple piece of code really handy for troubleshooting!)

    #include <Stepper.h>

    const int stepsPerRev = 2048

    // initialise the stepper library on pins 8, 9, 10 & 11
    Stepper myStepper(stepsPerRev, 8,10,9,11);

    void setup() {
      // set the speed
      myStepper.setSpeed(4);

    }

    void loop() {
      // step one revolution in one direction:
      myStepper.step(stepsPerRev);
      delay(1000);

      // step one revolution in the other direction:
      myStepper.step(-stepsPerRev);
      delay(1000);

    }

  [1]: http://42bots.com/wp-content/uploads/2014/02/stepper01.jpg


body:
I am using an Arduino Mega2560
While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.

How can I make my motor move without stopping the reception of data from UART?

title: Can not receive data from UART with stepper motor

Answers: 1

body:
If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:

    void AccelStepper::runToNewPosition(long position)
    {
        moveTo(position);
        runToPosition();
    }

which, in turns calls:

    // Blocks until the target position is reached
    void AccelStepper::runToPosition()
    {
        while (run())
     ;
    }

In turn, run() returns false only when the position is reached, as shown here:

    boolean AccelStepper::run()
    {
        if (_targetPos == _currentPos)
     return false;

        if (runSpeed())
     computeNewSpeed();
        return true;
    }

As you can see, your program is blocked until the position is not reached.

Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.

To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.

In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in `rotate_motor()` call only:

    stepper1.moveTo(1100);

Then in the loop, write somewhere:

    stepper1.run();

EDIT:
Hint for having the motor moving forward and then backward as in your original code:
Add a state variable (say you call it "`m`"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling `stepper1.run()`, check if you actually must move (`if (m != 0)`). When you call the `stepper1.run()` method, check if it returns `false`. In this case it means it reached the position, then you must change the value of m accordingly.


body:
I just purchased Adafruit headphone jack and I want to know how to connect it to an Arduino 101. I'm trying to use a breadboard to play a sample tone melody from the Arduino libraries, which I want to hear with my iPhone headphones.

I have been looking online for instructions on how to do this, but found nothing. Please advise.

Thank you!

title: How do I connect an Adafruit headphone jack to an Arduino 101?

Answers: 1

body:
First you need to confirm that the socket will actually work with your headphones. Make sure that the ground connection of the headphones (either the sleeve or the ring right next to the sleeve, depending on the type of headphones) is serviced by a connection.

Second you need to wire one or both of the tip and the first ring to the Arduino's output that you are using to generate audio. This should be done through a capacitor to block the DC voltage and only pass the AC waveform.

<!-- 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/7Zoml.png)

<!-- End schematic -->

Ideally, though, you should first pass the signal through a small headphone amplifier otherwise you risk drawing too much current out of the Arduino's GPIO pin.


body:
I am trying to make a serial monitor print something based on when a button is pushed.

When the button is not pushed, the variable storing it equals 1.
When the button is pushed, the variable equals 0.
When I have an if statement like this, why does it print what I want when I have one where the zero is, but not when it is like that and the button IS pressed.

Thanks

    int led = 2;
    const int buzzer = 3;

    int upButton = 5;
    int downButton = 7;
    int enterButton = 6;

    int up = 1;
    int down = 1;
    int enter = 1;

    bool homeActivated = true;
    bool appsActivated = false;

    int homeLocation = 1;
    int appsLocation = 1;

    bool homePrinted = false;
    bool appsPrinted = false;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode (upButton, INPUT);
      pinMode (enterButton, INPUT);
      pinMode (downButton, INPUT);
      Serial.println("Initializing");
      delay(2000);
    }

    void loop() {
      up = digitalRead (upButton);
      enter = digitalRead (enterButton);
      down = digitalRead (downButton);

      //move up and down
      if (up = 0)
      {
        if (homeActivated = true)
        {
          homeLocation + 1;
          Serial.println("Scrolled Down 1");
          delay(1500);
          homePrinted = false;
        }
        else if (appsActivated = true)
        {
          appsLocation + 1;
          Serial.println("Scrolled Down 1");
          delay(1500);
          appsPrinted = false;
        }
      }

title: Troubleshooting an Arduino Computer Program

Answers: 1

body:
You need to learn basic C syntax.

`=` is assignment, not comparison.

For comparison you use `==`

* https://www.tutorialspoint.com/cprogramming/c_operators.htm


body:
Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz)
I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".

    $ dmesg | grep tty
    [    0.000000] console [tty0] enabled

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command    `dmesg | grep FTDI`, but no any output returned.

    $ ls -l /dev/ttyUSB*
    ls: cannot access '/dev/ttyUSB*': No such file or directory

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?

title: Arduino Editor: Monitor menu show "Serial port unavailable"

Answers: 2

body:
type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.

Now remove (hmm. easier if you do that before typing the command above).  and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.

With a bit of luck you'll see something like:
   Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341
   Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0
What comes after "now attached to" is what you need to use for the serial port....

body: Do a `ls -l /dev/tty*` in a console screen and then search for the tty* port that your arduino is connected to (mine is `ttyACM0`), you will see which group (my group is `dialout` for Ubuntu 17.10) you need to add yourself to in order to be able to access your arduino via the Serial Monitor.