text:
Arduino pulls i2c bus down
I am building an airplane. As a controller I am using a Raspberry pi 4. There are 3 sensors (MPU6050, QMC5883L, BME280) and arduino pro mini connected to the raspberry via i2c. When sending requests to the arduino it pulls the bus to 0 and shuts down(?).

First screenshot. On the first search for all devices on the bus, the arduino responds and shuts down, but does not pull the bus to 0. On the second search It responds and pulls the bus to 0.

Second screenshot. Rebooting the arduino, the SDA line goes up. Repeated runs of the search leads to what is shown in the first screenshot.

Third screenshot. The arduino generates a PWM signal that is interrupted after a request to i2c.

As a test request I use the i2cdetect command on the Raspberry.
Raspberry is connected to the sensor bus through a level converter, because the level of signals from Raspberry is 3.3V, and sensors accept 5 volt logic.
There is no bus pull-up to the upper level, it is on the schematic of all sensors used (will it be enough?).
The arduino has a simple slave i2c device code, writing to registers the value arrived and output it to other elements (servo drives, motor controller, stepper motor drivers). The Arduino acts as a port expander because the Raspberry has only 2 buses and too few outputs for all the necessary devices
Why is the bus falling and how can I fix it?
arduino code
    #include <Wire.h>
    #include <Servo.h>
    #include <Stepper.h>

    uint16_t servoAngle1 = 90;
    uint16_t servoAngle2 = 90;
    uint16_t servoAngle3 = 90;
    uint16_t servoAngle4 = 90;

    bool zoomIn = false;
    bool zoomOut = false;

    bool focusIn = false;
    bool focusOut = false;

    Servo servo1;
    Servo servo2;
    Servo servo3;
    Servo servo4;

    Servo ESC;

    Stepper zoomMotor(100, 2, 4, 7, 8);
    Stepper focusMotor(100, 10, 11, 12, 13);

    void setup() {
      Wire.begin(0x23);
      Wire.onReceive(receiveEvent);

      servo1.attach(3);
      servo2.attach(5);
      servo3.attach(6);
      servo4.attach(9);
      ESC.attach(11, 1000, 2000);
    }

    void loop() {
      servo1.write(servoAngle1);
      servo2.write(servoAngle2);
      servo3.write(servoAngle3);
      servo4.write(servoAngle4);
      ESC.write(0);
      if (zoomIn) {
        zoomMotor.step(100);
        zoomIn = false;
      }
      if (zoomOut) {
        zoomMotor.step(-100);
        zoomOut = false;
      }

      if (focusIn) {
        focusMotor.step(100);
        focusIn = false;
      }
      if (focusOut) {
        focusMotor.step(-100);
        focusOut = false;
      }
    }

    void receiveEvent(int howMany) {
      if (howMany == 2) {
        uint8_t action = Wire.read();
        uint8_t value = Wire.read();

        if (action == 1) { servoAngle1 = value; }
        if (action == 2) { servoAngle2 = value; }
        if (action == 3) { servoAngle3 = value; }
        if (action == 4) { servoAngle4 = value; }

        if (action == 10) {
          if (value == 1) { zoomIn = true; }
          if (value == 2) { zoomOut = true; }
        }

        if (action == 11) {
          if (value == 1) { focusIn = true; }
          if (value == 2) { focusOut = true; }
        }
      } else {
        while (true) {
          Wire.read();
        }
      }
    }

Screenshot 1

Screenshot 2

Screenshot 3

and wiring diagram

please add a clear, answerable question to your post ... also add the code listing

The bus needs a pull-up.

That logic level shifter must be bidirectional. If it has markings on it like TX/RX then it is unlikely to be bidirectional. There should be pullup resistors (say 4.7k) on the low and high voltage sides of the I2C bus. If at least one module on each side of the level shifter has these then that should be enough. The module mpu6050 (and maybe others also) has 3.3 volt logic and should be on the Raspberry Pi side of the level shifter.

added code listing.

The BME280 is apparently a 3.3V device, so I don't know why you have it on the 5V part of the circuit.

The Pro Mini can also run at 3.3V - you are making it hard for yourself with the logic level converter.

From your newly posted code. How is it going to break out of this infinite loop ?  else { while (true) { Wire.read(); } }

@NickGammon How do I power it from 3.3V? Does it have no 3.3V pin or can 3.3V be supplied to the VCC pin too?

You have got to find and understand the schematics of the those modules you are using. Here https://www.waveshare.com/w/upload/4/42/BME280-Environmental-Sensor-Schematic.pdf for example is a BME280 module. The chip itself is 3.3v but the module has been designed for 5v operation with a built in level shifter. If this is the one you are using then, in this case, it is correct to connect it to the 5v side. What about the coding error that has been pointed out in my previous comment. Would that not cause the symptoms you have reported ?

You show the Raspberry Pi as having 3.3V on SDA and SCL - where does that come from? You show your devices like the BME280 with a 3.3V supply. Why are you asking where 3.3V comes from? If you don't want to do that then look at 6v6gt's comment. You need a bidirectional level shifter, otherwise I2C won't work.

The global variables which are used in the loop and updated in receiveEvent() should be declared as volatile because the call to this routine is via an interrupt. You should show also the code used on the I2C master.

For I2C to work there needs to be pull-ups on SDA and SCL somewhere (not one for each device). Typically 4.7k resistors or thereabouts would be used.
Also you need a bi-directional voltage level translator. An example schematic is:

Image credit: Sparkfun: Bi-Directional Logic Level Converter Hookup Guide
This is because I2C devices actively pull SDA and SCL low, however they rely on the pull-up resistors to pull them high. Also this won't work unless the voltage level shifter is bi-directional.
For more information see the Philips Application Note AN97055 - Bi-directional level shifter for I²C-bus and other systems.
If you use the level shifter you need pull-up resistors on both the 3.3V part and the 5V part of the circuit (shown as Rp below).


text:
How to turn off or stop Access Point network in ESP8266?
I've created a code for ESP8266 12E with Arduino IDE, in which it'll operate as "Station Mode" or "Access Point Mode" on Wifi, depending on the situation. Everything works fine except when device was configured as Access Point, even when I turn off device and then turn on again and force the Wifi initialization as "Station Mode", the Access Point network stays active.
Example: Let's suppose that I turned on the ESP8266 and initialized the Wifi as Access Point, and named the wifi network as "MY_WIFI_TEST". Let's assume now that I turned off the ESP8266 and forced it to turn on as "Station Mode". The ESP8266 typically connects to my network (the network of my gateway router 192.168.1.1), but keeps the network "MY_WIFI_TEST" active (the prior network as access point). You can not connect to this network, but it remains active.
How can I turn off or stop Access Point network?
My test code:
    #include <ESP8266WiFi.h>

    bool access_point_init(){
        // Access Point Mode

       Serial.begin(115200);
       IPAddress ip(192,168,1,254);
       IPAddress gateway(192,168,1,1);
       IPAddress subnet(255,255,255,0);
       char* ssid     = "myssidname";
       char* password = "12345678";

       WiFi.softAPConfig(ip, gateway, subnet);
       bool ret = WiFi.softAP(ssid, password);

       return ret;
    }

    void wifi_station_init(){

        // Station Mode
        Serial.begin(115200);
       Serial.printf("\n");

       WiFi.begin(net_ssid, net_pwd_ssid);

       IPAddress ip(192,168,1,10);
       IPAddress gateway(192,168,1,1);
       IPAddress subnet(255,255,255,0);

        WiFi.config(ip, gateway, subnet);

       k = 0;
       while ((WiFi.status() != WL_CONNECTED) && (k < 80)){
          delay(250);
          Serial.print('.');
          k++;
       }

       Serial.printf("\n");
       Serial.printf("IP address: ");
       Serial.println(WiFi.localIP());
    }

    void setup()
    {
        bool my_condition = false;
        //...
        // my_condition = myLoadFunction();
        //...

       if (my_condition) {
            access_point_init();
       } else {
          wifi_station_init();
       }
    }

I've already solved, by using a function of the library Wifi, specific for the connections in "Access Point" mode:
WiFi.softAPdisconnect (true);

Reference:
softapdisconnect

I fixed this by adding below command before starting the accesspoint.
 WiFi.mode(WIFI_AP);

I was trying to turn off the softAP in the new Arduino Uno R4 Wifi so I could rename it and restart it. I put a changing sensor reading in AP name so I can see the value of it by just doing a network scan without actually connecting to it.
The wifi.h lib for UNO R4 doesn't implement SOFTAPDISCONNECT. In the example AP_SIMPLEWEB server I found adding the following function shuts down the AP and allows restarting with a different name.
void endAccessPoint() {
  using namespace std;
  string res = "";
  modem.begin();
  modem.write(string(PROMPT(_DISCONNECTSOFTAP)),res,"%s%d\r\n" ,CMD_WRITE(_DISCONNECTSOFTAP),1);
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How arduino boards eliminate the need to press buttons to flash?
I've come across many Arduino shields for various boards like the Uno, ESP8266, and ESP32 which sometimes have a button for flashing and other times they do not because the flashing is automatic.
When I upload a binary sketch to ESP32 directly through a separate Serial to USB converter, I have to make the button connections and press the buttons manually for the uploading process to work.
The manual button pressing flashing process for the ESP32 goes like this:

Hold the Reset button (IO0 to ground)
Hold the Flash button (EN to ground)
Release the Reset button (IO0 to float)
Release the Flash button (EN to 3.3v)
The board is now in flashing mode
Press "Upload" in Arduino IDE
Wait until the IDE log shows "Connecting..."
Wait until the sketch is fully uploaded
Press the Reset button (IO0 to ground then float)

Arduino boards like the WeMos Lolin32 board eliminate the button pressing process completely during the flashing process.
QUESTION: Which part of the hardware on the Lolin32 board makes the flashing process autonomous?
Here's the manual uploading schematic:
And here's the WeMos Lolin32 board, that eliminates the button pressing process completely when I upload a sketch:
I believe the answer will also apply to any other auto-flashing board out there.

I'm not familiar with this board, but according to this schematic:
https://wiki.wemos.cc/_media/products:lolin32:sch_lolin32_v1.0.0.pdf
U4 (one of the small 6-leg components) connects to IO0 (pin 25) on the ESP-32. The transistor inside U4 combines the RTS and DTR signals (from U6 USB-Serial converter IC, which will be the large IC marked SIL2104) to put IO0 in the correct state for flashing. The RTS and DTR signals can be set by the host (the computer doing the flashing).
Apologies for the lack of depth, but the short answer is components U4 and U6 on the board work together on the command from the host computer to put IO0 in the correct state for flashing.

Now I know a little bit more about the components on Arduino shields! Thank you for looking into this for me.

From this, I went on to learn more about the U6 component (SIL 2104 F01BP 1711+)  and find out why it has 4 GPIO pins: https://www.silabs.com/documents/public/data-sheets/cp2104.pdf

@DemSec, i think that it has 4 GPIO pins because the manufacturer has decided that it would make the device more useful

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
RTL8170 Web Server - client unable to connect
RTL8170 is a new module, which is in many ways better than the old ESP8266 module. We are able to flash this module with Arduino using an Ameba Writer, and it should be able to support any code that is supported by the ESP (with some adjustments). It has been officially supported by Realtek's environment but it does not use all the GPIO (only 2). Luckily, pvvx developed an environment for Arduino IDE, which we can install and use through this tutorial: https://hackaday.io/project/19163/logs
I have uploaded a modified SimpleWebServerWiFi sketch from Ameba RTL8170 examples by both trying the official Realtek and pvvx's environments, and using LEDs to troubleshoot (I don't have an SPI/I2C LCD or a Serial-to-USB) I found the module being able to connect to my Samsung's hotspot but unable to communicate with the module because server.available() never turns true. When my module connects to my Samsung Note 4's hotspot, I see its IP (192.168.43.123) and fail to connect to it via a browser (on the phone or with a Windows laptop). Android port scanning apps indicate that the target IP address of the module has no open ports. Code below.
Update2: I've made adjustments to the code according to suggestions, but it still didn't respond. Updated code below:
   /*-----------------------------------------------------------------|
  |  Build using pvvx's enviroment: https://github.com/pvvx/RtlDuino  |
  |  Tutorial: https://hackaday.io/project/19163/logs                 |
  |=================================================================*/

#include <WiFi.h>

char ssid[] = "WiFi_SSID";      //  your network SSID (name)
char pass[] = "password";   // your network password
int keyIndex = 0;   // your network key Index number (needed only for WEP)
String currentLine = "";   // make a String to hold incoming data from the client

int status = WL_IDLE_STATUS;
WiFiServer server(80);

void setup() {
  pinMode(1,OUTPUT);

  //Serial.begin(38400);      // initialize serial communication
  pinMode(LED_BUILTIN, OUTPUT);      // set the LED pin mode
  // check for the presence of the shield:
  if (WiFi.status() == WL_NO_SHIELD) {
    //Serial.println("WiFi shield not present");
    while (true); // don't continue
  }
  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    //Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to Network named: ");
    //Serial.println(ssid);         // print the network name (SSID);

    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);
    // wait 0.2 seconds for connection:
    delay(200);
  }

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

}

void loop() {

  WiFiClient 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
    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
        //Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {

            // 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-Length: 88");
            client.println("Content-Type: text/html");
            client.println("Connection: Closed");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click here turn the BUILTIN_LED on
");
            client.print("Click here turn the BUILTIN_LED off
");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            //break;
          } else {    // if you got a newline, then clear currentLine:
            //digitalWrite(1,HIGH); // Doesn't turn ON
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          //digitalWrite(1,HIGH); // Turns ON
          currentLine += c;      // add it to the end of the currentLine
        }
        //digitalWrite(1,HIGH); // Turns ON
        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    //digitalWrite(1,HIGH); // Turns ON
    // close the connection:
    client.stop();
  }
}

Update 1:
I am still unable to fix the code. If no one can fix this code, please feel free to provide a totally new code.
P.S.: If this question keeps stagnating, I'll remove it and recreate it.
Any help is appreciated. Thank you!

Inside the while loop, where you give the link to click you have a break that prevents the handling of the answer from the client.
I would reconsider the use of that break and structure the code to not use it at all.

How would I correctly rewrite this code?

Could you please give a code snippet example? Thanks!

If you must use String, get its declaration out of loop(). You're only fragmenting your heap and reducing available RAM. Instead, declare it in the file scope and reserve sufficient space for a request line with the reserve() method in your setup().
Though response headers are supposed to be case-insensitive, it's still a good idea to follow the 'standard', spaces and all, like this for instance:
HTTP/1.1 200 OK
Content-Length: 88
Content-Type: text/html
Connection: Closed

Try sending all the fields above, especially the content length. And get rid of the break like mico said. There's no way your builtin LED will turn on or off if you keep breaking right after you respond to the client.

With these adjustments to the code, it still didn't respond

(Updated code above)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: Запорожец Александр


text:
Unexpected Delay Between For Loops
I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:
int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < sizeof(leds); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < sizeof(leds); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i; i > 0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?

Please include the FULL code. Yes, including the setup even though it is not really relevant for you.

Alright, I edited it. Does that help?

The cause it that your 3rd led (2nd element in the array) is repeated twice.
Try this instead:
int leds[3] = {13, 12, 11};

void setup() {
  for (int i = 0; i < 3; i++) {
    pinMode(leds[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < 2; i++) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
  for (int i = 2; i > 0; i--) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
}

Thank you! I thought that I wouldn't have to decrement the length of the array, guess I was wrong.

The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.
Apparently that sentence is supposed to mean that the long delay is due to i being one too large, coming out of the first loop and entering the second one.  Indeed, i is too large, but that's because each element of the array is a 2-byte int, so that instead of for (int i = 0; i < sizeof(leds); i ++) being equivalent to for (int i = 0; i < 3; i ++), it is equivalent to for (int i = 0; i < 6; i ++).
Thus, one second goes by with an extra 4 occurrences of delay(250); in the first loop, and another one second with 4 extra occurrences of delay(250); in the other loop.
To correct the problem, write sizeof leds/sizeof leds[0] instead of sizeof(leds), and write for (--i; i > 0; i--) instead of for (i; i > 0; i --).

The problem is on "for loops" condition,
Try this:
int leds[] = {13, 12, 11};
int i;

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

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

void loop() {
    for (i = 0; i < (sizeof(leds)/sizeof(leds[0]); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i=((sizeof(leds)/sizeof(leds[0])-1); i>=0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

This is not true. It depends on the persons intention.

Well my friend, the "intention" is to blink a LED. (1) You turn on a LED, (2) put it on hold by using delay, (3) You turn the LED off, (4) loops, the LED is turned on again. Well, if by "blinking" you mean its turn off for less than 10 clocks instruction, I accept.

You turn it off then change leds so there is a delay anyways.

ah you are right. Sorry my bad.

You mean sizeof(leds)/sizeof(leds[0]).

wow thanks, another mistake. forget about the byte size

Still wrong. Why don't you just const int LED_COUNT = 3;?

well, maybe its personal preference to prepare "ifs..", maybe reducing or increasing the number LED. May i know why it still wrong?

Because 1) you forgot to divide the first sizeof, 2) sizeof(int) is 2 on the Uno, not 8, 3) using an explicit integer instead of sizeof(leds[0]) makes the code non portable to, say, an Arduino Due.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
A SoftwareSerial library for SAMD boards
So I've got three boards that I'm using to test this (modified) code:
int sensor1Pin = A0;
int sensor2Pin = A1;
int sensor3Pin = A2;

float sensors[] = {0,0,0};

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

void loop(){

sensors[0] = analogRead(sensor1Pin);
sensors[1] = analogRead(sensor2Pin);
sensors[2] = analogRead(sensor3Pin);

Serial.print(sensors[0]);
Serial.print(",");
Serial.print(sensors[1]);
Serial.print(",");
Serial.println(sensors[1]);
}

An Uno, a Feather M0, and an MKR1000.
The code will only work on the Uno because it's AVR-based whereas the other two boards are SAMD. When running on a feather, you get this error:
/home/ghylama/Arduino/libraries/SoftwareSerial_master/SoftwareSerial.cpp:260:2: error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
     #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors

However, the resolution of the Uno is too low for my purposes (its DAC has a resolution of 10, whereas I need a resolution of 12, minimum). Are there any libraries/workarounds that I can use for this purpose?
I've tried SoftwareSerial, NeoSWSerial, and this one.

Sorry I'm confused, what exactly is the question? How to add Serial (/UART) ports to your Feather M0? Or about the DAC? You are using analogRead here though, which uses the ADC.

What has serial to do with DAC (ADC?) resolution?

Sorry if my wording was unclear but I've been at this for a while now so I've got tunnel vision.
Running this code on a feather gives this error:
Arduino/libraries/SoftwareSerial_master/SoftwareSerial.cpp:260:2:error: #error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
#error This version of SoftwareSerial supports only 20, 16 and 8MHz processors
Thing is, I can run this on an Uno without issues but I want it on a feather. The DAC has nothing to do with serial but that is my constraint. I need a library that does the same job as SoftwareSerial but for M0.

Why do you need software serial?  An ARM part will typically have multiple hardware serial ports.

@gre_gor Serial has nothing to do with that. My problem is that I am trying to get the SoftwareSerial library to run on devices it was not designed for. I need it to run on a device with a higher DAC resolution (Duo, Zero, Feather).

@ChrisStratton I am trying to save data from three sensors to an excel sheet. I wanted to do this by using Processing + Arduino IDE with the code from this link: http://www.hackerscapes.com/2014/11/how-to-save-data-from-arduino-to-a-csv-file-using-processing/
Is there a better way?

That has nothing to do with software serial, any serial implementation should work.  Software serial is a hack to deal with the fact that the classic Arduino only has 1 port.

@ChrisStratton It's there in the original Arduino code, line 27. Seemed pretty important so I left it in. So that example would work without it?

No, it has nothing to do with the algorithm, and everything to do with the limitations of the ATmega328p.  Which you are not using.  If you're going to run programs you don't understand, and argue with the people who explain them to you, then you need to stick to doing things exactly as described, without trying to run them on alternate hardware.

@ChrisStratton I'm not arguing, I just want to understand what is seemingly obvious to everyone else. Sorry if it came off that way. Now that you explained what software serial is, i get it. So since the only use for that library is as a fix for a limitation, i'm removing that line.

I will restate the problem as I have understood it: You want more Serial objects, aka more UART ports.
On your Adafruit Feather M0 with its SAMD21G18 Cortex-M0+ MCU, you have six SERCOM peripherals which you can arbitrarily configure to be a UART, I2C or SPI port. Each peripheral can have its connections routed to several different pins on the board. It is a very versatile piece of hardware.
Don't use a SoftwareSerial library made for AVR MCUs when you have the hardware. Adafruit's guide shows how you can reconfigure those SERCOMs to get additional Serial objects.
https://learn.adafruit.com/using-atsamd21-sercom-to-add-more-spi-i2c-serial-ports?view=all#creating-a-new-serial


text:
Making a distance sensor for human interaction
I want to make a sensor that senses a person between 1.5 m and 0.2 m, connected to an LED that is on 100% at 0.2 m and 1% at 1.5 m and gradually scales.
Is an ultrasonic sensor the best sensor to use here?

Welcome to Arduino:SE. You might find this helpful: How to ask a good question for Arduino Stack Exchange

The 'best' sensor might be a $100K Computer vision system with 400 cameras.

are you talking about a swimmer underwater? ... you did not actually say anything about the usage of the system.

Most arduino compatible ultrasonic sensors should work perfectly for your use case. You would just have to program the arduino then but I am going to assume that you know how to do that.
Here is a link to the one that I personally use: https://www.amazon.com/HC-SR04-Ultrasonic-Distance-MEGA2560-ElecRight/dp/B01MA4O5G5/ref=sr_1_3?ie=UTF8&qid=1524520770&sr=8-3&keywords=ultrasonic+sensor


text:
How do I connect a LED strip to a Multiwii SE 2.5?
https://www.m.nu/neopixel/mini-skinny-neopixel-digital-rgb-led-strip-60-led-m-black-pcb-1m
I just purchased this led-strip that I plan to use with my Multiwii SE 2.5.

I power the Multiwii itself via a power distribution board where I connect a 3s LiPo battery. Now I wonder how I would wire my LED strip in order to use it with my Multiwii. I have a few smaller LiPo batteries if I need to power the LED itself (not via the 3s LiPo that powers the Multiwii) but the best solution would of course be to power them together.
I appreciate all help I can get.

Have you looked at any NeoPixel libraries yet?

yes the adafruit one. it works with arduino and since the multiwii is arduino-based i am positive it can be used with the multiwii also? i am just a bit confused on the schematic

Which part? It only needs one pin.

this is my first project so sry if i dont follow along 100 %. if i udnerstand correctly 1 pin goes to a open D-pin. but how does the led get battery? if i look at this image https://www.google.se/search?q=arduino+led+strip&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiUlcC3v7HVAhWE1xQKHQxxBYQQ_AUICigB&biw=1920&bih=983&dpr=1#imgrc=KxTVn-hmlWKCjM: it seems to get volt from the arduino itself. How do i make sure the multiwii powers the led-strip with the 3s lipo?

The 3S LiPo will burn out the strip since it only takes 5V as the specs say. So connect it to 5V.

The led strips I've used with my Naze32 have three connection, +5VDC, GND and DATA. I'm not familiar with your FC but based on the image you provided it looks like you would use one of the two I2C ports. As long as you don't try to run too many LEDs (I've maxed out my FC with 32 LEDs no problem) the +5VDC connection should be able to power the LEDs. Obviously connect LED GND to the FC GND. You'll need to check the docs for you FC to confirm but it would make the most sense to me to connect the FC SDA to the LED DATA. The FC SCL would not be used.
NOTE: If your PDB has a +5VDC output you'd be better off using that one to power the LEDs.
In the picture with the Arduino one of the leads is providing +5VDC. I've read the suggestion for LED strips to place a capacitor across the +5VDC and GND to make it more stable but I don't and I've not had any issues. FYI, the lead to the Arduino is for GND and DATA (being driven by one of the Arduino Digital I/O Pins.


text:
How can I know if I can stack some shield on another shield?
Yesterday I tried to stack a motor shield on a servo motor shield already stacked on my Arduino Uno.
But I realized that I have some problem when I try to use both of them. It seems like some energy is lost or the stepper motor connected to my servo motor shield move weirdly slowly.
I already checked online, and I found some explanations about stacking many shields. About making sure the shields don't use the same pins or SS. As a beginner, help would be very helpful. Thank you.
Here are the two shields I use.

Smart Servo Shield for dynamixel
https://store.arduino.cc/arduino-motor-shield-rev3
Smart Arduino Digital Servo Shield for Dynamixel AX
https://www.dfrobot.com/product-958.html

wiki : https://www.dfrobot.com/wiki/index.php/Digital_Servo_Shield_for_Arduino_SKU:DRI0027
On these links, you can find all the specs with the pins used. I think I have some pinß shared by both of them... But not sure.
Does anyone have a solution please? Many thanks in advance.

The real answer, you don't know.  For example, a shield may need to use the serial port.  So a second identical shield may not work as it too may need to use the same serial port.  Or it may be that the designer of the shield did something clever and used a software serial port of the 2nd shield.

The above comment refers only to hardware.  There is also the software problem of sharing resources.  For instance, a motor shield may use the same timer as an SDCard shield.  So the software for each may not work when both are active on the same Arduino.

Thank you for your example. but for my problem , both of my shields is different. They are not same. I just want to kknow if i need buy another arduino , or have a way for make it work

Mhh ok , so , the best choice is to use one shield per arduino i know. But i know too, sometimes we can stack more than one shield. And for my project i want try to make it the lightest and thinest possible

When using more than 1 shield or Arduino library you will always be taking a risk of running out of resources.  The only true way to be sure this will not happen is to backwards engineer the shield and / or library until you understand what resources each need.  It is a lot of work for a beginner. Many people simply experiment / test to see if a given combination works.  Usually for software nothing much bad happens.  But for hardware there is always a chance of "burning something up".

First you have to compare the pinouts of the two shields. If the shields use completely different pins then yes, you can use them together.
However if they share pins then you need to look in more detail at what those pins are and how they are being used.
In your example you have SPI being used (pins 10-13) for one shield and PWM (3/11) and GPIO (8/9/12/13) and analog input (A0/A1) for the other shield.
You can see now that there is a conflict. For instance pin 13 for the SPI clock for the DFRobot shield is also being used for one of the GPIO pins of the Arduino shield. Pin 12 for MISO is being used as GPIO. Pin 11 for MOSI is also being used for PWM.
Those are disparate functions on the pin, so it can never work.
However if the SPI pins were being used for both shields as SPI then that could work. In that case it's only the "chip select" pin that needs to be unique for each shield, since SPI is a Master-Slave Bus protocol which can be shared amongst multiple shields.

Ok thank you , That's a nice answer !! So even if i want to use a arduino Mega, it's will not work . I think i will use two separate Arduino Uno.


text:
RFM95 LoRa module frequency options
I live in India, and unfortunately here the unlicensed band ranges only from 865MHz to 867M Hz. The IBM LoRa code for Arduino (as node) for RFM95 module allow you to choose between 915 Mhz and 868 Mhz only. I initially created a gateway using a Pi3 listening at 865.7 (to conform with Indian rules), but it couldn't receive any payloads from my node running at 868 Mhz. Then, eventually, I tried again with my gateway listening at 868 Mhz, and it worked like a charm. No hiccups.
But, obviously, it seems to be against the rules, and I don't fancy prison. So I want to know if I can get the RFM95 module working somewhere in the range of 865 Mhz to 867 Mhz? And if yes, how can I do it? There certainly doesn't seem to be an option to choose a frequency other than 868 Mhz or 915 Mhz in the IBM Lora code. Here is the link to the code library. https://github.com/matthijskooijman/arduino-lmic

Are you sure that limitation also applies for such low powered radios and home appliances?

The various LoRa projects I've come across online make an effort to conform with their respective nationalities' frequency regulations. Hence, the question.

The RF networks of the RFM95 board are ideally configured for the general range of frequencies, but the difference between your 865.7 MHz and the 868 MHz tuning of a European (vs US) version of the board is likely smaller than the error with which the RF networks can be tuned to begin with, so that is unlikely to be a problem unless there is some hard lockout of your desired frequency in the SX1272 chip.  I've even heard claims that some people have managed to at least somehwat use US vs European tuned versions on the opposite bands, which is far more drastic than what you are trying to accomplish.
So assuming there is no hard lockout of your desired frequencies in the hardware, basically what you will need to do is to change the frequency list in the source of the software you are using to operate the module.
Basically you would edit src/lmic/lorabase.h and make a modified version of the EU configuration.  Ideally you'd add that as an additional option and select it, but for an initial test you could just edit the European version to fit your needs.
Do keep in mind the code will probably want to use multiple frequencies - if you have a gateway that receives only on a single frequency, you'll need to modify the code to always use that, after determining if doing so fits with usage-rate rules in your jurisdiction.
It's probably worth doing some online research to see if anyone has already put thoughts into operating LoRa in India - if so, there may already be a modified branch of the LMiC code you can use.

Unfortunately there isn't much LoRa stuff going on here. 5 TTN gateways in total in India. Speaks for itself.

5 Things Network gateways is a non-zero number, and a sufficient number for you to determine what frequencies they are using if you can find an email address, post or other information for one of their owners.  For that matter, you'd probably be better off asking in a global Things Network forum than asking here, since your question is really about the radios and the LMiC code, not Arduino.


text:
Arduino UNO + Ethernet Shield + LCD + RFID but RFID doesn't work
I've been working to a project that uses arduino for RFID but when connected to ethernet shield, the RFID seems to not read any card tapped to sensor but the LCD seems to do fine. Here's the code I use from this page: http://www.instructables.com/id/RFID-CARD-READER-WITH-ARDUINORFID-RC522-and-LCD-16/
#include <EEPROM.h> //Library To read and write PICC's UIDs from/to EEPROM
#include <SPI.h> //Library  RC522 Module uses SPI protocol
#include <MFRC522.h> //Library  RC522 Module
#include <LiquidCrystal.h> //Library  for LCD Display
#include <Ethernet.h>

EthernetServer server(80);
boolean match = false; // initialize card match to false
boolean programMode = false; // initialize programming mode to false
int successRead; // Variable integer to keep if we have Successful Read from Reader
byte storedCard[4]; // Stores an ID read from EEPROM
byte readCard[4]; // Stores scanned ID read from RFID Module
byte masterCard[4]; // Stores master card's ID read from EEPROM
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
LiquidCrystal lcd(7, 6, 5, 4, 3, 2); //Initializing LCD PINS as (RS, EN, D4, D5, D6, D7)

void setup() {
  Serial.begin(9600); // Initialize serial communications with PC
  lcd.begin(16, 2); //Initializing LCD 16x2
  pinMode(8, OUTPUT); //LED and Buzzer PIN OUT
  SPI.begin(); // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init(); // Initialize MFRC522 Hardware
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
  if (EEPROM.read(1) != 1) {
    // Look EEPROM if Master Card defined, EEPROM address 1 holds if defined
    Serial.println("No Admin Card Defined");
    //When no Master Card in Your EEROM (Serial Display)
    Serial.println("Scan A card to Define as Admin Card");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.println("SET ADMIN CARD   ");
    //When no Master Card in Your EEROM (LCD Display)
    lcd.setCursor(0, 1);
    lcd.println("SCAN A CARD.....");
    //Scan any RFID CARD to set Your Master Card in Your EEROM (LCD Display)
    delay(1500);
    do {
      successRead = getID();
      // sets successRead to 1 when we get read from reader otherwise 0
    }
    while (!successRead);
    //the program will not go further while you not get a successful read
    for (int j = 0; j < 4; j++) {
      // Loop 4 times
      EEPROM.write(2 + j, readCard[j]);
      // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 1); //Write to EEPROM we defined Master Card.
    Serial.println("Admin Card Defined");
  }
  Serial.println("Administrator Card's UID");
  for (int i = 0; i < 4; i++) { // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard
    Serial.print(masterCard[i], HEX); //Master Card only view in serial
    Serial.println("Waiting PICCs to bo scanned :)");
  }
 //WAITING TO SCAN THE RFID CARDS:
  Serial.println("");
  Serial.println("Waiting cards to bo scanned :)");
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.println("WAITING     ");
  lcd.setCursor(3, 1);
  lcd.println("FOR CARD...  ");
  delay(1500);
}

int getID() {
 // Getting ready for Reading PICCs
  if (! mfrc522.PICC_IsNewCardPresent()) {
    //If a new PICC placed to RFID reader continue
    return 0;
  }
  if (! mfrc522.PICC_ReadCardSerial()) {
    //Since a PICC placed get Serial and continue
    return 0;
  }
 // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
 // I think we should assume every PICC as they have 4 byte UID
 // Until we support 7 byte PICCs
  Serial.println("Scanning card's UID....");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SCANNING");
  lcd.setCursor(0, 1);
  lcd.print("Card's UID.....");
  delay(2000);
  for (int i = 0; i < 4; i++) {
    readCard[i] = mfrc522.uid.uidByte[i];
    Serial.print(readCard[i], HEX);
  }
  Serial.println("");
  mfrc522.PICC_HaltA(); // Stop reading
  return 1;
}
boolean isMaster(byte test[]) {
  if (checkTwo(test, masterCard))
    return true;
  else
    return false;
}

boolean checkTwo (byte a[], byte b[]) {
  if (a[0] != NULL)
    // Make sure there is something in the array first
    match = true;
    // Assume they match at first
  for (int k = 0; k < 4; k++) {
    // Loop 4 times
    if (a[k] != b[k])
      // IF a != b then set match = false, one fails, all fail
      match = false;
  }
  if (match) {
    // Check to see if if match is still true
    return true;
  } else  {
    return false;
  }
}
boolean findID(byte find[]) {
  int count = EEPROM.read(0);
  // Read the first Byte of EEPROM that
  for (int i = 1; i <= count; i++) {
    // Loop once for each EEPROM entry
    readID(i);
    // Read an ID from EEPROM, it is stored in storedCard[4]
    if (checkTwo(find, storedCard)) {
      // Check to see if the storedCard read from EEPROM
      return true;
      break; // Stop looking we found it
    } else {
      // If not, return false
    }
  }
  return false;
}
void readID(int number) {
  int start = (number * 4) + 2;
  // Figure out starting position
  for (int i = 0; i < 4; i++) {
    // Loop 4 times to get the 4 Bytes
    storedCard[i] = EEPROM.read(start + i);
    // Assign values read from EEPROM to array
  }
}
void deleteID(byte a[]) {
  if (!findID(a)) {
    // Before we delete from the EEPROM, check to see if we have this card!
    failedWrite(); // If not
  } else {
    int num = EEPROM.read(0);
    // Get the numer of used spaces, position 0 stores the number of ID cards
    int slot;
    // Figure out the slot number of the card
    int start;
    // = (num * 4) + 6; // Figure out where the next slot starts
    int looping;
    // The number of times the loop repeats
    int j;
    int count = EEPROM.read(0);
    // Read the first Byte of EEPROM that stores number of cards
    slot = findIDSLOT(a);
    //Figure out the slot number of the card to delete
    start = (slot * 4) + 2;
    looping = ((num - slot) * 4);
    num--; // Decrement the counter by one
    EEPROM.write(0, num); // Write the new count to the counter
    for (j = 0; j < looping; j++) {
      // Loop the card shift times
      EEPROM.write(start + j, EEPROM.read(start + 4 + j));
      // Shift the array values to 4 places earlier in the EEPROM
    }
    for (int k = 0; k < 4; k++) {
      //Shifting loop
      EEPROM.write(start + j + k, 0);
    }
    successDelete();
  }
}
//For Failed to add the card:
void failedWrite() {
  Serial.println("something wrong with Card");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SOMETHING WRONG");
  lcd.setCursor(0, 1);
  lcd.print("WITH CARD");
  delay(2000);
}

//For Sucessfully Deleted:
void successDelete() {
  Serial.println("Succesfully removed");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SUCCESFULLY");
  lcd.setCursor(0, 1);
  lcd.print("REMOVED CARD");
  delay(2000);
}

int findIDSLOT(byte find[]) {
  int count = EEPROM.read(0);
  // Read the first Byte of EEPROM that
  for (int i = 1; i <= count; i++) {
    // Loop once for each EEPROM entry
    readID(i);
    // Read an ID from EEPROM, it is stored in storedCard[4]
    if (checkTwo(find, storedCard)) {
      // Check to see if the storedCard read from EEPROM
      // is the same as the find[] ID card passed
      return i;
      // The slot number of the card
      break;
      // Stop looking we found it
    }
  }
}
//For Sucessfully Added:
void successWrite() {
  Serial.println("Succesfully added");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("SUCCESFULLY");
  lcd.setCursor(0, 1);
  lcd.print("ADDED");
  delay(2000);
}

//For Adding card to EEPROM:
void writeID(byte a[]) {
  if (!findID(a)) {
    // Before we write to the EEPROM, check to see if we have seen this card before!
    int num = EEPROM.read(0);
    // Get the numer of used spaces, position 0 stores the number of ID cards
    int start = (num * 4) + 6;
    // Figure out where the next slot starts
    num++;
    // Increment the counter by one
    EEPROM.write(0, num);
    // Write the new count to the counter
    for (int j = 0; j < 4; j++) {
      // Loop 4 times
      EEPROM.write(start + j, a[j]);
      // Write the array values to EEPROM in the right position
    }
    successWrite();
  } else {
    failedWrite();
  }
}
void loop() {
  lcd.clear();
  lcd.setCursor(4, 0);
  lcd.print("TAP YOUR");
  lcd.setCursor(4, 1);
  lcd.print("CARD HERE");
  do {
    successRead = getID(); // sets successRead to 1 when we get read from     reader otherwise 0
    if (programMode) {
      // Program Mode cycles through RGB waiting to read a new card
    } else {
    }
  }
  while (!successRead);
  //the program will not go further while you not get a successful read
  if (programMode) {
    if (isMaster(readCard)) {
      //If master card scanned again exit program mode
      Serial.println("This is ADMIN Card");
      Serial.println("Exiting ADMIN Mode");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("EXITING FROM");
      lcd.setCursor(0, 1);
      lcd.print("ADMINISTRATOR MODE");
      delay(2000);
      programMode = false;
      return;
    } else {
      if (findID(readCard)) {
        //If scanned card is known delete it
        Serial.println("I know this CARD, so removing");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("AVAILABLE!");
        lcd.setCursor(0, 1);
        lcd.print("SO DELETING.....");
        delay(5000);
        deleteID(readCard);
        Serial.println("-----------------------------");
      } else {
        // If scanned card is not known add it
        Serial.println("Adding this card...");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("Card no:");
        lcd.setCursor(0, 1);
        lcd.print(readCard[0], HEX);
        lcd.print(readCard[1], HEX);
        lcd.print(readCard[2], HEX);
        lcd.print(readCard[3], HEX);
        lcd.print(readCard[4], HEX);
        delay(4000);
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("NOT AVAILABLE");
        lcd.setCursor(0, 1);
        lcd.print("SO ADDING...");
        delay(5000);
        writeID(readCard);
        Serial.println("-----------------------------");
      }
    }
  } else {
    if (isMaster(readCard)) {
      // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println("Welcome to Administrator Mode");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("WELCOME TO");
      lcd.setCursor(0, 1);
      lcd.print("ADMIN MODE");
      delay(3000);
      int count = EEPROM.read(0);
      // Read the first Byte of EEPROM that
      Serial.print("I have ");
      // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(" record(s) on EEPROM");
      Serial.println("");
      Serial.println("Scan a card to ADD or REMOVE");
      Serial.println("-----------------------------");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SCAN CARD TO");
      lcd.setCursor(0, 1);
      lcd.print("ADD OR REMOVE...");
      delay(2500);
    } else {
      if (findID(readCard)) {
        // If not, see if the card is in the EEPROM
        Serial.println("Acces Granted");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("ACCESS GRANTED");
        lcd.setCursor(0, 1);
        lcd.print("YOU MAY ENTER NOW");
        digitalWrite(8, HIGH);
        delay(1500);
        digitalWrite(8, LOW);
        lcd.clear();
      } else {
        // If not, show that the ID was not valid
        Serial.println("Access Denied");
        for (int abcd = 0; abcd < 3; abcd++) {
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("     SORRY");
          lcd.setCursor(0, 1);
          lcd.print("  ACCESS DENIED");
          digitalWrite(8, HIGH);
          delay(1000);
          digitalWrite(8, LOW);
          lcd.clear();
          lcd.print("   YOU'RE NOT  ");
          lcd.setCursor(0, 1);
          lcd.print("   AUTHORIZED   ");
          delay(1000);
        }
        lcd.clear();
      }
    }
  }
}

Any help would be appreciated!

Well, the Ethernet shield uses SPI as well, and pins 10-13.  Seems that would be a problem...

Thank you kind Sir, I'm fairly new to coding arduino and I just follow instructions so I don't know what to add in the code to add SPI device(Ethernet shield).

What @KCTucker is saying is that you can not use every optional feature with every other optional feature.

I recently made a similar project with a RFID reader and an SD card shield, and I had the same problem.
The explanation why it doesn't work is that some shields that use SPI communication don't really care about your slave select pin being pulled low, and interfere when Arduino is talking to another SPI device via the MISO pin.
The only way I got it to work is by using a tri-state buffer on the MISO pins of my SPI devices. You can find plenty of info about it on the internet, as well as how to use them in your project.
The idea is simple, it works kind of like a transistor. When you pull the enable pin of the buffer to ground using SS pin, you allow the MISO pin of that device to be connected to the corresponding Arduino input. Otherwise, the MISO pin will be on a state of high impedance and would not interfere on the communication anymore.
Good luck with your project.

It may not be possible to use every optional Arduino feature with every other optional Arduino feature. Some features use the same Arduino resources.  If there is actually a hardware contention problem, you need to dive deep into the software drivers and hardware to figure out if there is a possible work around.  But this is hardly the type of effort new developers would take on.  It might be easier for a new developer to use 2 different Arduino's to host the features desired and set up a communication link between them.

If you are "following instructions", please post a URL to the project that is using all the hardware you mentioned.


text:
Problem with Arduino line follower
I am making a line follower robot. My code is like this
#define motI1 10
#define motI2 6
#define motI3 5
#define motI4 3

int left=9;   // left sensor
int right=1;  // right sensor

void setup() {
  pinMode(motI1, OUTPUT);
  pinMode(motI2, OUTPUT);
  pinMode(motI3, OUTPUT);
  pinMode(motI4, OUTPUT);
  pinMode(left, INPUT);
  pinMode(right, INPUT);
  Serial.begin(9600);
}

void loop() {
  if(((digitalRead(left))==HIGH)&&((digitalRead(right))==HIGH)) {
    digitalWrite(motI1, HIGH);
    digitalWrite(motI2, LOW);
    digitalWrite(motI3, HIGH);
    digitalWrite(motI4, LOW);
    Serial.println("FORWARD");
    delay(1);
  } else if(((digitalRead(left))==HIGH)&&((digitalRead(right))==LOW)) {
    // turn right
    digitalWrite(motI1,HIGH);
    digitalWrite(motI2,LOW);
    digitalWrite(motI3,LOW);
    digitalWrite(motI4,LOW);
    Serial.println("Right turn Right Sensor LOW");
    delay(1);
  } else if(((digitalRead(left))==LOW)&&((digitalRead(right))==HIGH)) {
    // turn left
    digitalWrite(motI1,LOW);
    digitalWrite(motI2,LOW);
    digitalWrite(motI3,HIGH);
    digitalWrite(motI4,LOW);
    Serial.println("Left turn Left Sensor LOW");
    delay(1);
  } else if(((digitalRead(left))==LOW)&&((digitalRead(right))==LOW)) {
    digitalWrite(motI1,LOW);
    digitalWrite(motI2,LOW);
    digitalWrite(motI3,LOW);
    digitalWrite(motI4,LOW);
    Serial.println("Stop");
    delay(1);
  }
}

Only pin 1 of the Arduino is working but other pins are not working for the IR sensor. But the pins for the motor are working just fine. What is the real problem?

Are you sure it's working? Pin 1 is used as Serial Tx line. Is there possibility that IR sensors requires pull up resistor?

Yes pin 1 is working. I don't think IR sensor requires pull up resistor.

Battery operated?  Disconnect the motors and measure to see if the sensor and motor control states are as you expect them when moving the sensors across the line.  Often people skip over the pitfalls of high current / low voltage problems when using batteries or even under powered wall supplies.

What kind of line-following sensor is it? If it's like the Sparkfun IR sensors, then they need to be connected to ADC pins and a digitalRead won't work on them.


text:
16*2 LCD display doesn't display my result
I am working on a project to calculate line frequency meter by reciprocal counting with Arduino. I am trying to print the the result on a 16*2 LCD but it is not displaying anything. It just gets on and stuck there. I got the project details from this website Line Frequency Meter Based On Reciprocal Counting
I modified the stock program to interface the LCD but it's not working. Here is the code I am using:
//To read and display the Line frequency
//using Reciprocal counting method
//clk for 'Time Counter'  is generated with 'Tone' function
//'Time counter' is the physical counter T1
// 'EVENT Counter' is a software counter
#define Fin 6      // input pin for Line freq sig
#define clk 7      // input to ' Time ' counter
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
boolean FState;   // status of the 50 Hz Signal
int countS;       // Signal count
int countC=0;     //  Clock count
int LineFreq;     // Result

void setup() {
  tone(8, 5000); // generates ref freq of 5000 Hz at Pin 8
  pinMode(Fin, INPUT); // set the Fin pin as INPUT
  pinMode(clk, INPUT); // set the clk pin as INPUT
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Frequency of signal");
  // to avoid partial cycles, first detect the rising edge
  while(digitalRead(Fin)) {
    //wait for '0' state of the Signal
    delayMicroseconds(10);
  }
  //here '0' state
  while(!digitalRead(Fin)) {
    //wait for '1' state
    delayMicroseconds(10);
  }
  //this is the rising edge of the Fin
  //counting can start from here
  // clear the TIME Counter T1
  counterStart1();
  //count 50 of the Line freq signals
  while(countS<50) {
    while(digitalRead(Fin)) {
      //wait for '0' state
      delayMicroseconds(1);
    }
    //here '0' state
    while(!digitalRead(Fin)) {
      //wait for '1' state
      delayMicroseconds(1);
    }
    // here '1' state
    // here one cycle is just over
    //increment the event counter
    countS=countS+1;
  }
  //here 50 Signal cycles over
  // read the contents of T1 & compute frequency
  countC = getCount1();
  LineFreq = 25000000/countC;

  //send to display
  lcd.setCursor(0,1);
  lcd.print(LineFreq);
  lcd.print(" Hz");
  delay(500);
  delay(100);
  // clear counter
  countS=0;
  // repeat
}

//The following code is obtained from on-line articles in the public domain
void counterStart1() {
 // hardware counter setup,  for  the 16-bit Timer1 Timer/Counter
 TCCR1A=0; // reset timer/countern control register A
 TCCR1B=0; // reset timer/countern control register B
 TCNT1=0; // initialize the counter value to 0; this register holds the current count
  // set timer/counter1 hardware as a counter; it counts events on pin Tn (Arduino pin 5)
 TCCR1B = TCCR1B | 7; // Counter Clock source = pin Tn (Arduino pin 5) , start counting now
 // 7 in binary is 0111; OR-ing will set CS10,11,12 to 1's
return;
}

// the following code is obtained from on-line articles in the public domain
// Sub routine  to get the current count
unsigned int getCount1() {
 unsigned int count; // this variable returns the current count from the counting register
 TCCR1B = TCCR1B & ~7; // Gate Off  / Counter T1 stopped,
 // this operation clears the bits (CS10,11,12)
 count = TCNT1; // read the counting register
 TCCR1B = TCCR1B | 7; // re-start counting by resetting the bits (CS10,11,12)
 return count; // return the retrieved count to the calling function
}

I am getting a blank screen but the line at very first of the code "Frequency of signal" is printing accurately.
What is wrong with the code and what changes do I need?
Thanks in advance!

Which is it? Not displaying anything, or only displaying "Frequency of signal"?

I fixed your indentation, as it was nearly impossible to read.

If the latter, it seems like you signal on pin 6 isn't there, or is too weak. Ending up with your code waiting for 50 transitions that just aren't there?

It is only displaying frequency of the signal only, which is written at the top of code. After that nothing is working. I checked the pin 6 signal And it was working fine.

Your variables are int, which on an Arduino is a 2-byte signed type by default, and has a range of -32768 to 32767.
When you execute:
LineFreq = 25000000/countC;

is the result of the math a 2-byte int, or a 4-byte long? Regardless, you are possibly assigning a 4-byte value to an int.
You can declare LineFreq to be type long, and also append an L to the end of the constant value 25000000 to force long math, so that you have:
long LineFreq;
[...]
LineFreq = 25000000L/countC;


text:
What's the problem? My motor works properly only when we press the left key and not others
int mf11=13;//motor1 1st terminal
int mf12=12;//motor1 2nd terminal
int mf21=9;//motor2 1st terminal
int mf22=8;//motor2 2nd  terminal
int fr=2;//front key
int bk=3;//back key
int rt=4;//right key
int lt=5;//left key

void setup() {
    pinMode(mf11,OUTPUT);
    pinMode(mf12,OUTPUT);
    pinMode(mf21,OUTPUT);
    pinMode(mf22,OUTPUT);
    pinMode(fr,INPUT);
    pinMode(bk,INPUT);
    pinMode(rt,INPUT);
    pinMode(lt,INPUT);
}

void loop() {
    int s = digitalRead (fr);
    int h = digitalRead (bk);
    int i = digitalRead (rt);
    int v = digitalRead (lt);
    if(s==HIGH) {
         digitalWrite(mf11,HIGH);
         digitalWrite(mf12,LOW);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
    if (h==HIGH) {
        digitalWrite(mf11,LOW);
        digitalWrite(mf12,HIGH);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
    }
    if (i==HIGH) {
         digitalWrite(mf11,LOW);
         digitalWrite(mf12,HIGH);
         digitalWrite(mf21,HIGH);
         digitalWrite(mf22,LOW);
    }
   if (v==HIGH) {
        digitalWrite(mf11,HIGH);
        digitalWrite(mf12,LOW);
        digitalWrite(mf21,LOW);
        digitalWrite(mf22,HIGH);
   } else {
       digitalWrite(mf11,LOW);
       digitalWrite(mf12,LOW);
       digitalWrite(mf21,LOW);
       digitalWrite(mf22,LOW);
  }
}

Would need schematics to be able to tell whats going on....   Also I am guessing you really want to use else if statements rather then separate if statements as the else only applies to the if(v==HIGH) statement  (this may be part/all of your issue, as that is the condition you say works)

The reason your code only works for left, is because when v is LOW your else block gets executed and sets all pins to low! You need to use else if.
if(condition1)
{
  ...
}
else if (condition2)
{
  ...
}
else
{
  ...
}


text:
Will I be able send a HTTP request using the Arduino Yún?
After spending countless hours trying to get my wifi module to work only to fail, I've decided I might as well get an Arduino with built-in wifi.
Would I be able to send HTTP requests (GET, POST etc) straight out of the box or would I have to configure and connect some additional components/modules to the board?
Also, I plan on connecting a thermistor and a GPS module to the Arduino. When the thermistor reaches a certain level, it sends the GPS coordinates of my server. Is this possible in terms of practicality and voltage? And would I be able to write a sketch using the Arduino board or would I have to switch the board to something like 'Generic ESP8266 Module' (something we have to do if we want to program the ESP8266 using the Arduino IDE).

Never buy the Arduino Yun. The wifi/linux part runs OpenWRT, and you can do a lot with that. OpenWRT is awesome. If you are familiar with linux, then OpenWRT is no problem for you. The Arduino part is just like an Arduino Leonardo. The problem is the serial communication between those two via the 'Bridge'. It causes a lot of troubles. Therefor my advice is to never buy an Arduino Yun. Don't buy it. Just don't. You can stay Arduino compatible with a nodemcu or go for linux with the Raspberry Pi.

just use a dirt-cheap ESP8266/32 devboard instead of forking over a fortune for an undesirable MCU. you need to choose your board type in the IDE no matter what. if you started with a non-devboard, like an 01, you messed up, but don't allow that to poison the well. try a relatively fool-proof nodeMCU before going down the esoteric route...

Looking at your other two questions as well I see you have had limited success with a ESP8266.  I have never used a Yun, but I haven't seen much good stuff about them on here.  If you want a Linux based none real time system then you may as well get a PI.
Most people seem to think the way to use an ESP8266 is to hook it up to an Arduino and use it as a 'serial over wifi' link.  You can do that, but its like owning a Porsche and Kia and always using the Kia on Motorway journeys.  The ESP8266 is an 80MHz chip with 0.5 MByte of RAM, and you could program it in just the same way as an Arduino if you download the board support package.  It does have only 10 Digital pins and 1 Analog (which I think has lower resolution that the Arduino), but that's where the Arduino comes in.  If you need to hook up lots of pins, then stick the Arduino on the I2C bus as a slave to the ESP.
Now I suspect you have an ESP-01 board and are wondering what the [heck] I am talking about, 10 pins.  The number '01' is the number of GPIO pins that are taken to the edge of the board, so really you want to look at ESP-12E or ESP-13E boards (they still cost about the same $1).  You might want to look at a Wemos D1 or a Node MCU.  Both are fully fledge dev boards, jus plug in the USB and away you go.
So to answer your question:
Get a Wemos D1, hook the hardware up like you wood the Arduino (thermistor and GPS - via SoftwareSerial) and then either code a web server to run on the Wemos or Get it to Post message to you favourite server (see examples for details of either approach)

This is exactly what I want. I guess the way I thought the interaction works between the esp8266 and arduino was wrong. Thanks for clearing the space. I'll order a nodemcu and hopefully it'll end all my trouble! I've got this GPS receiver: https://www.amazon.co.uk/gp/aw/d/B015R62YHI/ref=ya_aw_od_pi?ie=UTF8&psc=1, would this be compatible with the nodemcu?

If you thought it was going to be compatible with an Arduino then yes it should be.  You need to remember that the ESPs are 3.3v chips.  In theory they should accept up to 6V on their digital pins before smoking, but they still only put out 3.3v which might not be enough for you GPS.  So you might want to spend an extra $0.1 on a level convertor.


text:
There is an error stating that "exit status 1 expected unqualified-id before 'if'. This project is used to turn on/off LED and magnetic door
* /
#define CUSTOM_SETTINGS
#define INCLUDE_KEYPAD_SHIELD

/* Include 1Sheeld library. */
#include <OneSheeld.h>

/* Define an iterator. */
int iterations = 0;

/* A name for the LockPin on pin D2. */
int lockPin = 2;
int ledRed = A5;
int ledGreen = A4;

/* A name for the switch led on pin D5. */
const int lampuPin = 5;
const int ledlampu = A0;

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
int stateBefore = 0;
int i = 0;
int j = 0;

void setup() {
  /* Start communication. */
  OneSheeld.begin();
  /* Set the LED & LOCK as output. */
  pinMode(lockPin, OUTPUT);
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  /* Set the LampuPin pin as output. */
  pinMode(lampuPin, INPUT);
  /* Set the LED pin as output. */
  pinMode(ledlampu, OUTPUT);
}

void loop() {
  //======Lampu Rumah=======
  // read the state of the pushbutton value:
  buttonState = digitalRead(lampuPin);
  if (buttonState != stateBefore) {
    if (buttonState == HIGH and i == 0) {
      digitalWrite (ledlampu, HIGH);
      j = 1;
    } else if (buttonState == LOW and j == 1) {
      i = 1;
    } else if (buttonState == HIGH and i == 1) {
      digitalWrite (ledlampu, LOW);
      j = 0;
    } else if (buttonState == LOW and j == 0) {
      i = 0;
    }
  }
  stateBefore = buttonState;
}

//======Pintu Hadapan Rumah=======
/* Check if "1" is pressed, iterate one time. */
if (iterations == 0 && isOnePressed()) {
  iterations++;
} else if (iterations == 1 && isTwoPressed()) {
  /* Check if "2" is pressed, iterate one time. */
  iterations++;
} else if (iterations == 2 && isThreePressed()) {
  /* Check if "3" is pressed, iterate one time. */
  iterations++;
} else if (iterations == 3 && isFourPressed()) {
  /* Check if "4" is pressed, iterate one time. */
  iterations++;
} else if (isOtherButtonPressed()) {
  /* Check if any other button is pressed, reset iterations. */
  iterations = 0;
}
if (iterations == 4) {
  /* Check if the number of iterations is 4, blink the LED. */
  digitalWrite(lockPin, LOW);
  digitalWrite(ledGreen, HIGH);
  digitalWrite(ledRed, LOW);
  OneSheeld.delay(6000);
  digitalWrite(lockPin, HIGH);
  digitalWrite(ledRed, HIGH);
  digitalWrite(ledGreen, LOW);
  OneSheeld.delay(1000);
  /* Reset the iterator. */
  iterations = 0;
}

/* Helper functions check if a certain button is pressed by checking its row and column. */

boolean isOnePressed() {
  return Keypad.isRowPressed(0) && Keypad.isColumnPressed(0);
}

boolean isTwoPressed() {
  return Keypad.isRowPressed(0) && Keypad.isColumnPressed(1);
}

boolean isThreePressed() {
  return Keypad.isRowPressed(0) && Keypad.isColumnPressed(2);
}

boolean isFourPressed() {
  return Keypad.isRowPressed(1) && Keypad.isColumnPressed(0);
}

boolean isOtherButtonPressed() {
  return ((Keypad.isAnyColumnPressed() || Keypad.isAnyColumnPressed()) && !isOnePressed() && !isTwoPressed() && !isThreePressed() && !isFourPressed());
}

You got an extra closing brace after this line.
stateBefore = buttonState;
}

It ends the loop function so the next if is outside any function and illegal.  Hit Control-T in the IDE to auto-format the code and it will line up the indention and that will help you spot these sorts of errors.


text:
How to send an array of unknown size via I2C (from slave to master)?
When I try something like this, everything works.
Slave:
    # define DEFAULT_DATA_SIZE 256

    byte DATA[DEFAULT_DATA_SIZE];

    void requestEvent()
    {
      Wire.write( (byte*) DATA, sizeof(DATA));
    }

    void receiveEvent(int numBytes)
    {
      for (int i = 0; i < numBytes; i++) {
        DATA[i] = Wire.read();
      }
    }

Master:
    # define DEFAULT_DATA_SIZE 5

    void writeData(byte data[], int numBytes) {
      Wire.beginTransmission(I2C_SLAVE_ADDRESS);
      for (int i = 0; i < numBytes; i++)
      {
        Wire.write(data[i]);
      }
      Wire.endTransmission();
    }

    void readData() {
      byte data[DEFAULT_DATA_SIZE];
      Wire.requestFrom( I2C_SLAVE_ADDRESS, DEFAULT_DATA_SIZE );
      if ( Wire.available() == sizeof( data))
      {
        Wire.readBytes( (byte *) data, DEFAULT_DATA_SIZE);
      }
      Serial.print("Byte Array: ");
      for (int i = 0; i < DEFAULT_DATA_SIZE; i++ ) {
        Serial.print(data[i]);
        Serial.print(" ");
      }
      Serial.println();
    }

    byte data[5] = {0x1, 0x2, 0x3, 0x4, 0x5 };

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

      writeData(data, sizeof(data));
      delay(500);
      readData();
    }

    void loop() {

    }

But this only works when the master knows how long the array needs to be.
If I set the value of DEFAULT_DATA_SIZE not to 5, but more, then I get a set of random numbers.
I tried to make the slave pass the length of the array first, and then the array itself. But for some reason it doesn't work and I also get random numbers.
Slave:
    #include <Wire.h>
    # define I2C_SLAVE_ADDRESS 12
    # define DEFAULT_DATA_SIZE 256

    byte DATA[DEFAULT_DATA_SIZE];
    int RECEIVED_NUMBYTES = 0;
    bool isNumBytesSended = false;

    void setup()
    {
      Wire.begin(I2C_SLAVE_ADDRESS);
      delay(1000);
      Wire.onRequest(requestEvent);
      Wire.onReceive(receiveEvent);
    }

    void loop()
    {
    }

    void requestEvent()
    {
      if (!isNumBytesSended) {
        isNumBytesSended = true;
        Wire.write(RECEIVED_NUMBYTES);
      }
      else {
        isNumBytesSended = false;
        Wire.write( (byte*) DATA, sizeof(DATA));
      }
    }

    void receiveEvent(int numBytes)
    {
      RECEIVED_NUMBYTES = numBytes;
      for (int i = 0; i < numBytes; i++) {
        DATA[i] = Wire.read();
      }
    }

Master:
    #include <Wire.h>
    # define I2C_SLAVE_ADDRESS 12
    # define DEFAULT_DATA_SIZE 10

    void writeData(byte data[], int numBytes) {
      Wire.beginTransmission(I2C_SLAVE_ADDRESS);
      for (int i = 0; i < numBytes; i++)
      {
        Wire.write(data[i]);
      }
      Wire.endTransmission();
    }

    void readData() {
      Wire.requestFrom( I2C_SLAVE_ADDRESS, 1 );
      int numBytes = Wire.read();
      Serial.println("numBytes: " + String(numBytes));

      byte data[numBytes];
      if ( Wire.available() == sizeof( data))
      {
        Wire.readBytes( (byte *) data, numBytes);
      }
      Serial.print("Byte Array: ");
      for (int i = 0; i < numBytes; i++ ) {
        Serial.print(data[i]);
        Serial.print(" ");
      }
      Serial.println();
    }

    byte data[5] = {0x1, 0x2, 0x3, 0x4, 0x5 };

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

      writeData(data, sizeof(data));
      delay(100);
      readData();
    }

    void loop() {

    }

Master outputs:

01:20:13.844 -> numBytes: 5
01:20:13.878 -> Byte Array: 11 8 212 8 22
01:21:51.222 -> numBytes: 0
01:21:51.255 -> Byte Array:
01:21:54.323 -> numBytes: 5
01:21:54.323 -> Byte Array: 11 8 212 8 22
01:22:01.682 -> numBytes: 0
01:22:01.717 -> Byte Array:
01:22:04.280 -> numBytes: 5
01:22:04.314 -> Byte Array: 11 8 212 8 22
01:22:06.879 -> numBytes: 0
01:22:06.912 -> Byte Array:
01:22:10.386 -> numBytes: 5
01:22:10.420 -> Byte Array: 11 8 212 8 22

Please tell me the best way to solve this problem. Maybe transfer all values one byte at a time, and put a special delimiter between the beginning of new data?

I get a set of random numbers ... the numbers are not random because they repeat ... the numbers are invalid though

Try making the first byte the length. That will keep you from sending a zero size but the first byte would be 0. Create a function that will send the array byte by byte. Your receiving would also have to know the format.

yes, the idea of sending one byte at a time and specifying the length of the array worked. I'm surprised that I didn't do that sooner :)
SLAVE:
#include <Wire.h>
# define I2C_SLAVE_ADDRESS 12
# define DEFAULT_DATA_SIZE 256

byte DATA[DEFAULT_DATA_SIZE];
int pointer = 0;

void setup()
{
  Wire.begin(I2C_SLAVE_ADDRESS);
  delay(1000);
  Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);
}

void loop()
{
}

void requestEvent()
{
  if (pointer > DATA[0]) {
    Wire.write(0);
  }
  else {
    Wire.write(DATA[pointer++]);
  }
}

void receiveEvent(int numBytes)
{
  DATA[0] = numBytes;
  for (int i = 1; i <= numBytes; i++) {
    DATA[i] = Wire.read();
  }
  pointer = 0;
}

MASTER:
#include <Wire.h>
# define I2C_SLAVE_ADDRESS 12

void writeData(byte data[], int numBytes) {
  Wire.beginTransmission(I2C_SLAVE_ADDRESS);
  for (int i = 0; i < numBytes; i++)
  {
    Wire.write(data[i]);
  }
  Wire.endTransmission();
}

void readData() {
  Wire.requestFrom( I2C_SLAVE_ADDRESS, 1 );
  int numBytes = Wire.read();
  Serial.println("numBytes: " + String(numBytes));

  byte data[numBytes];

  for (int i = 0; i < numBytes; i++) {
    Wire.requestFrom( I2C_SLAVE_ADDRESS, 1 );
    data[i] = Wire.read();
  }
  Serial.print("Byte Array: ");
  for (int i = 0; i < numBytes; i++ ) {
    Serial.print(data[i]);
    Serial.print(" ");
  }
  Serial.println();
}

byte data[8] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8 };

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

  writeData(data, sizeof(data));
  delay(100);
  readData();
}

void loop() {

}


text:
sim800l gsm module response isn't completed
I am using the sim800l gsm module with nodemcu esp8266 and comunicating with it using AT+ commands. The module is working correctly but I am trying to use the command AT+CLCC to get all the current calls' state but it responds with only the first call information and a part of the second call.
This is the response while there are two active calls
15:37:19.156 -> AT+CLCC
15:37:19.156 -> +CLCC: 1,0,1,0,0,"+0123456789",145,"name"
15:37:19.156 ->
15:37:19.156 -> +CLCC: 2,

I think it is the Serial buffer's problem because the size of the serial buffer is 64 bytes and the response is more than that but I don't know how to handle that
I hope someone can help.
EDIT: this is the code i am using
#include <SoftwareSerial.h>
#include <cstring>

#include <Arduino.h>

#define simTX D3
#define simRX D4

SoftwareSerial sim800l(simRX, simTX);  //RX, TX

void setup() {

  Serial.begin(115200);  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)

  sim800l.begin(115200);  //Begin serial communication with Arduino and SIM800L

}

void loop() {

  updateSerial();

}

//Start
// this method takes input from the serial monitor the pass it to sim800l via serial communication
void updateSerial() {
  delay(500);
  while (Serial.available()) {
    sim800l.write(Serial.read());  //Forward what Serial received to Software Serial Port
  }
  while (sim800l.available()) {
    Serial.write(sim800l.read());  //Forward what Software Serial received to Serial Port
  }
}
//End

Could you please share your code? Buffer size shouldn't be an issue depending on how you're fetching the response.

@NickS. i added it in the question :)

get rid of delay() ... change while to if ... see what happens

@jsotola i removed the delay() and changed the while to if as you mentioned and that was the result
`22:54:55.552 -> AT+CLCC
22:54:55.552 -> +CLCC: 1,0,0,0,1,"+0123456789",145,"name"
22:54:55.552 ->
22:54:55.552 -> +CLCC:`
still the same problem

Just for someone in the future who is having the same issue.
the problem was because of the boadrate 115200 is pretty fast for a software serial implementation so i just changed it to 9600
 sim800l.begin(9600);  //Begin serial communication with Arduino and SIM800L

good luck from the past :)


text:
Unable to read the sensor data from all the sensors connected
I am trying to build a project where I have connected 8 Sparkfun TOF Sensors to an I2C MUX which is connected to a Sparkfun RedBoard.
I need to read and display the data from each sensor on the serial monitor right now and later on an OLED Display. The issue I am facing is that it is reading data only from the first sensor and then it stops running.
I have pasted my code below. I am new to all of this so any help would be appreciated on how to fix this issue.  The enableMux() and disableMux() functions are from the GitHub example code libraries. I want to know if the issue is that I am not enabling my ports properly or if the issue is with my data reading. Do I need to initialize each sensor individually?
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "SparkFun_TMF882X_Library.h"

#define sensors 8
SparkFun_TMF882X  myTMF882X;

void setup()
{
  Serial.begin(9600);
  while(!Serial);
  Wire.begin();
  for(byte x=0;x<sensors;x++)
  {
    enableMuxPort(x);
    if(!myTMF882X.begin())
    {
        Serial.println("Error - The TMF882X failed to initialize - is the board connected?");
        while(1);
    }
    else
    Serial.print(x+1);
    Serial.println(" TMF882X started.");
    disableMuxPort(x);
  }
}

void loop()
{
    delay(500);
    for(byte x=0;x<sensors;x++)
    {
      enableMuxPort(x);
      struct tmf882x_msg_meas_results myResults;

      myTMF882X.startMeasuring(myResults);
      Serial.print(myResults.num_results);
      unsigned int distance = myResults.results[0].distance_mm;
      Serial.print("Sensor ");
      Serial.print(x+1);
      Serial.print(" distance: ");
      Serial.print(distance);
      Serial.print("mm");
      Serial.println();
      disableMuxPort(x);
    }
}

Hardware Used:

Microcontroller: Sparkfun Redboard Turbo
MUX: SparkFun Qwiic Mux Breakout - 8 Channel (TCA9548A) - BOB-16784 - SparkFun Electronics
Sensor: Qwiic dToF Imager (TMF882X) Hookup Guide - SparkFun Learn

Below is the output I am getting:
1 TMF882X started.

2 TMF882X started.

3 TMF882X started.

4 TMF882X started.

5 TMF882X started.

6 TMF882X started.

7 TMF882X started.

8 TMF882X started.

9Sensor 1 distance: 3325mm

0Sensor 2 distance: 0mm

you have to supply the module I2C address when you instantiate the SparkFun_TMF882X  object

I'd have started with the assumption that you have to create 8 objects of type SparkFun_TMF882X as
SparkFun_TMF882X myTMF882X[ 8 ]; instead of using a shared object. Alternatively, call the begin() method each time you switch to a different sensor. You could also test the multiplexing by hardcoding say enableMuxPort(2); to see if it works  for just sensor 2.

Where is the definition of enableMux() and disableMux()?


text:
Does 12v 5A power supply is okay to operate motor shield external power
I am new to arduino.

Recently purchased motor shield V1.0 which have two l293 and can run 4 DC motors simultaneously.
But here the problem comes: when I purchased the shield I was not aware that it can only supply 2A peak current.
However, my DC motor rating is 12v 5A. So I purchased a 12v 5A power supply.
But now I am not sure to operate shield with external power of 12v 5A.
Does it works or will it burn?

It looks very much like this motor which isn't 5A - it's 300mA. Where did you get the idea of 5A from?

@Majenko actually it is written in motor 125A , so the shop owner told me that it is 12V and 5A motor

Well, my eyes don't lie to me - there is no 5A motor from Vega Robot Kit - certainly not in that style. So the shop keeper probably has no clue what he is talking about.

Thanks @Majenko, I understood your point of view.
So now I what should I use to power my motors, I tried the computer usb to arduino and placed the jumper so its moving slowly at 255 speed and 64 frequency

You can use your 12V 5A power supply and your motor shield. The motor should never draw more than 300mA, which is far less than both the motor shield and the power supply.

You mean to say remove that jumper and connect the power supply to motor shield directly

Yes. The motor needs 12V. You have to power the shield with 12V so the motor can get that 12V it needs.

So my motor shield will not burn by supplying 12V 5A external power supply?

@Majenko please reply

Only if you try and use more current than the shield can cope with. The 5A for the supply is the maximum it can supply, not what it will supply. The current draw is determined by the load, not the supply.

The shield will "burn". You need a shield that can provide minimum 5A per channel to run a 5A motor.
However, your motors aren't 5A. They have a stall current of 300mA, which is well within the capabilities of the motor shield, and the 5A power supply you have would barely even notice they were there.

What if the 5A is the average current ? If the stall current is 50A, then a motor driver of 50A is required.

@Jot We can only go by what we are told by the OP...

I updated my question, please review and provide appropriate answer

@Majenko please review my question

UmarAta, thanks for the photos. I think that is a 12V motor with 60mA or 70mA without load and 300mA stall current. Why do you think it is 5A ? Do you have specifications for that motor ?


text:
Converting between NEC and HEX values from IR receiver
I jacked one of the IR receivers from my LED strip and hooked it up to my ESP8266 NodeMCU (running Arduino code). I found a great library called IRremoteESP8266. With this library, I can basically receive and send IR signals. However, the HEX values I get in are different from the NEC values I have to send out.
Here's what I've got:
Serial.println((uint32_t) (results.value & 0xFFFFFFFF), HEX);

When I compile this and I open the Serial Monitor, I get D7E84B1B when I press the button on my remote. I searched for it on Google, and I found a site that shows this:
‘real’ decode: FF02FD, hash decode: D7E84B1B

So naturally I tried doing:
irsend.sendNEC(0x00FF02FD, 32);

and it works just fine. The code example for receiving and sending can be found on the repository.
How do I make a conversion between what I receive and what I send, so I can basically mirror what I do?
EDIT:
According to the website I got the real NEC value from, they simply do:
Serial.print(results.value, HEX);

However, when I try to do that, I get this error:

call of overloaded 'println(uint64_t&, int)' is ambiguous

I know they are different projects, but the ESP8266 project I use is based off the IRremote library, which they seem to use.

There is a comment in the linked receiving code: // print() & println() can't handle printing long longs. (uint64_t)  you could just try casting it back to uint32_t - Serial.print((uint32_t)results.value, HEX);


text:
Sending NEC IR signals makes LED strip blink
I'm trying to make my ESP8266 (running NodeMCU meaning Arduino code gets compiled on it). I followed a guide and now I can read the IR codes from my remote using my Arduino UNO, and then send them to the LED strip. So far sending it actually works, but it blinks REALLY fast.
Some part of me tells me it's trying to send it twice or the radio frequency is wrong. For TVs and so on, it doesn't really matter, as you can't turn on and off a TV instantly. You can with this LED strip though. This is how I send my NEC signal to the strip:
irsend.sendNEC(0xFF02FD, 433);

433 is the frequency (433 kHz), as I read that's the most common frequency these LED strips work at. The entire code I used can be found here. Do you think I have a frequency issue? I have tried a lot of different frequencies and they all seem to do the same thing.
Also, when I try to send the exact same NEC signal to my receiver, I get two different results. It is only being sent one time as well. Here is what I receive:
Using the actual receiver:
Decoded NEC(1): Value:FF02FD (32 bits)
Raw samples(68): Gap:51848
  Head: m8750  s4550
0:m450 s650 1:m450 s650      2:m450 s650    3:m450 s650
4:m500 s650 5:m450 s650      6:m450 s650    7:m450 s650
8:m450 s1750    9:m500 s1750         10:m450 s1750  11:m450 s1750
12:m500 s1750   13:m450 s1750        14:m450 s1750  15:m500 s1750

16:m450 s650    17:m450 s650         18:m450 s650   19:m450 s650
20:m500 s600    21:m500 s650         22:m450 s1750  23:m450 s650
24:m450 s1750   25:m500 s1700        26:m500 s1750  27:m450 s1750
28:m500 s1700   29:m500 s1750        30:m450 s650   31:m450 s1750

32:m450
Extent=66900
Mark  min:450    max:500
Space min:600    max:1750

Using irsend.sendNEC(0xFF02FD, 433)
Decoded Unknown(0): Value:0 (0 bits)
Raw samples(38): Gap:18088
  Head: m8850  s4550
0:m500 s1750    1:m500 s650      2:m450 s650    3:m500 s650
4:m500 s650 5:m450 s650      6:m500 s650    7:m450 s1800
8:m450 s700 9:m450 s1800         10:m450 s1800  11:m450 s1800
12:m450 s1800   13:m450 s1800        14:m450 s1800  15:m450 s650

16:m500 s1750   17:m500
Extent=43200
Mark  min:450    max:500
Space min:650    max:1800

EDIT: I forgot to mention: 0xFF02FD is the signal power/on/off button. If I change the 0xFF02FD to anything else (like 0xFF18E7 to make it yellow), the LED strip will just blink.

Huh, are you controlling a ledstrip or a TV (by ir)?

@Paul LED strip :) But as you can see below, I managed to fix this.

Ah wait, you've got an ledstripcontroller with IR? Or are you actually blinking a whole strip in IR signals? xd

38kHz is the most common for IR. For RF remotes it's 433MHz. So I think that where you got that number from.

32 kHz seems to be the winner. Now all my codes work! Damn, if I only had read that ONE SITE that showed it haha.


text:
Best way to assign value to lot of variables
I'm building web based remote control system for esp8266. In arduino IDE, using the ESP libraries. To, send data to the server, I'm using http post.
For some settings, I need to transfer 30 or so, different values over a single post request.  And assign it to different type of variables.
so, from this:
192.168.1.101/testpost?lenght=10&1=100&2=true&3=1800&4=125

i need this:

uint8_t brightness = 100;
bool randomOrder = true;
uint16_t Delay = 1800;
uint8_t Position = 125;

This is the relevant code. Basically, my idea is, to send the lenght of the array (will be different each time.) in the first argument.
Than create a for loop that put every value in a array into variable pointers. But, since lots of different type variables going on, i'm not sure how to do that.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

//values i need to set in a single post.
uint8_t settings0;
bool brightness;
uint16_t randomOrder;
uint8_t Delay;

void setup {
//relevant code that handels post request.
server.on("/testpost", HTTP_POST, []() {

String ZeroValue = server.arg("lenght");

int lenght = ZeroValue.toInt();

//this doesnt really work, but its a starting idea.
int* SettingsArray[4] = {&settings0, &brightness, &randomOrder, &Delay};

for( int i = 0; i < lenght; i++) {

     String PresetSettings = server.arg(i);
     SettingsArray[i] = PresetSettings.toInt();
    }
});
}

Ultimately, I can just do that, but I'm wondering if there is a more elegant solution.
brightness = SettingsArray[1];
randomOrder = SettingsArray[2];
Delay = SettingsArray[3];
Position = SettingsArray[4];

The WebServer class supports argument lookup by name. This should allow HTTP argument parsing that does not require length and/or specific order:
192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

And parse with:
brightness = server.arg("brightness").toInt();
randomOrder = server.arg("randomOrder").toInt();
Delay = server.arg("delay").toInt();
Position = server.arg("position").toInt();

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.
String arg = server.arg("argName");
val = (arg.length() == 0 ? defaultVal : arg.toInt());

Or simply:
String arg = server.arg("argName");
if (arg.length() != 0) val = arg.toInt();

Cheers!

Thank you! didn't notice i can do that, that simplify code on front end as well.


text:
Power supply change change gps readings?
I was powering a GPS Sensor from the 3v3 pin of a raspberry pi and my reading for my GPS sensor had some strange symbols in the mix, but when i switched to the 3v3 on the arduino, my reading came back to normal. This wasted several hours of my time.
Any idea why i would get weird readings when using a different power source?? (even though it is the same voltage)
Note: Both the raspberry pi and the arduino are getting their power form the USB that is connected to my PC.

The Pi can only supply ~50mA from 3.3V. This is unlikely to be enough to run GPS.
In addition USB can only supply 500mA. This is marginal at best, and below the recommended minimum for Pi.


text:
How to Change the Output Resolution of Sine Wave Controller
I have code that receives values from a serial connection, then uses those values to generate sine wave points. These sine wave points are used to position multiple servos.
I am currently trying to decrease the resolution of the sine wave points so there is more time for the servo to reach its given position.
The only way I can think of to accomplish this is by increasing the time between writing servo positions. As far as I can tell, I have implemented this correctly, however it results in a sine wave of a lower frequency.
The method I am using to alter the resolution is by changing the variable sine_time, which is used in the conditional statement if(currentMillis - previousMillis >= sine_time), near the bottom of the program.
/*
This is a program that recieves sine wave parameters from a serial connection in a single string.
The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
positions for each joint of the robot.
*/

#include <Servo.h>

Servo SB, SF, HB, HF, EB, EF, KB, KF;
int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
unsigned int t = 0;
unsigned long previousMillis = 0;
float fKnee_amp, fAfreq, fPhase, fGait;

void setup(){
  //Start serial stream at 115200 baud
  Serial.begin(115200);

  //Connect servos to Arduino
  HB.attach(2);
  KF.attach(3);
  SB.attach(4);
  EB.attach(5);
  HF.attach(6);
  KB.attach(7);
  SF.attach(8);
  EF.attach(9);

  delay(3000);
}

void loop(){
  char c, buffer[10];
  String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
  //change the resolution of the sine wave (lower value is higher resolution)
  //digital servos refresh at a rate of 50Hz which is 0.02s
  float sine_time = 100;

  while (Serial.available() && readString.length() < 37){
    //delay to allow buffer to fill
    delayMicroseconds(10);
    if (Serial.available() > 0){
      //get one byte from serial buffer
      char c = Serial.read();
      //creates the string "readString"
      readString += c;
    }
  }

  if (readString.length() > 36){
    //see what was received
    Serial.println("The string is: " + readString);
    Serial.println(readString.length());

    //parse serial string into separate parameters
    amp = readString.substring(0, 3);
    knee_amp = readString.substring(3, 7);
    afreq = readString.substring(7, 11);
    phase = readString.substring(11, 15);
    gait = readString.substring(15, 20);
    f_offset = readString.substring(20, 24);
    b_offset = readString.substring(24, 28);
    fk_offset = readString.substring(28, 32);
    bk_offset = readString.substring(32, 36);
    /*
    //Print to serial monitor to see parsed results
    Serial.println("Hip Amp: " + amp);
    Serial.println("Knee Amp: " + knee_amp);
    Serial.println("Afreq: " + afreq);
    Serial.println("Gait: " + gait);
    Serial.println("Phase: " + phase);
    Serial.println("F Offset: " + f_offset);
    Serial.println("B Offset: " + b_offset);
    Serial.println("Fk Offset: " + fk_offset);
    Serial.println("Bk Offset: " + bk_offset + "\n");
    */
    //convert string values to numbers
    iAmp = amp.toInt();

    knee_amp.toCharArray(buffer, 10);
    fKnee_amp = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    afreq.toCharArray(buffer, 10);
    fAfreq = atof(buffer)/100;
    memset(buffer, 0, sizeof(buffer));

    phase.toCharArray(buffer, 10);
    fPhase = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    gait.toCharArray(buffer, 10);
    fGait = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    iF_offset = f_offset.toInt();
    iB_offset = b_offset.toInt();
    iFk_offset = fk_offset.toInt();
    iBk_offset = bk_offset.toInt();

    //clear strings
    readString="";
    amp="";
    knee_amp="";
    afreq="";
    gait="";
    phase="";
    f_offset="";
    b_offset="";
    fk_offset="";
    bk_offset="";
  }

  //if the joints should be oscillating
  if (fAfreq > 0){
    //determine joint positions
    pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
    pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
    pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
    pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

    pos[4] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fPhase) + 1500 + iFk_offset;
    pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 - iFk_offset;
    pos[6] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1500 + iBk_offset;
    pos[7] = iAmp*fKnee_amp*2 * sin(fAfreq*t + fGait + fPhase) + 1538 - iBk_offset;
    /*
    //print parameter variables
    Serial.println(iAmp);
    Serial.println(fKnee_amp);
    Serial.println(fAfreq);
    Serial.println(fGait);
    Serial.println(fPhase);
    Serial.println(iF_offset);
    Serial.println(iB_offset);
    Serial.println(iFk_offset);
    Serial.println(iBk_offset);

    //print servo positions
    Serial.println(pos[0]);
    Serial.println(pos[1]);
    Serial.println(pos[2]);
    Serial.println(pos[3]);
    Serial.println(pos[4]);
    Serial.println(pos[5]);
    Serial.println(pos[6]);
    Serial.println(pos[7]);
    */
    //get time in milliseconds
    unsigned long currentMillis = millis();

    //if the time threshold has been passed
    if(currentMillis - previousMillis >= sine_time){

      Serial.println(currentMillis - previousMillis);

      previousMillis = currentMillis;

      //write servo positions
      HB.writeMicroseconds(pos[2]);
      KF.writeMicroseconds(pos[6]);
      SB.writeMicroseconds(pos[0]);
      EB.writeMicroseconds(pos[4]);
      HF.writeMicroseconds(pos[3]);
      KB.writeMicroseconds(pos[7]);
      SF.writeMicroseconds(pos[1]);
      EF.writeMicroseconds(pos[5]);

      //increment time parameter
      t+=1;
    }
  }
}

Your sine waves depend on “time” via appearances of fAfreq*t in lots of places.  However, t actually is a pass counter, rather than reflecting true elapsed time.
Instead of incrementing t by 1, increment it by a value that's proportional to elapsed time.  Or, more directly, set t equal to a multiple of elapsed time.  For example, whenever you start over, record current time via basetime = millis().  Then, just after your //determine joint positions comment, say t = speedratio * (millis()-basetime);.

authors: خالد الهزازي