body:
I'm trying to send GPS data using a neo-6m GPS module through WiFi using esp8266 module, I have both of the modules working alone, but when I try using both the WiFi works but won't send the data from the GPS.

I call the GPS and save the latitude, longitude, date and time to separate variables, then try sending those variables using the WiFi to the server on the Arduino Uno, but they just show up as 0's.

    #include <TinyGPS++.h>
    #include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(6, 7); // RX, TX
    #endif

    char ssid[] = "UPC9080883";            // your network SSID (name)
    char pass[] = "OYKXVYND";        // your network password
    int status = WL_IDLE_STATUS;

    int ledStatus = LOW;

    WiFiEspServer server(80);

    // use a ring buffer to increase speed and reduce memory allocation
    RingBuffer buf(8);

    static const int RXPin = 4, TXPin = 3;
    static const uint32_t GPSBaud = 9600;

    // The TinyGPS++ object
    TinyGPSPlus gps;

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

    double  latitude, longitude;
    int days, months, years, hr, mins, secs;
    void setup()
    {
      pinMode(LED_BUILTIN, OUTPUT);  // initialize digital pin LED_BUILTIN as an output.
      Serial.begin(115200);   // initialize serial for debugging
      Serial1.begin(9600);    // initialize serial for ESP module
      WiFi.init(&Serial1);    // initialize ESP module

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }

      // attempt to connect to WiFi network
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      Serial.println("You're connected to the network");
      printWifiStatus();

      // start the web server on port 80
      server.begin();
    }

    void loop()
    {
      Serial1.end();
      Serial2.begin(GPSBaud);
      GPS();
      Serial2.end();
      Serial1.begin(9600);
      WiFiEspClient client = server.available();  // listen for incoming clients
      if (client) {                               // if you get a client,
        Serial.println("New client");             // print a message out the serial port
        buf.init();                               // initialize the circular buffer
        while (client.connected()) {              // loop while the client's connected
          if (client.available()) {               // if there's bytes to read from the client,
            char c = client.read();               // read a byte, then
            buf.push(c);                          // push it to the ring buffer

            // printing the stream to the serial monitor will slow down
            // the receiving of data from the ESP filling the serial buffer
            //Serial.write(c);

            // you got two newline characters in a row
            // that's the end of the HTTP request, so send a response
            if (buf.endsWith("\r\n\r\n"))
            {
              sendHttpResponse(client);
              break;
            }
          }
        }

        // close the connection
        client.stop();
        Serial.println("Client disconnected");
      }
    }
    void GPS() {
      while (Serial2.available() > 0) {
        gps.encode(Serial2.read());
        if (gps.location.isUpdated()) {
          // Latitude in degrees (double)
          latitude = (gps.location.lat(), 6);
          // Longitude in degrees (double)
          longitude = (gps.location.lng(), 6);

          // Day (1-31) (u8)
          days = (gps.date.day());
          // Month (1-12) (u8)
          months = (gps.date.month());
          // Year (2000+) (u16)
          years = (gps.date.year());

          // Hour (0-23) (u8)
          hr = (gps.time.hour());
          // Minute (0-59) (u8)
          mins = (gps.time.minute());
          // Second (0-59) (u8)
          secs = (gps.time.second());
          Serial.println(longitude);
          Serial.println(latitude);
          Serial.println(days);
          Serial.println(months);
          Serial.println(years);
          Serial.println(hr);
          Serial.println(mins);
          Serial.println(secs);

        }
      }
    }

    void sendHttpResponse(WiFiEspClient client)
    {
      // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
      // and a content-type so the client knows what's coming, then a blank line:
      client.println("HTTP/1.1 200 OK");
      client.println("Content-type:text/html");
      client.println();

      // the content of the HTTP response follows the header:
      client.println("
");
      client.println("
");
      client.print("Latitude= ");
      client.print(latitude);
      client.print(" Longitude = ");
      client.println(longitude);
      client.println("
");
      client.print("Date: ");
      client.print(days);
      client.print("/");
      client.print(months);
      client.print("/");
      client.print(years);
      client.println("
");
      client.print("Time: ");
      client.print(hr);
      client.print(":");
      client.print(mins);
      client.print(":");
      client.print(secs);
      // The HTTP response ends with another blank line:
      client.println();
    }

    void printWifiStatus()
    {
      // print the SSID of the network you're attached to
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print where to go in the browser
      Serial.println();
      Serial.print("To see this page in action, open a browser to http://");
      Serial.println(ip);
      Serial.println();
    }

title: Sending GPS data through a WiFi module

Answers: 1

body:
SoftwareSerial can't listen on two instances. There is a `.listen()` function to switch between SoftwareSerial instances.

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to receive data from GPS module over hardware Serial.


body: I searched for answers but I didn't found any answers to my problem. Actually, I use my Arduino with a 16x2 LCD screen. But as the title says, only the half of the screen displays (8x2), the other side just doesn't turn on. Do someone knows how to solve this problem?

title: Only half of the 16x2 LCD appears

Answers: 0


body:
Rx Code:

    #include <Servo.h>
    Servo myServo;

    void setup() {
    Serial.begin(9600);
    myServo.attach(9);
    delay(5000);
    myServo.write(0);
    }

    void loop() {
      while(Serial.available()==0);

        int d = Serial.read() - '0';
        if(d>0)
        {
          int pos = map(d,0,9,0,180);
          pos = constrain(pos,0,180);
          myServo.write(pos);
          Serial.println(d);

          delay(50);
          }
          else
          {};

    }

Tx code:

    int sensorValue = 0;         // the sensor value
    int sensorMin = 1023;        // minimum sensor value
    int sensorMax = 0;           // maximum sensor value
    int SensorMid = 0;
    const int POWER_OF_TWO_TO_AVERAGE = 6;

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

      while (millis() < 10000) {
        digitalWrite(13,HIGH);
        sensorValue = analogRead(A1);
        if (sensorValue > sensorMax) {
          sensorMax = sensorValue;
        }
        if (sensorValue < sensorMin) {
          sensorMin = sensorValue;
        }
      }
      SensorMid = (sensorMin + sensorMax )/2;
      digitalWrite(13,LOW);
      }

    void loop() {
    int val = map(analogRead(A1),SensorMid,sensorMax,0,9);
    Serial.println(val);
    delay(100);
    }

I am building a robotic arm and I am facing some problems regrading to the servos stability with the flex, I am using the flex as the transmitter and the servo as the receiver, and when I press my finger my servo doesn't move properly.

Any suggestions?

title: I am building an robotic arm by using flex sensor, servo and 2 xbees

Answers: 1

body:
Without knowing more about the actual problem of "doesn't move properly", what I initially see is that you are transmitting values 0-9 by using `Serial.println()`, which sends the byte data, and also a newline (ASCII value `10`), so your RX code is probably getting alternating input of the intended value, and the value `10`, which is getting subtracted from `48` (the ASCII value of `'0'`), `map`ped and `constrain`ed to `0`.

Try changing your TX script to call `Serial.print()` instead. Your receiver doesn't care about each value showing up on a new line -- it doesn't know about lines.


body:
Is there a way to "ask" the Arduino what sketch was compiled on it?

There are several versions of the sketch and I need to see which version the Arduino has been running.

title: What Version of the Sketch did I leave on there?

Answers: 2

body:
First, you have to store the desired information in your sketch.

    #define VERSION F("0.01 4-Apr-2019")

    void setup() {
       Serial.begin(9600);
       Serial.print(F("Test Sketch V"));
       Serial.println(VERSION);
    }

    void loop() {
    }

Of course any other way might work as well:

- Only print it, if at reset a test button is pressed

- Check for a Serial command and respond the version info.

- Don't print it, but use avrdude and a programmer to read the FLASH memory and search it for the version string. (Similar to jot's comment above)

body:
If you have not set the flash protection bits you can read back the contents of the program memory. See https://www.evilmadscientist.com/2011/avr-basics-reading-and-writing-flash-contents/

By reading back the first pages you can then compare with the different versions of the sketch (hex file) and determine which version is on the device. The first pages are the different ISR vectors and should be unique for the sketches.

Cheers!


body:
Many electronic devices turn on/off, or more correctly on/sleep, by pressing a button and holding it for two or three seconds. I would like to put this ability into a project using an Adafruit Feather board.  The sleep side is easy, I can detect a level and if it stays there for some time, run the code to put the processor to sleep.  My question involves the wake up side. The chip wakes up via an interrupt.

The question then becomes, how do I generate the interrupt source only after the button has been held for the designated time? I've considered two options:

1) Use a level interrupt and an RC circuit to do the delay.
2) Have the processor wake up immediately and then implement logic to determine if it has been held "long enough" and go back to sleep if not.

Am I missing an easy option? Is there a general consensus on the best way to do this? It seems like such a normal thing that I'm surprised my searches haven't turned up any tutorials.

title: Push and hold on/off switch for arduino

Answers: 1

body:
I would go for option 2.

You can wake up the controller immediately, but only the processor.

Then just start waiting for the "long enough" time that you defined, regulary checking the button state. If the button is still pushed, then initiate full wake up. If it is released, go back to sleep.

This is the easy option, requiring no extra hardware, and only a dozen of so of lines of code.

Another option, that exist and have a somewhat similar behaviour, is to have your processor wake up regulary on timer, and checking the state of the input. This is what is done for "radio controled" devices, for example (Where the "button" is a radio circuit that need to be switch on and off).
Given a sufficiently long sleep between check, on average you will get the "long enough" delay.

This option is useful when you don't have available interrupt pins, or you need something more complex that a button as the input.


body:
I am currently working with MPU-6050. Now I want to minus gravity from my accelerometer's value as we minus the offset.

Here is the code:

    #include <Wire.h>
    #include <MPU6050.h>
    //read as rool:pitch:yaw:accX:accY:accZ
    MPU6050 mpu;
    unsigned long timer = 0;
    float timeStep = 0.01;
    float pitch = 0;
    float roll = 0;
    float yaw = 0;
    float accX = 0;
    float accY = 0;
    float accZ = 0;
    float rollRad = 0;
    float pitchRad = 0;
    float yawRad = 0;

    int count = 0;

    Vector minusGravity(Vector vec)
    {
        /*
         float x = vec.XAxis, y = vec.YAxis, z = vec.ZAxis;
         vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) + x * cos(pitchRad) + z
               * sin(pitchRad) + 0;
         vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) + 0 + y * cos(rollRad) -
               z * sin(rollRad);
         vec.ZAxis -= 0 - x * sin(pitchRad) + z * cos(pitchRad) + y *
               sin(rollRad) + z * cos(rollRad);
        */

        return vec;
    }

    float accP(float value)
    {
        int x = (int)(value * 10);
        return ((float)(x)) / 10;
    }

    void setup()
    {
        Serial.begin(115200);
        while (!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
        {

        }
        //mpu.calibrateGyro();
        mpu.setThreshold(1);
     }

     void loop()
     {
        timer = millis();
        Vector norm = mpu.readNormalizeGyro();
        pitch = pitch + norm.YAxis * timeStep;
        roll = roll + norm.XAxis * timeStep;
        yaw = yaw + norm.ZAxis * timeStep;
        Vector normAccel = minusGravity(mpu.readNormalizeAccel());
        rollRad = roll * 0.0174533;
        pitchRad = pitch * 0.0174533;
        yawRad = yaw * 0.0174533;

        Serial.print(roll);
        Serial.print(":");
        Serial.print(pitch);
        Serial.print(":");
        Serial.print(yaw);
        Serial.print(":");
        accX = accP(normAccel.XAxis);
        accY = accP(normAccel.YAxis);
        accZ = accP(normAccel.ZAxis);
        Serial.print(accX);
        Serial.print(":");
        Serial.print(accY);
        Serial.print(":");
        Serial.println(accZ);
        delay((timeStep * 2500) - (millis() - timer));
    }

I understand the problem is here :

    vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) + x * cos(pitchRad) + z
               * sin(pitchRad) + 0;
         vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) + 0 + y * cos(rollRad) -
               z * sin(rollRad);
         vec.ZAxis -= 0 - x * sin(pitchRad) + z * cos(pitchRad) + y *
               sin(rollRad) + z * cos(rollRad);

New code :

          #include <Wire.h>
      #include <MPU6050.h>
      //read as rool:pitch:yaw:accX:accY:accZ
      MPU6050 mpu;
      unsigned long timer = 0;
      float timeStep = 0.01;
      float pitch = 0;
      float roll = 0;
      float yaw = 0;
      float accX = 0;
      float accY = 0;
      float accZ = 0;
      float rollRad = 0;
      float pitchRad = 0;
      float yawRad = 0;
      float gX = 0;
      float gY = 0;
      float gZ = -9.8;

      int count = 0;

      Vector minusGravity(Vector vec)
      {

        float x = gX, y = gY, z = gZ;
        vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) ;
        vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) ;

        x = vec.XAxis; z = vec.ZAxis;
        vec.XAxis -=  x * cos(pitchRad) + z * sin(pitchRad) ;
        vec.ZAxis -= - x * sin(pitchRad) + z * cos(pitchRad) ;

        y = vec.YAxis, z = vec.ZAxis;
        vec.YAxis -=  y * cos(rollRad) - z * sin(rollRad);
        vec.ZAxis -=  y * sin(rollRad) + z * cos(rollRad);

        return vec;
      }

      float accP(float value)
      {
        int x = (int)(value * 10);
        return ((float)(x)) / 10;
      }

      void setup()
      {
        Serial.begin(115200);
        while (!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
        {

        }
        //mpu.calibrateGyro();
        mpu.setThreshold(1);
        Vector normAccel = mpu.readNormalizeAccel();
        gX = normAccel.XAxis;
        gY = normAccel.YAxis;
        gZ = normAccel.ZAxis;
      }
      void loop()
      {
        timer = millis();
        Vector norm = mpu.readNormalizeGyro();
        pitch +=  norm.YAxis * timeStep;
        roll += norm.XAxis * timeStep;
        yaw += norm.ZAxis * timeStep;
        Vector normAccel = minusGravity(mpu.readNormalizeAccel());
        rollRad = roll * 0.0174533;
        pitchRad = pitch * 0.0174533;
        yawRad = yaw * 0.0174533;
        Serial.print(roll );
        Serial.print(":");
        Serial.print(pitch );
        Serial.print(":");
          Serial.print(yaw );
        Serial.print(":");
        accX = accP(normAccel.XAxis);
        accY = accP(normAccel.YAxis);
        accZ = accP(normAccel.ZAxis);
        Serial.print(accX);
        Serial.print(":");
        Serial.print(accY);
        Serial.print(":");
        Serial.println(accZ);
        delay((timeStep * 2500) - (millis() - timer));
      }
It is little buggy.

Can anyone help me figure out what is my mistake ?

title: Remove gravity from accelerometer of MPU-6050

Answers: 1

body:
I may have come to a solution :

    Vector minusGravity(Vector vec)
    {

     float x = vec.XAxis, y = vec.YAxis, z = 0;
     vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) ;
     vec.YAxis -= x * sin(yawRad) - y * cos(yawRad) ;

     x = vec.XAxis; z = vec.ZAxis;
     vec.XAxis -=  x * cos(pitchRad) + z * sin(pitchRad) ;
     vec.ZAxis -= - x * sin(pitchRad) + z * cos(pitchRad) ;

     y = vec.YAxis, z = vec.ZAxis;
     vec.YAxis -=  y * cos(rollRad) - z * sin(rollRad);
     vec.ZAxis -=  y * sin(rollRad) + z * cos(rollRad);

     return vec;
    }

Now this is far better, as after calculating effect of `roll,pitch,yaw` in every step the  `x,y,z` changes. I missed that part. I was calculating directly, so it was giving me wrong value.

`vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) `

then, `vec.XAxis -=  x * cos(pitchRad) + z * sin(pitchRad) `
 doesn't give the same result as the wrong one `vec.XAxis -= x * cos(yawRad) - y * sin(yawRad) + x * cos(pitchRad) + z
           * sin(pitchRad) + 0;`


body:
I am frustrated with my arduino project can you help me?
I am using Arduino Uno, electric lock (high/low), 4 distance sonic modules. Basically I have 4 drawers, I am measuring the distance - how much are they opened and if they are opened in given limits, I set the electric lock open (high).

It is working, but after some while, it stops and it stops running.
I have tried to comment all serial communication - didn't help. I have tried to use proper variable data types - same. I have tried to buy much powerful power source - 12V 3,5A and I bought Electrolyte condenzator 4,7mF to balance the power peaks while the lock closes - didn't help.

The lock is turned on using relay, connecting it directly to power source 12V.
Relay is powered from 5V arduino supply and controlled by arduino Digital pin.
4 Sonic distance modules are powered from arduino power supply.

Its even more funny that it starts running after ~10 minutes from nothing. Im confused.

Code:

        // defines pins numbers
    const int trigPin1 = 2;
    const int echoPin1 = 3;
    const int trigPin2 = 6;
    const int echoPin2 = 5;
    const int trigPin3 = 9;
    const int echoPin3 = 8;
    const int trigPin4 = 12;
    const int echoPin4 = 11;
    const int relayPin = 7;
    //distance limits
    const int minSuplik4=27;//suplik4
    const int maxSuplik4=29;
    const int minSuplik3=22;//suplik3
    const int maxSuplik3=24;
    const int minSuplik2=32;//suplik2
    const int maxSuplik2=34;
    const int minSuplik1=9;//suplik1
    const int maxSuplik1=11;
    /*
    double PreDistance1[4]={0,0,0,0};//supliky
    double PreDistance2[4]={0,0,0,0};//supliky
    double PreDistance3[4]={0,0,0,0};//supliky
    */
    long distance[4]={0,0,0,0};//array with distances
    int i;
    int x;

    int trigPinX[4]={trigPin1,trigPin2,trigPin3,trigPin4};//supliky
    int echoPinX[4]={echoPin1,echoPin2,echoPin3,echoPin4};//supliky
    int maxD[4]={maxSuplik1,maxSuplik2,maxSuplik3,maxSuplik4};//supliky
    int minD[4]={minSuplik1,minSuplik2,minSuplik3,minSuplik4};//supliky
    void setup() {
    pinMode(relayPin, OUTPUT);
    pinMode(trigPin1, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin1, INPUT); // Sets the echoPin as an Input
    pinMode(trigPin2, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin2, INPUT); // Sets the echoPin as an Input
    pinMode(trigPin3, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin3, INPUT); // Sets the echoPin as an Input
    pinMode(trigPin4, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin4, INPUT); // Sets the echoPin as an Input
    digitalWrite(relayPin, LOW);
    Serial.begin(9600); // Starts the serial communication
    }
    void loop() {

    for (int i=0; i<4; i++)
    {
      delay(5);
      distance[i]=DistanceFunction(trigPinX[i],echoPinX[i]);
      delay(20);
      /*********** DEBUG ************
      Serial.print("Distance");// Prints the distance on the Serial Monitor
      Serial.print(i+1);
      Serial.print(":");
      Serial.print(distance[i]);
      Serial.print("<");
      Serial.print(minD[i]);
      Serial.print(":");
      Serial.print(maxD[i]);
      Serial.print(">");
      Serial.print(";");
      *********************************/
    }

    if(distance[0]>=minD[0] && distance[0]<=maxD[0] && distance[1]>=minD[1] && distance[1]<=maxD[1] && distance[2]>=minD[2] && distance[2]<=maxD[2] && distance[3]>=minD[3] && distance[3]<=maxD[3])
          {
            OpenFcn();
          }
    else
          {
            CloseFcn();
          }
    delay(100);
    }

    int DistanceFunction(int trigPin, int echoPin)
    {
      digitalWrite(trigPin, LOW);// Clears the trigPin
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);// Sets the trigPin on HIGH state for 10 micro seconds
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      long duration = pulseIn(echoPin, HIGH);// Reads the echoPin, returns the sound wave travel time in microseconds
      long distanceFcn= duration*0.034/2;// Calculating the distance
      return distanceFcn;
    }

    int OpenFcn()
    {
      digitalWrite(relayPin, HIGH);
      //Serial.println("OPENED");
      for (int x=5; x>0; x--)
        {
          //Serial.println("Otevreno:");
          //Serial.println(x);
          delay(1000);
        }
    }

    int CloseFcn()
    {
      digitalWrite(relayPin, LOW);
      //Serial.println("CLOSED");
    }

[![This is the moment when it start working crazy][1]][1]

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

title: Arduino freezes while running code

Answers: 1

body:
It looks like that there was a problem in the relay module or power supply cord. I have changed these two HW elements and looks like it is working. The reason why it did malfuctioning the arduino was, that when i moved the drawer, it slightly moved the power cord which had bad connection, so it made voltage drop on arduino supply and started to do crazy things.
Thanks all for your time


body:
We checked Xbee, ZigBee and other alternatives already and we're trying to figure out a way for good and cheap network system. NRF24l01 looks good but 32 bytes not enough actually. Even so looks like we'll use it but some questions;

Questions' scenario contains 1 master and 300 slave devices with NRF24l01. We're thinking about making a addressing system like computer networks and every message will contain device id or device group tag. Master will be at the center of the room. Room do not have any inner wall or obstacle. Maximum range is less than 100m².

1) May messages get corrupt or latency ?
2) Is there any prepared library for Arduino for this kind of communication ?
3) Do you think is there any better solution for this kind of master & slaves networking logic (*must be cheap and stable*) ?

title: NRF24L01 Networking

Answers: 1

body:
> 1) May messages get corrupt or latency ?

For uni-directional Master to One Slave, no, there should be no corruption (at least not caused by there being lots of slaves present). For bi-directional Master to Multiple Slaves at the same time, yes, you're going to run into problems when the slaves try and reply. Keeping your protocol really simple will be beneficial.

> 2) Is there any prepared library for Arduino for this kind of communication ?

There's nothing special about what you propose. The RF24.h library will probably do the job (though I have never used it, so don't ask me how to use it).

> 3) Do you think is there any better solution for this kind of master & slaves networking logic (must be cheap and stable) ?

They're all a bit of a muchness really. RF communication is RF communication. It's how you use it that matters.

The nRF24L01+ has a number of benefits that mean you can do some things in hardware:

* Multiple receive pipes, each with their own address - so you can have one for the device address, one for a group address, and one for a global "broadcast" address
* Auto-acknowledge and re-sending of failed packets for more reliable communication (only for one-to-one communication)
* Automatic packetisation so you don't have to worry about crafting a low-level protocol of your own
* Direct communication giving low-latency
* Power Amplifier option for greater range.

You could use WiFi, however that would struggle with so many devices (most home access points and routers can't handle more than a few dozen devices), plus it adds extra latency that it sounds like you don't want.

The nRF24L01+ is probably a good choice for this kind of communication - however, be cautious with cheap clone devices: some of them have a silicon error that causes them to not be compatible with other nRF24L01+ devices.


body:
I'm working on RFID project to handle multiple cards.

I did most of the things OK. But now I have one problem. Which is the following:

1. The RFID code is 5 bytes, so I need an array of 5 bytes. If more cards then the array size = number of card * 5.
2. For my example I'm working with 2 cards. So array size is 10 bytes.
3. I can store the first card in the first 5 bytes.

The problem:
I can't store the 2nd card in the next 5 bytes in the array. I don't know why.

This is my only test code:

    /****************************** LIBRARIES ******************************/
    #include <SPI.h>
    #include <RFID.h>

    /****************************** DEFINITIONS ******************************/
    // pins definitions
    #define SS_PIN          10
    #define RST_PIN         9

    // setup definitions
    #define CARDS           2
    #define MXCD            CARDS*5

    /****************************** VARIABLES ******************************/
    // rfid variables:
    byte crd_buf[MXCD],card_no;
    byte register_lock,check_lock,print_lock;

    /****************************** FUNCTIONES ******************************/
    // rfid functions
    void register_accepted_card(void);
    void record_new_cards(void);
    void check_card(void);
    void print_registered_cards(void);

    // objects
    RFID rfid(SS_PIN, RST_PIN);

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

    void loop(){
        register_accepted_card(); // apply only once
    }

    void register_accepted_card(void){
      if (!register_lock) {
        if (rfid.isCard()) {
          if(rfid.readCardSerial()){
            if(card_no>0){
              for(byte i = 0; i<card_no; i++){
                if(!memcmp((crd_buf+(i*5)),rfid.serNum,5)){

                  Serial.println("already card is");
                  for(byte p = i*5; p<(i*5)+5; p++){
                    Serial.print(crd_buf[p],HEX);Serial.print(", ");}
                    Serial.println();

                  lcd_state = ALREADY_MSG;
                  register_lock = 1;
                }
              }
            }

            //////////////////////////
            // problem is in this part
            //////////////////////////

            if(!register_lock){

              for(byte i=card_no*5;i<(card_no*5)+5;i++){
                crd_buf[i] = rfid.serNum[i];}

              Serial.print("loop#"); Serial.println(card_no);
              Serial.print("start index ");Serial.println(card_no*5);
              Serial.print("end index ");Serial.println((card_no*5)+5);
              Serial.println();

              Serial.print("card#"); Serial.println(card_no+1);
              for(byte i=card_no*5;i<(card_no*5)+5;i++){
                Serial.print(crd_buf[i],HEX);Serial.print(", ");}
              Serial.println();Serial.println("//////////////////////////");

              card_no++;
              if(card_no >= CARDS){lcd_state = FINISH_MSG;}
              else{lcd_state = REGISTER_MSG;}
              register_lock = 1;
            }
          }
        }
        rfid.halt();
      }
    }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

My second question, for the part of checking the cards after finishing registering the cards to be accepted.

I did a for loop for the number of cards to get the card that is registered in the array and send a message that the card is stored and accepted, otherwise, it returns a denied message that the card isn't stored in the array with alarm buzzer.

The problem that is the for loop checks the card for all the indexes in the array which is what I want but the result is mixed with accepted and denied.

The question is how to get out of the for loop?

    void check_card(void){
      if (check_lock){
        if (rfid.isCard()){
          if (rfid.readCardSerial()){
            for(byte i=0;i<card_no;i++){

              // start of for loop
              Serial.print("check# ");Serial.println(i);
              if(!memcmp(crd_buf+(i*5),rfid.serNum,5)){
                Serial.println("card accepted");
                digitalWrite(ACCEPT_LED,HIGH);
                digitalWrite(DENIED_LED,LOW);
                digitalWrite(BUZZER,LOW);
                check_lock = 0;
                sys_state = 1;
                lcd_state = ACCEPTED_MSG;
              }
              else{
                Serial.println("card denied");
                digitalWrite(ACCEPT_LED,LOW);
                digitalWrite(DENIED_LED,HIGH);
                digitalWrite(BUZZER,HIGH);
                check_lock = 0;
                sys_state = 1;
                lcd_state = DENIED_MSG;
              }
            }
                // end of for loop

          }
          rfid.halt();
        }
      }
    }

title: Can't store RFID data in the next 5 bytes of array

Answers: 1

body:
Your problem is this bit:

          for(byte i=card_no*5;i<(card_no*5)+5;i++){
            crd_buf[i] = rfid.serNum[i];}

For the first card you're copying bytes 0-4 of the serNum to bytes 0-4 of crd_buf.

However for the second card you're copying bytes 5-9 of serNum to bytes 5-9 of crd_buf.  That's correct for crd_buf but wrong for serNum.

The right way would be to add card_no*5 to i when creating the index:

          for(byte i=0; i<5; i++){
            crd_buf[(card_no*5) + i] = rfid.serNum[i];}

Or better to define your card buffer as a 2D array so you don't need to do that calculation:

    byte crd_buf[CARDS][5];

    for (i = 0; i < 5; i++) {
        crd_buf[card_no][i] = rfid.serNum[i];
    }

Or simpler:

    memcpy(crd_buf[card_no], rfid.serNum, 5);

----

For your second question, don't print your message at all in the loop.

Instead start out assuming that access is denied. Then if a card matches, grant access.  The simplest way is with a flag.

    if (rfid.readCardSerial()){

        bool accessGranted = false;  // A flag to store the state - start off denied.

        for(byte i=0;i<card_no;i++){
            if(!memcmp(crd_buf+(i*5),rfid.serNum,5)){
                accessGranted = true;
            }
        }

        // replace these with your own message routines.
        if (accessGranted) {
            Serial.println("Access Granted");
        } else {
            Serial.println("Access Denied");
        }
    }


body:
I managed to work with timer 0 and 1 but am unable to generate a PWM with timer 2 in my atmega328p.

This is the code:

    #include <avr/io.h>

    int main(void)
    {
        /* PD6 output */
        DDRD |= (1 << DDD6);

        /* 50% duty cycle */
        OCR2A = 128;

        /* fast PWM  */
        TCCR2A |= (1 << WGM21) | (1 << WGM20);

        /* prescaler = 8 */
        TCCR2B |= (1 << CS21);

        while (1);

    }

Could someone explain what the issue is and why I am not seeing a pwm signal on pin 6 of my arduino uno board?

Thanks

title: Why is no PWM signal generated using Timer 2?

Answers: 1

body:
The output compare unit of timer 2 is connected to pins PB3 (OC2A) and PD3 (OC2B). So you have to configure those as outputs.
Keep in mind that you can't choose any pin when using hardware pwm, this hardware feature is linked to specific pins.

You also have to set `COM2A1` in `TCCR2A`. Otherwise `OC2A` is disconnected from the output compare unit (ref: Table 17-3 in [datasheet][1]).
The effect of `COM2A0/1` depends on the configuration in `WGM20`-`WGM22`.
The same applies to `OC2B` respectively.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf


body:
I want to run multiple sketches on one sketch. I use the method of multiple void loops. It works but esp8266 take a lot of time to execute commands.

    void Setup()
     {
      setup1();
      setup2();
     }
    void loop()
     {
      loop1();
      loop2();
     }

Is there any method to avoid that ?

title: Multiple void loops with ESP8266

Answers: 2

body:
If the `setup()` or `loop()` functions call `delay()` then of course that will delay getting to the next function and will slow down the whole process.

The only way to deal with that is to rewrite the code, combining what you're calling and fixing it so that it takes into account the other work it needs to do.

Same thing if you call any blocking functions, like reading from `Serial` until you get a newline.

If that's not the case... well, the ESP8266 is a small, not particularly fast processor. If there are no delays or blocking functions then your code is running as fast as your code might run and you'll just have to live with it.

body:
As long as you're not using `delay()` or other blocking code, as John mentions in his answer, that approach will work fine. I have a fairly large project where I defined a class `ArduinoObject`. The `ArduinoObject` class has a setup method and a loop method, and the main sketch creates and manages an array of `ArduinoObject`s (and another stack of a subclass of `ArduinoObject` called a `MenuObject` that manages menus on the LCD screen the project uses.)

At times there are a dozen or more `ArduinoObjects` being called on each pass through the sketch's `loop()` function and it works just fine. The key thing is to write your sub-loops to be FAST. They should do a tiny amount of work on each pass, and then a little more on the next pass (if needed.) You never want one of your sub-loops to take enough time to make the other sub-loops "stutter".


body:
I am new to Arduino, some how I have put this code together to run stepper motor using LDR(kind of solar tracker program) I searched on net and tried using servo motor circuit to run stepper motor, assuming just replacing servo motor with stepper motor would work. I guess that is not the case (because servo motor is not moving according to LRD inputs). Please help me with circuit diagram.

Here is the code I am using

```

const int dirPin  = 5;
const int stepPin = 4;
const int enPin   = 6;
const int SensorPin1 = A0;
const int SensorPin2 = A1;
int sensorValue1 = 0;
int sensorValue2 = 0;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);

  pinMode(enPin,OUTPUT);
  digitalWrite(enPin,LOW);
  Serial.begin(9600);

}
void loop() {
  sensorValue1 = analogRead(SensorPin1);
  Serial.println(sensorValue1);
  sensorValue2 = analogRead(SensorPin2);
  Serial.println(sensorValue2);

  if(sensorValue1 < 40 && sensorValue2 < 400){
    Serial.print("No sun Detected");
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,LOW);
  }
  else if(sensorValue1 > 400){

    digitalWrite(dirPin,HIGH);
    digitalWrite(stepPin,HIGH);

 }
else if(sensorValue2 > 400){
    digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,HIGH);
}
}

```

**Hardware Used:**

 - Bipolar stepper motor- NEMA 23 20Kg torque
 - Stepper driver: TB6600
 - Power supply: SMPS 12V, 5amp
 - LDR: 2
 - Resistors: 2, 10K resistors
 - 1 Arduino Uno
 - Breadboard

[![Circuit Diagram][1]][1]

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

title: Circuit diagram for running bipolar stepper motor using LDR

Answers: 1

body:
If it helps, I tuned your code little.

    const int dirPin  = 8;
    const int stepPin = 7;
    const int enPin   = 13;//with pin 13 You can monitor on-board LED, if its lit, "enable" is HIGH and stepper will turn.
    const int rightSensorPin = A0;
    const int leftSensorPin = A1;
    int rightSensorRead = 0;
    int leftSensorRead = 0;
    int rightLightPct = 0;
    int leftLightPct = 0;
    int degreeChange = 1;

    void setup() {
      Serial.begin(9600);
      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
      pinMode(enPin,OUTPUT);
      pinMode(A0, INPUT_PULLUP);//no need extra resistors. Just connect one LDR leg to A0 and another GND.
      pinMode(A1, INPUT_PULLUP);
    }

    void loop() {
      rightSensorRead = analogRead(rightSensorPin);
      leftSensorRead = analogRead(leftSensorPin);
      rightLightPct = map(rightSensorRead, 0, 1023, 0, 100);
      leftLightPct = map(leftSensorRead, 0, 1023, 0, 100);
      degreeChange = map(abs(rightLightPct-leftLightPct),0,100,2,10);
      Serial.print("right = ");
      Serial.print(rightSensorRead);
      Serial.print(" left = ");
      Serial.print(leftSensorRead);
      Serial.print(" Pct r/l = ");
      Serial.print(rightLightPct);
      Serial.print("/");
      Serial.println(leftLightPct);
      if(rightLightPct < 15 && leftLightPct < 15){
        Serial.println("Sun is detected");
        digitalWrite(enPin, LOW);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
        delay(5000);//if somthing get in a way, program waits 5 sec. If nothing in that time, program will continue. That time may erase or add some more.
      }else if(rightLightPct > 50 && leftLightPct > 50){
        Serial.println("Sun is set!");
        digitalWrite(enPin, LOW);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
      }else if(rightLightPct > 20 && leftLightPct > 20){
        Serial.println("Seeking sun!");
        digitalWrite(enPin, HIGH);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
        delay(1);
        digitalWrite(stepPin,HIGH);
      }else if(rightLightPct > leftLightPct){
        Serial.println("Turning CW!");
        digitalWrite(enPin, HIGH);
        digitalWrite(dirPin,HIGH);
        digitalWrite(stepPin,LOW);
        delay(1);
        digitalWrite(stepPin,HIGH);
      }else{
        Serial.println("Turning CCW!");
        digitalWrite(enPin, HIGH);
        digitalWrite(dirPin,LOW);
        digitalWrite(stepPin,LOW);
        delay(1);
        digitalWrite(stepPin,HIGH);
      }
    }


body:
I'm trying to read from an MCP23008 I/O expander using the Wire library over I2C. The MCP23008 is wired to address 0x04, giving an effective device address of 0x24. Writing to the device GPIO seems to work fine, and I'm a bit confused on how to read from the GPIO.

So I set it up for read as follows:

    #define MCP23008_DEVICE_I2C_ADDRESS 0x20
    #define MCP23008_SLAVE_I2C_ADDRESS  0x04

    #define MCP23008_REGISTER_IODIR     0x00
    #define MCP23008_REGISTER_GPIO      0x09

    #define IO_ALL_PINS_INPUT           0xFF

    inline void eeprog::_read_enable()
    {
        Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
        {
            Wire.write(MCP23008_REGISTER_IODIR); // Set I/O direction
            Wire.write(IO_ALL_PINS_INPUT);       // Set all pins as input
        }
        Wire.endTransmission();
    }

after which I attempt to read from it, by first addressing the GPIO register and then requesting a byte to read:

    inline uint8_t eeprog::_read()
    {
        Wire.beginTransmission(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS);
        {
            Wire.write(MCP23008_REGISTER_GPIO); // Select the GPIO register
        }
        Wire.endTransmission();

        Wire.requestFrom(MCP23008_DEVICE_I2C_ADDRESS | MCP23008_SLAVE_I2C_ADDRESS, (uint8_t)1);

        return Wire.read();
    }

Looking at my logic analyzer this is what I get:

[![I2C read from MCP23008][1]][1]

The NACK seems to indicate that the read went wrong.. actually a bit unsure what "Data read: 07" means in this context, did it read the value 7, or did it try read address 07?

Any ideas what I could be doing wrong? Am I missing something obvious from the documentation?

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

title: Wire with MCP23008 I/O expander with I2C

Answers: 1

body:
Everything is fine and nothing is wrong.
You are reading the GPIO register and its contents is 0x07.

The NACK at the end is not an error, it is a way to communicate between the Master and Slave.

When the Master reads data, the Master gives an ACK after each databyte from the Slave. The Master is not trying to tell the Slave that it was received, but rather it tells the Slave that another byte is going to be read.
After the last databyte, the Master send a NACK and after that a STOP.

Since only one byte is read, the Master sends a NACK and a STOP. The Master is telling the Slave that no more data is needed.

The I2C bus is only two wires. There are START, STOP, ACK and NACK conditions and the clock pulse can be stretched by a Slave. The possibilities are limited. For example when the Master wants to read 6 bytes and the Slave has only 1 byte. The Slave has no way to tell the Master that it has only 1 byte, and the Master will read those 6 bytes, valid or not.


body:
I recently bought a **MQ7 sensor module** like the one in the attached picture. I have read several tutorials, and they're all different. Some of them says that i need to **connect the module directly to 5v** and wait 24 hours to made it work properly, others says that i need to program **different periods (5v and 1.4v) and wait the same time to make correct meditions.** I read this [Datasheet][1], but i think that the information it has is not for the module.

If anyone knows how to setup this module i will aprecciate an answer (i want to read analog values).

Thanks in advance and sorry for my bad english.

[![Back View][2]][2]
[![Front View][3]][3]

  [1]: https://www.sparkfun.com/datasheets/Sensors/Biometric/MQ-7.pdf
  [2]: https://i.stack.imgur.com/gBWa3.jpg
  [3]: https://i.stack.imgur.com/T1lIy.jpg

title: How to calibrate the MQ7 sensor module?

Answers: 1

body:
first of all, you need to understand how these sensors work.

 1. the sensor itself is just a resistor (like a normal resistor, with 2 legs) which is constructed from materials that are affected in presence of a specific gas. the gas changes its resistance. but as it's obvious, these type of materials are not calibrated.
 2. in order to make that resistor sensitive enough, we have to warm it. so the manufacturer puts a simple coil element near the resistor in the capsule and you connect it to 5v. it warms up (it draws a lot of current) and thus, the effect of gas on the resistor becomes greater and we can measure it easily. when they say connect and let it be for 24 hours they mean warming up the resistor. I think it's a little high. I used them after a few minutes of warming up but it depends on situation and desired precision.
 3. the resistor and element, have separate pins and are completely independent. you have to connect the coil to 5v (because manufacturer made it like that) and use the resistor anyway you like. even with a ohmmeter.
 4. as we have to use Arduino, so we have to measure a resistor with the ADC of Arduino. the procedure is straightforward. you put a normal resistor in series with the sensor resistor and make a voltage divider (search that if you don't know about it. it's a fundamental thing to know in electronics).I think there should be a schematic in datasheet for it. and you measure the voltage with ADC.

and some notes :

 - you have to use A0 pin of the module if you want reading the value like the procedure above. this pin is the output of voltage divider(the sensor + blue pot on the board) and should be connected to ADC.
 - the D0 is just the output of another circuit present on board for another purpose. it's a comparator output. it's used for situations where you only need to do something (like turning emergency lights on and off) when the gas goes up from a level. you don't read anything with ADC. you just turn the pot to set a threshold (that's empirical) and digital pin get high and low according to that.
 - the voltage divider's GND and VCC are connected to GND and VCC of heating element accordingly. so you have just one pair of GND/VCC


body:
I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.

The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.

The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.

The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position.
The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.

It then repeats this sub cycle about 20 times.

After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.

It then does this whole complete cycle 20 times before stopping.

There's a momentary switch as well, which when pushed, is supposed to restart everything again.

It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.

I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.

Any ideas what I could try?

    int Relay_1 = 10;           //first Relay
    int Relay_2 = 11;           //second Relay
    int Prox_Input = 12;        //input signal from proximity sensor
    int Switch_Input = 13;      //the switch

    int Cycle_Number = 20;      //number of repeating number of "complete" cycle
    int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
    int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
    int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

    bool Button_Pushed = true ; //the state required for the button
    int i, j;

    void setup() {
      /*configurate the output relays to be begin "low"*/
      pinMode(Relay_1 , OUTPUT);
      digitalWrite(Relay_1, LOW);

      pinMode(Relay_2 , OUTPUT);
      digitalWrite(Relay_2 , LOW);
      /*===========================================================*/
      /*configurate the input switch and sensor*/
      pinMode(Prox_Input , INPUT);
      pinMode(Switch_Input , INPUT_PULLUP);
      /*===========================================================*/
      /*configurate Serial port if you want it*/
      Serial.begin(9600);
      /*===========================================================*/
    }

    void loop() {
      if (Check_Button() == Button_Pushed) { //check the button
        for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
          for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
            digitalWrite(Relay_1 , HIGH);
            delay(Delay_Sub_Cycle);
            digitalWrite(Relay_1 , LOW);
            while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
          }
          digitalWrite(Relay_2 , HIGH);
          delay(Delay_Sub_Cycle);
          digitalWrite(Relay_2 , LOW);
          delay(Delay_Cycle);
        }
      }
    }

    bool Check_Button()  {
      int Reading_1;
      int Reading_2;

      Reading_1 = digitalRead(Switch_Input);
      delay(20);
      Reading_2 = digitalRead(Switch_Input);
      if ((Reading_1 == 1) && (Reading_2 == 1))
        return true;
      else
        return false;
    }

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

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

title: Can someone check my code? My Arduino isn't doing a consistent count cycle

Answers: 1

body:
The only reason it might "jump the gun" would be this line:

>              while(digitalRead(Prox_Input) == HIGH){}          // waiting the sensor signal

I suggest you check for a *transition*, that is, make sure the proximity switch has become LOW, and then wait for it to become HIGH again. So for example, if sending HIGH to the relay should make the proximity sensor read LOW, then put a loop in to make sure it does that, before proceeding.


body:
    x = 5;
    Serial.println (x);

    if (x == 0);
        {
          //stuff in this IF keeps happening why ?
          //Iam too stupid ?
        }

title: Why is IF statement executing on itself

Answers: 1

body:
You have a rogue semi-colon.

Splitting your code up on the end of statements you get:

    1. x = 5;
    2. Serial.println (x);
    3. if (x == 0);
    4. { // stuff }

With the semi-colon after the `if` it terminates the `if` before the opening block `{`, and that block becomes a completely separate statement detached from the `if`.


body:
For a final project I'm making a word clock using three 74HC595 registers and three ULN2803A transistor arrays as led drivers, as well as a DS1307 RTC.

The program works great, except for one large problem. While chips 2 and 3 work correctly, the outputs of the first chip are always lit.
I've tried several different programs online, I've done a lot of research and I just couldn't find the answer.
[![Schematic][1]][1]
The code:

    #include <Wire.h>
    #include <Time.h>
    #include <DS1307RTC.h>

    #define BUTTON_HOUR 8
    #define BUTTON_MINUTE 7
    #define DATA 2                    // digital 2 to pin 14 on the 74HC595
    #define LATCH 3                   // digital 3 to pin 12 on the 74HC595
    #define CLOCK 4                   // digital 4 to pin 11 on the 74HC595

    // Variables will change:
    int buttonStateHOUR = 0;          // current state of the button
    int buttonStateMINUTE = 0;        // current state of the button
    int lastButtonStateHOUR = 0;      // previous state of the button
    int lastButtonStateMINUTE = 0;    // previous state of the button

    byte registerByte1 = 0;           // 0 IT IS | 1 FIVE  | 2 EIGHT | 3 QUARTER | 4 THREE  | 5 TEN | 6 MINUTES  | 7 TWENTY
    byte registerByte2 = 0;           // 0 TO    | 1 PAST  | 2 HALF | 3 FIVE    | 4 ONE   | 5 NINE | 6 TWO | 7 THREE
    byte registerByte3 = 0;           // 0 FOUR   | 1 SIX | 2 EIGHT| 3 SEVEN  | 4 TWELVE | 5 TEN | 6 ELEVEN  | 7 O'CLOCK

    tmElements_t tm;

    void setup()
    {
      // ***********************************
      Serial.begin(9600);
      while (!Serial) ; // wait for serial
      delay(200);
      Serial.println("DS1307RTC Read Test");
      Serial.println("-------------------");
      // ***********************************

      // Buttons
      pinMode(BUTTON_HOUR, INPUT);
      pinMode(BUTTON_MINUTE, INPUT);

      // Shift Register
      pinMode(LATCH, OUTPUT);
      pinMode(CLOCK, OUTPUT);
      pinMode(DATA, OUTPUT);
    }

    void loop()
    {
      // read the pushbutton input pin:
      buttonStateHOUR = digitalRead(BUTTON_HOUR);
      buttonStateMINUTE  = digitalRead(BUTTON_MINUTE);

      // Detect HOUR Button
      if (buttonStateHOUR != lastButtonStateHOUR) {
        if (buttonStateHOUR == HIGH) {
          addTime(1,0);
        }
        lastButtonStateHOUR = buttonStateHOUR;
      }
      // Detect MINUTE Button
      if (buttonStateMINUTE != lastButtonStateMINUTE) {
        if (buttonStateMINUTE == HIGH) {
          addTime(0,1);
        }
        lastButtonStateMINUTE = buttonStateMINUTE;
      }

      // Generate time and shiftOut
      timeToBytes();
      updateShiftRegisters();
      printTime();
    }

    void timeToBytes()
    {
      if (RTC.read(tm)) {
        int deutschHour = shortHour(tm.Hour);
        int halb = 0;
        registerByte1 = 0;
        registerByte2 = 0;
        registerByte3 = 0;
        bitSet(registerByte1,0);    // "ES IST"

        if (tm.Minute >= 0 && tm.Minute <= 5) {
          bitSet(registerByte1,1);    // "FIVE"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,1);    // "PAST"
        } else if (tm.Minute >= 10 && tm.Minute <= 19) {
          bitSet(registerByte1,5);    // "TEN"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,1);    // "PAST"
        } else if (tm.Minute >= 20 && tm.Minute <= 24) {
          bitSet(registerByte1,7);    // "TWENTY"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,1);    // "PAST"
        } else if (tm.Minute >= 25 && tm.Minute <= 29) {
          bitSet(registerByte1,7);    // "TWENTY"
          bitSet(registerByte1,1);    // "FIVE"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,1);    // "PAST"
          halb = 1;
        } else if (tm.Minute >= 30 && tm.Minute <= 34) {
          bitSet(registerByte2,2);    // "HALF"
          bitSet(registerByte2,1);    // "PAST"
          halb = 1;
        } else if (tm.Minute >= 35 && tm.Minute <= 39) {
          bitSet(registerByte1,7);    // "TWENTY"
          bitSet(registerByte1,1);    // "FIVE"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,0);    // "TO"
          halb = 1;
        } else if (tm.Minute >= 40 && tm.Minute <= 49)  {
          bitSet(registerByte1,3);    // "QUARTER"
          bitSet(registerByte2,0);    // "TO"
          halb = 1;
        } else if (tm.Minute >= 50 && tm.Minute <= 54) {
          bitSet(registerByte1,5);    // "TEN"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,0);    // "TO"
          halb = 1;
        } else if (tm.Minute >= 55 && tm.Minute <= 59) {
          bitSet(registerByte1,1);    // "FIVE"
          bitSet(registerByte1,6);    // "MINUTES"
          bitSet(registerByte2,0);    // "TO"
          halb = 1;
        }

        deutschHour = shortHour( deutschHour + halb);
        if ( deutschHour == 1 ) {
          bitSet(registerByte2,4);    // "ONE"
        } else if ( deutschHour == 2 ) {
          bitSet(registerByte2,6);    // "TWO"
        } else if ( deutschHour == 3 ) {
          bitSet(registerByte2,7);    // "THREE"
        } else if ( deutschHour == 4 ) {
          bitSet(registerByte3,0);    // "FOUR"
        } else if ( deutschHour == 5 ) {
          bitSet(registerByte2,3);    // "FIVE"
        } else if ( deutschHour == 6 ) {
          bitSet(registerByte3,1);    // "SIX"
        } else if ( deutschHour == 7 ) {
          bitSet(registerByte3,3);    // "SEVEN"
        } else if ( deutschHour == 8 ) {
          bitSet(registerByte3,2);    // "EIGHT"
        } else if ( deutschHour == 9 ) {
          bitSet(registerByte2,5);    // "NINE"
        } else if ( deutschHour == 10 ) {
          bitSet(registerByte3,5);    // "TEN"
        } else if ( deutschHour == 11 ) {
          bitSet(registerByte3,6);    // "ELEVEN"
        } else if ( deutschHour == 12 ) {
          bitSet(registerByte3,4);    // "TWELVE"
        }
        bitSet(registerByte3,7);    // "UHR"
      }
    }

    void updateShiftRegisters()
    {
       digitalWrite(LATCH, LOW);
       shiftOut(DATA, CLOCK, MSBFIRST, registerByte3);
       shiftOut(DATA, CLOCK, MSBFIRST, registerByte2);
       shiftOut(DATA, CLOCK, MSBFIRST, registerByte1);
       digitalWrite(LATCH, HIGH);
    }

    void addTime(int addHour, int addMinute)
    {
      // get time from RTC
      if (RTC.read(tm)) {

        if (addHour > 0) {
          tm.Hour = tm.Hour + addHour;
          if (tm.Hour > 12) {
            tm.Hour = tm.Hour - 12;
          }
        }

        if (addMinute > 0) {
          tm.Minute = tm.Minute + addMinute;
          if (tm.Minute > 59) {
            tm.Minute = tm.Minute - 60;
            addTime(1,0);
          }
        }

        tm.Second = 0;
        RTC.write(tm);
      }
    }

    int shortHour(int tempHour)
    {
      tempHour = tempHour % 12;
      return tempHour == 0 ? 12 : tempHour;
    }

    void printTime() {

      if (RTC.read(tm)) {
        Serial.print("Ok, Time = ");
        print2digits(tm.Hour);
        Serial.write(':');
        print2digits(tm.Minute);
        Serial.write(':');
        print2digits(tm.Second);
        Serial.print(", Date (D/M/Y) = ");
        Serial.print(tm.Day);
        Serial.write('/');
        Serial.print(tm.Month);
        Serial.write('/');
        Serial.print(tmYearToCalendar(tm.Year));
        Serial.println();
        Serial.print("registerByte3 = ");
        Serial.print(registerByte3, BIN);
        Serial.println();
        Serial.print("registerByte2 = ");
        Serial.print(registerByte2, BIN);
        Serial.println();
        Serial.print("registerByte1 = ");
        Serial.print(registerByte1, BIN);
        Serial.println();
      } else {
        if (RTC.chipPresent()) {
          Serial.println("The DS1307 is stopped.  Please run the SetTime");
          Serial.println("example to initialize the time and begin running.");
          Serial.println();
        } else {
          Serial.println("DS1307 read error!  Please check the circuitry.");
          Serial.println();
        }
        delay(9000);
      }
      delay(1000);
    }

    void print2digits(int number) {
      if (number >= 0 && number < 10) {
        Serial.write('0');
      }
      Serial.print(number);
    }

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

title: Problem using 74HC595 with ULN2803A as LED driver

Answers: 0


body:
I have been trying to use the WifiNINA library to access the JSON output from the [following API][1] using the WifiNINA library and the Arduino Wifi Rev2.

This is the code that I have been using (it is an **edited** example form the library):

    /*
      Web client

     This sketch connects to a website (https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo)
     using the WiFi module.

     This example is written for a network using WPA encryption. For
     WEP or WPA, change the Wifi.begin() call accordingly.

     This example is written for a network using WPA encryption. For
     WEP or WPA, change the Wifi.begin() call accordingly.

     Circuit:
     * Board with NINA module (Arduino MKR WiFi 1010, MKR VIDOR 4000 and UNO WiFi Rev.2)

     created 13 July 2010
     by dlf (Metodo2 srl)
     modified 31 May 2012
     by Tom Igoe
     */

    #include <SPI.h>
    #include <WiFiNINA.h>

    #include "arduino_secrets.h"
    ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
    char ssid[] = SECRET_SSID;        // your network SSID (name)
    char pass[] = SECRET_PASS;    // your network password (use for WPA, or use as key for WEP)
    int keyIndex = 0;            // your network key Index number (needed only for WEP)

    int status = WL_IDLE_STATUS;
    // if you don't want to use DNS (and reduce your sketch size)
    // use the numeric IP instead of the name for the server:
    //IPAddress server(74,125,232,128);  // numeric IP for Google (no DNS)
    char server[] = "www.alphavantage.co";    // name address for Google (using DNS)

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    WiFiClient client;

    void setup() {
      //Initialize serial and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // check for the WiFi module:
      if (WiFi.status() == WL_NO_MODULE) {
        Serial.println("Communication with WiFi module failed!");
        // don't continue
        while (true);
      }

      String fv = WiFi.firmwareVersion();
      if (fv < "1.0.0") {
        Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        Serial.print("Attempting to connect to SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);

        // wait 10 seconds for connection:
        delay(10000);
      }
      Serial.println("Connected to wifi");
      printWifiStatus();

      Serial.println("\nStarting connection to server...");
      // if you get a connection, report back via serial:
      if (client.connect(server, 80)) {
        Serial.println("connected to server");
        // Make a HTTP request:
        client.println("GET /query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo HTTP/1.1");
        client.println("Host: https://www.alphavantage.co");
        client.println("Connection: close");
        client.println();
      }
    }

    void loop() {
      // if there are incoming bytes available
      // from the server, read them and print them:
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }

      // if the server's disconnected, stop the client:
      if (!client.connected()) {
        Serial.println();
        Serial.println("disconnecting from server.");
        client.stop();

        // do nothing forevermore:
        while (true);
      }
    }

    void printWifiStatus() {
      // print the SSID of the network you're attached to:
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your board's IP address:
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength:
      long rssi = WiFi.RSSI();
      Serial.print("signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

However, when I run the library, all that the serial monitor returns is:

    Attempting to connect to SSID: HIDDEN
    Connected to wifi
    SSID: HIDDEN
    IP Address: HIDDEN
    signal strength (RSSI):-40 dBm

    Starting connection to server...
    connected to server
    HTTP/1.1 301 Moved Permanently
    Connection: close
    Server: gunicorn/19.7.0
    Date: Sun, 07 Apr 2019 15:02:16 GMT
    Transfer-Encoding: chunked
    Location: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&outputsize=full&datatype=json&apikey=8UV48KKJJM1JW700
    Content-Type: text/html; charset=utf-8
    Via: 1.1 vegur

    0

    disconnecting from server.

I would like the code to return the string from the link. The output should like this (instead of just the 0). I had to shorten the example output below because of size restraints, but it should be the full webpage.

    {
        "Meta Data": {
            "1. Information": "Intraday (5min) open, high, low, close prices and volume",
            "2. Symbol": "MSFT",
            "3. Last Refreshed": "2019-04-05 16:00:00",
            "4. Interval": "5min",
            "5. Output Size": "Compact",
            "6. Time Zone": "US/Eastern"
        },
        "Time Series (5min)": {
            "2019-04-05 16:00:00": {
                "1. open": "119.8100",
                "2. high": "119.9100",
                "3. low": "119.7350",
                "4. close": "119.8800",
                "5. volume": "728814"
            },
            "2019-04-05 15:55:00": {
                "1. open": "119.9200",
                "2. high": "119.9200",
                "3. low": "119.7800",
                "4. close": "119.8000",
                "5. volume": "307126"
            },
            "2019-04-05 15:50:00": {
                "1. open": "119.9300",
                "2. high": "119.9300",
                "3. low": "119.8800",
                "4. close": "119.9200",
                "5. volume": "235238"
            }
        }
    }

  [1]: https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo

title: Arduino WiFi Rev2 JSON String

Answers: 2

body:
The target site uses HTTPS. If you connect to port 80, it redirects to HTTPS on port 443.

Use the `WiFiSSLClient` of the library. See the WiFiSSLClient example. Basically it is same as the example you used. There are two differences. It uses `WiFiSSLClient` instead of `WiFiClient` and connects to standard https port 443.

body:
It's not that the API is incompatible with the Arduino, it's that the Arduino Firmware update tool used to add the required SSL certificate to the wifi module fails to do so because the SSL certificate for www.alphavantage.co does not exist at their domain.

This can be verified by:

openssl s_client -showcerts -connect www.alphavantage.co:443


body: I managed to update the library but getting error "Error Downloading http://downloads.arduino.cc/packages/packages_index.json" when updating the *Board Manager*. I switched the proxy to no proxy instead of automatic. Anyone can help me?

Answers: 2

body:
The URL is wrong, and should read:

    https://downloads.arduino.cc/packages/package_index.json

Note that "package_index" is in the singular, not the plural.

Check what you have in the "Additional Boards Manager URLs:" section of Preferences.

body:
I had the same issue and the fix that worked for me is to directing the jvm to use the Windows Certificate Store instead of the ancient cacerts file that comes with java 1.8. This may also help people behind a Cisco Umbrella filter.

One does this by adding the following lines to "C:\Program Files (x86)\Arduino\arduino.l4j.ini" (note, you will need to open a text editor as an administrator, then open the file in question, in order to edit it):

    -Djavax.net.ssl.trustStore=NUL
    -Djavax.net.ssl.trustStoreType=Windows-ROOT

[I found this answer here][1]

  [1]: http://You can also try directing the jvm to use the Windows Certificate Store instead of the ancient cacerts file that comes with java 1.8. This may also help people behind a Cisco Umbrella filter. One does this by adding the following lines to "C:\Program Files (x86)\Arduino\arduino.l4j.ini" (note, you will need to open a text editor as an administrator, then open the file in question, in order to edit it): -Djavax.net.ssl.trustStore=NUL -Djavax.net.ssl.trustStoreType=Windows-ROOT


body:
I am currently working on a project where I need a stepping motor and a servo running at the same time, the servo turns fine and the speed is ok, but the stepping motors speed is very slow and as a result it is loud. I tried the code for the stepping motor on its own and it runs faster, but when it is ran with the servo it is slow. I have follwed a few tutorials to get this to the stage it is at currently, I have removed any delays that i could find which did help a little, but it is still not enough.

The servo is powered from the arduino and the stepping motor is powered by a 12v plug. I am just not sure if there is something within this code that is causing it to slow down? Thank you for you time! The code that it is running slow from is here:
<!-- language-all: lang-cpp -->

    #include <Servo.h>

    Servo myservo;

    // Configurable Variables
    int MaxServoTurn = 20;

    // Spooky Variables
    int pos = 0;
    int customDelay;
    int customDelayMapped;
    const int pin_LED = 10;
    const int pin_switch = 8;
    const int stepPin = 3;
    const int dirPin = 4;
    boolean oldSwitchState = LOW;
    boolean newSwitchState1 = LOW;
    boolean newSwitchState2 = LOW;
    boolean newSwitchState3 = LOW;
    unsigned long timeNow = 0;
    unsigned long timePrev = 0;
    unsigned int timeWait = 100;
    boolean flashingLEDisON = false;
    boolean LEDstatus = LOW;
    boolean keyPressed = false;
    boolean buttonToggle = false;

    // Setup only, call functions in here
    void setup() {
      myservo.attach(9);
      //Sets the two pins as Outputs
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
      //Enables the motor to move in a particular direction
      digitalWrite(dirPin, HIGH);
      pinMode(pin_LED, OUTPUT);
      digitalWrite(pin_LED, LOW);
      pinMode(pin_switch, INPUT);
    }

    // This is the main controller for the application
    void loop() {
      for (pos = 0; pos <= MaxServoTurn; pos += 1) {
        buttonLoop();
        if (buttonToggle == true) {
          myservo.write(pos);
          setupPotentiometer();
        }
      }
      for (pos = MaxServoTurn; pos >= 0; pos -= 1) {
        buttonLoop();
        if (buttonToggle == true) {
          myservo.write(pos);
          setupPotentiometer();
        }
      }
    }

    void buttonLoop() {
      newSwitchState1 = digitalRead(pin_switch);
      newSwitchState2 = digitalRead(pin_switch);

      newSwitchState3 = digitalRead(pin_switch);

      if (  (newSwitchState1 == newSwitchState2) && (newSwitchState1 == newSwitchState3) )
      {
        if ( newSwitchState1 != oldSwitchState )
        {
          if ( newSwitchState1 == HIGH ) {
            keyPressed = true;
            buttonToggle = true;
          } else {
            keyPressed =  false;
            buttonToggle = false;
          }
          oldSwitchState = newSwitchState1;
        }
      }

      if ( keyPressed )
      {
        // turn on or turn off the blinking LED
        if ( flashingLEDisON == false)
        {
          flashingLEDisON = true;
        }
        else
        {
          flashingLEDisON = false;
          // the LED may be on so to be safe we turn it off. If you wished you could check LEDstatus
          LEDstatus = LOW;  digitalWrite(pin_LED, LEDstatus);
        }
        keyPressed = false;
      }

      // if the blinking LED is on. See if it is time to blink it
      if ( flashingLEDisON == true )
      {
        timeNow = millis();
        if (timeNow - timePrev >= timeWait )
        {
          timePrev = timeNow;
          if (LEDstatus == LOW) {
            LEDstatus = HIGH;
          } else {
            LEDstatus = LOW;
          }
          digitalWrite(pin_LED, LEDstatus);
        }
      }
    }

    void setupPotentiometer() {
      customDelayMapped = speedUp(); // Gets custom delay values from the custom speedUp function
      // Makes pules with custom delay, depending on the Potentiometer, from which the speed of the motor depends
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(customDelayMapped);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(customDelayMapped);
    }

    // Function for reading the Potentiometer
    int speedUp() {
      int customDelay = analogRead(A0); // Reads the potentiometer
      int newCustom = map(customDelay, 0, 1023, 300, 4000); // Convrests the read values of the potentiometer from 0 to 1023 into desireded delay values (300 to 4000)
      return newCustom;
    }

title: Slow speed with stepping motor

Answers: 2

body:
A stepper motor requires that you send pulsed control signals to it for each step. If you want it to run at a given number of steps/second, you have to send the controlling pulses at the correct time intervals.

If you have delays in your code, it will slow down the timing of the control pulses, and slow down your steppers. You need to rewrite your code to use millis() to calculate the timing of your control signals instead of using `delay()` or `delayMicroseconds()`

body:
I had a project where I needed to run two steppers at the same time as they were moving a heavy load and were moving the same piece.

While a servo is going to move the desired spot, a stepper will not.

In the process of setting up the stepper you designated steps per rev and amount of steps to take at a time.

The stepper is only going to move the "amount of steps" at a time for each run of the code. I ran into a similar  problem and I had to put in a 2ms delay after the servo run command to make the motors run smoother and faster, other wise it sounded like a bunch of gears gnashing and skipping.  These steppers were facing each other that is why they move opposite directions.
<!-- language-all: lang-cpp -->

    if (down==true){
      TLstep.step(-step1);
      TRstep.step(step1);
      delay(2);
    }

I know it been a year since this was looked at. Hope you got your issue figured out.