body:
I am trying to send and receive data using I2C between an Arduino Nano and an ATTiny85.
The ATTiny is mounted on this board:
[Link][1]

I've tried to reach the slave with the simple I2C scanner, but I don't find anything.

Those are the codes:

Master (I2C scanner):

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

    #include <Wire.h>

    void setup()
    {
      Wire.begin();

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

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

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

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

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

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

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

And this is the code of the ATTiny85 (slave):

    #include <TinyWire.h>

    #define led_pin 1

    byte own_address = 10;

    void setup() {
      // config led_pin as Output for driving an LED
      pinMode(led_pin, OUTPUT);

      // config TinyWire library for I2C slave functionality
      TinyWire.begin( own_address );
      // sets callback for the event of a slave receive
      TinyWire.onReceive( onI2CReceive );
    }

    void loop() {

    }

    /*
    I2C Slave Receive Callback:
    Note that this function is called from an interrupt routine and shouldn't take long to execute
    */
    void onI2CReceive(int howMany){
      // loops, until all received bytes are read
      while(TinyWire.available()>0){
        // toggles the led everytime, when an 'a' is received
        if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
      }
    }

Once I've programmedo both the boards I've connected SCL and SCK pins of the boards together.

If i open the serial monitor of the master this is what i get:

> I2C Scanner Scanning... Unknown error at address 0x20 Unknown error at
> address 0x21 No I2C devices found
>
> Scanning... Unknown error at address 0x78 No I2C devices found
>
> Scanning... No I2C devices found
>
> Scanning... Unknown error at address 0x08 Unknown error at address
> 0x09 Unknown error at address 0x60 No I2C devices found
>
> Scanning... Unknown error at address 0x70 No I2C devices found

And so on.
Can someone explain me were I'm doing errors?

  [1]: https://www.aliexpress.com/item/GY-Attiny85-Digispark-kickstarter-Mini-USB-Development-Board-Module-Tiny85/32356300524.html?spm=2114.search0104.3.17.62253bd9WXTC3J&ws_ab_test=searchweb0_0,searchweb201602_1_10065_10068_319_317_10696_10084_453_10083_454_10618_10304_10307_10820_10821_537_10302_536_10902_10843_10059_10884_10887_321_322_10103,searchweb201603_59,ppcSwitch_0&algo_expid=7b44b0ad-ce27-4e20-b79a-b5c8487f54d5-2&algo_pvid=7b44b0ad-ce27-4e20-b79a-b5c8487f54d5&transAbTest=ae803_4

title: ATTiny85 I2C connection with Arduino Nano

Answers: 1

body:
Problem solved!

I've modified the code, this is the final one:

    #include <TinyWire.h>

    #define led_pin 1
    #define I2C_SLAVE_ADDR  0x11

    void setup() {
     // config led_pin as Output for driving an LED
     pinMode(led_pin, OUTPUT);

     // config TinyWire library for I2C slave functionality
     TinyWire.begin( I2C_SLAVE_ADDR );
     // sets callback for the event of a slave receive
     TinyWire.onReceive( onI2CReceive );
    }

    void loop() {

    }

    /*
    I2C Slave Receive Callback:
    Note that this function is called from an interrupt routine and shouldn't take long to execute
    */
    void onI2CReceive(int howMany){
     // loops, until all received bytes are read
     while(TinyWire.available()>0){
      // toggles the led everytime, when an 'a' is received
      if(TinyWire.read()=='a') digitalWrite(led_pin, !digitalRead(led_pin));
     }
    }

Like this the I2C scanner sees the board at the address 0x11.

The wirings are the following:

 - Arduino pin SCL to ATTiny85 pin SCL (P2)
 - Arduino pin SDA to ATTiny85 pinSDA  (P0)
 - Take care of wire to the same ground both the boards.


body:
Will a delay() function in a void SerialEvent() also stop the code that is running in the void loop() function?

This is about an Arduino Uno.

Answers: 2

body:
This is the main function of the Arduino core:

    int main(void)
    {
     init();

     initVariant();

    #if defined(USBCON)
     USBDevice.attach();
    #endif

     setup();

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

     return 0;
    }

`serialEventRun()` runs the `serialEvent()` function, if it is assigned,
so yes, **a delay in serialEventRun will delay the loop**.

body:
In an Atmega328p, the Uno's processor, there is only 1 CPU; it can only do one thing at a time. If it is executing code in the SerialEvent() function, then by definition, it is *not* executing code in the loop() function or anywhere else.

There is a minor exception to this: interrupt service routines will run briefly when their respective interrupts occur. In fact, one way a delay() function can operate depends on timer updates that take place as interrupts. (The other way is by executing a loop whose execution time is accurately known, a specified number of times).

But interrupt service routines do one, very short, job, and return the CPU to whatever it was doing immediately before (delay() within the SerialEvent() function), so no other user code can be executed until the delay ends.


body:
My Rfid reader stops scanning cards after scanning the wrong rfid card. It doesn't scan it anymore after turning off the relay. *It turns on the relay if my rfid card is the right one

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

    #define SS_PIN 10
    #define RST_PIN 9
    #define relay 2
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
    int touchPin = 8;
    unsigned long previousMillis = 0;        // will store last time LED was updated
    unsigned long tacc = 5000UL;           // interval at which to blink (milliseconds)
    boolean opened = false;
    void setup()
    {
      pinMode(touchPin, INPUT);
      pinMode(relay, OUTPUT);
      digitalWrite(relay, HIGH);
      Serial.begin(9600);   // Initiate a serial communication
      SPI.begin();      // Initiate  SPI bus
      mfrc522.PCD_Init();   // Initiate MFRC522
      mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
      Serial.println("Approximate your card to the reader...");
      Serial.println();
    }
    void loop()
    {
      unsigned long currentMillis = millis();
      int touchValue = digitalRead(touchPin);
      if (touchValue == HIGH) {
        digitalWrite(relay, HIGH);
      }
      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent())
      {
        return;
      }
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial())
      {
        return;
      }
      //Show UID on serial monitor
      Serial.print("UID tag :");
      String content = "";
      byte letter;
      for (byte i = 0; i < mfrc522.uid.size; i++)
      {
        Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
        Serial.print(mfrc522.uid.uidByte[i], HEX);
        content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        content.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
      Serial.println();
      Serial.print("Message : ");
      content.toUpperCase();
      if (content.substring(1) == "72 02 EF E9" ) {
      Serial.println("Authorized access");
        digitalWrite(relay, LOW);
        opened = true;
      }
      if (((unsigned long)(currentMillis - previousMillis) >= tacc) && (opened== true)) {
      digitalWrite(relay, HIGH);
        previousMillis = currentMillis;
        opened = false;
      }
    }

title: Rfid stops scanning after wrong card scanned

Answers: 0


body:
I have to reproduce a signal (of 6 UART frames) which have 950 µs delay between each of the frames. Than, a delay of 37ms at the end of those frames.

Everything going right except the delay between each frame...The baud rate is at 9600.

Here is my current code :

      Serial1.write(sw_binary_train_1);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_2);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_3);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_4);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_5);
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_6);
      delay(37);

title: Wait between UART frames

Answers: 2

body: set delayMicroseconds(1900) do a delay of 950µs between each frames...Strange but works !

body:
It's not strange at all.  Serial doesn't block while it sends.  When you call write that pushes the byte into the send buffer and that's all.  Then the code moves on to the next instruction, the delay(950) and during that time the serial data is actually being sent.  It takes about 1 millisecond for that to happen.

This solution works as long as the send buffer doesn't have anything else in it that's slowing you down and as long as you don't change the baud rate.  If either of those things happen then you need to recalculate that time.

A better solution would be:

      Serial1.write(sw_binary_train_1);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_2);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_3);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_4);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_5);
      Serial1.flush();
      delayMicroseconds(950);
      Serial1.write(sw_binary_train_6);
      Serial1.flush();
      delay(37);

The flush blocks until the send buffer is empty again.  That way you don't have to account for that time and all you need the delay for is the time between transmissions.

Even better would be if those things were in an array so you didn't have to keep repeating yourself.  Anytime you catch yourself putting numbers on variable names what you really want is an array so that you can use those numbers in the program:

    for (int i=0; i<6; i++){
      Serial1.write(sw_binary_train[i]);
      Serial1.flush();
      delayMicroseconds(950);
    }
    delay(37)

looks much better.


body:
I have an oled display which can only display 4 digits + decimal point.
I need a way to format the number into 4 significant figures;
Then I need to convert that into an array of 5 chars (4 digits and one dp) before I can display them.

Not sure how to format to correct number of digits or how to convert into a char array. I searched a bit and printf seems to be the solution(?) but I've had no luck with it so far as it spits out all sorts of errors. if you know how to make it work, please can you provide a code snippet which compiles without errors? thanks.

title: Specific formatting of floats and converting them to an array of chars

Answers: 1

body:
Normally `sprintf()` would be the solution - however the `sprintf()` in the AVR LIBC is a cutdown version with no floating point support.

Instead you have to use [`dtostrf()`](https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html) to get the job done:

    dtostrf(val, 6, 4, buffer);

The numbers there are the maximum width of the string (note: you need to take into account any minus sign in that value), and the number of decimal places (6,4 would give you room for "0.0000" but not "-0.0000"). Make sure your buffer is bigger by one byte than your text, since you have to have the trailing NULL character in there to terminate it.

Another (nasty) way would be to go via `String` (although I would never recommend using `String` for anything, ever):

    String s(val, 4);
    const char *buf = s.c_str(); // this points to the internal char buffer.


body:
I have a function defined as follows:

`void turn_leds_on(int col_indx, int bright_1 = BRIGHTNESS, int del_1 = 5, bool dir_1 = true ) `

This function is called using MQTT from user to define led's properties, which only first is mandatory ( has no default value ) - MQTT format is : ` 1,50,40,0`, but can be `1,10`.

Now, to implements this - I read MQTT message and store os into `parameters` as follows:

    splitter(incoming_msg, 4, parameters); // read 4 parameters

when it defined as:

        void splitter(char *inputstr, int x, char *output[]) {
      char * pch;
      char *pnts[x];
      int i = 0;

      pch = strtok (inputstr, " ,.-");
      while (pch != NULL)
      {
        output[i] = pch;
        pch = strtok (NULL, " ,.-");
        i++;
      }
    }

The problem starts when the user enters only 2 parameters and when passing `parameters` into :

    if ( atoi(parameters[0]) <= tot_colors - 1 && isDigit(*parameters[0])) { // color num
          if (atoi(parameters[1]) <= 100 && isDigit(*parameters[1])) { //brightness
            if (atoi(parameters[2]) <= 100 && isDigit(*parameters[2])) { //delay between leds
              if (atoi(parameters[3]) <= 1 && isDigit(*parameters[3])) { //direction
                turn_leds_on(atoi(parameters[0]), atoi(parameters[1]), atoi(parameters[2]), atoi(parameters[3]));

So the question is: how to pass arguments, and on the other hand when they are not given, to use their default values as defined inside the function?

title: How to use parameteric function arguments

Answers: 0


body:
I'm trying to print out the temperature from a DS18B20 sensor to my app via a tpc connection. Because I have two sensors connected I will need to call the one needed by an Index. This index comes from my app and is a char value which I need to convert it to an int for comparision later. The problem I have is the conversion from to input char value to int.
My code:
<!-- language-all: lang-cpp -->

    void loop() {
      //setting default sensor to 0
      sensorindex = 0;
      //starting server
      WiFiClient client = wifiServer.available();

      if (client) {
      Serial.write("Client connected");
              client.println("connected");
        while (client.connected()) {
          while (client.available()>0) {

            //instream from client/mobile device
            char c = client.read();
            //converting char c to int
            sensorindex = String(c).toInt() ;
            Serial.println(sensorindex);
          }

          //comparing client input to DS18B20 sensor index
          sensors.requestTemperatures();
          if(sensorindex == 1){
               client.println(sensors.getTempCByIndex(1));
               Serial.println("Index 1");
          }
          if(sensorindex == 0){
               client.println(sensors.getTempCByIndex(0));
                 Serial.println("Index 0");
          }

          delay(50);
        }

        client.stop();
        Serial.println("Client disconnected");
      }
    }

The serial output:

    Client connectedIndex 0
    Index 0
    Index 0
    Index 0
    Index 0
    Index 0
    1
    0
    Index 0
    Index 0
    Index 0
    Index 0
    Index 0
    Index 0
    Index 0
    Index 0
    Client disconnected

When I type in 1 from my android app it shows

    1
    0

in the output. What am I doing wrong?

title: Converting Client input char to int

Answers: 0


body:
I am trying to build a gateway for ESP-NOW (https://github.com/HarringayMakerSpace/ESP-Now) and I would like to get help with connecting two esp8266 (nodemcu + esp01) with serial link (for use as gateway).

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

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

What I done so far:

    ESP01 ... NODEMCU
    -----------------
    3V3   ...  3v3
    GND   ...  GND
    CH_PD ...  3v3
    TX    ...  RX
    RX    ...  TX

The problem is that with this setup NodeMCU (and I think ESP01 too) is not booting (probably because TX is connected?). What's the correct way to connect two ESP8266 as described in ESP-NOW project?

NodeMCU is running this code:

https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowFromSerialGateway

ESP-01 is running this code:

https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowToSerial

title: Connect two ESP8266 using serial link

Answers: 0


body:
I am trying to create a Traffic Light Controller.
There are three modes to the controller:
Mode 1 - the traffic light operates RED-YELLOW-GREEN-YELLOW and should repeat
* (The other modes are not necessary apart from knowing the user can select the mode.)*

I want to loop the function of the mode until I receive an input from the serial monitor. If no input is detected, then it should continue with the current mode.
At the moment I am using **Serial.read()** at the start of the main loop function before my switch statement to select the mode. However, this needs an input, but I want the switch cases to loop until an input is received.

All help will be much appreciated.

title: How do you make a switch case run until another serial input is detected?

Answers: 2

body:
Use something like this (it is pseudo code so convert it to your sketch):

    enum EState { NORMAL, SPECIAL } _state; // States
    enum ENormalState { RED, YELLOW1, GREEN, YELLOW2 } _normalState; // State only valid when _state == NORMAL
    unsigned long _time; // _time only valid when _state == NORMAL

    void loop()
    {
       if ('serial input available')
       {
          if ('input == ...')
          {
             _state = NORMAL;
          }
          else if ('input == ...')
          {
             _state = SPECIAL;
          }
          ...
       }

       switch (_state)
       {
       case NORMAL:
           if (_time + ... > time())
           {
              // Change to next state
              switch (_normalState)
              {
              case RED:
                  _normalState = YELLOW1;
                  _time = time();
                  break;

              case YELLOW1:
                  _normalState = GREEN;
                  _time = time();
                  break;
              ...
              }

           setLight(_normalState); // Change the light according to the _normalState
           break;

       case SPECIAL:
           ...
           break;

       ...
       }
    }

Ideas to improve/explain:

- Try to make some specific functions for setting the light according to the current state
- You do not need a delay
- Split functions (like above, make a separate function for normal state, and specific state

body:
thankyou for your responses.
I managed to solve this myself by using a while loop to store the code inside each switch case, my working code is below, utilising **Serial.peek()** and by changing the input ending in the serial monitor to **no line ending**.
```
while ((Serial.peek() == -1)){
          regularMode(ledRed, ledYellow, ledGreen);
}
```
Serial.peek() gets the next item from the serial stack, if there is nothing there, it returns '-1' so i can check against that as shown above.


body:
I have been trying to create code where my MPU6050 is constantly reading the angle it is at and based on that angle, increase or decrease the motor speed. For example the motor will be off when the sensor is level and maximum speed at 45 degrees, and 22 degrees is roughly half speed.

I have a 5065 200kv brushless motor going to a ESC with a bec which i can attach to the Arduino. I have tried to modify a self balancing drone code that used PID. I took out the PID and tried to do an if-then for if the angle is > 5 < 45 then servo write (anglex36) because the maximum angle is 45 and if i multiply 45 by 36 it will be 1620. It says in the code the maximum rpm is 2000, although mine can go faster, and I will change it later after testing.  It is recommended to have the max motor speed be at most 85% motor power to prevent damage so that is why I have it at 1620 for now and not 2000.

I am fairly new with Arduino and have no experience with the MPU6050 so I apologize for any misunderstanding of information or code.

Here is my code :

    #include <Wire.h>
    #include <Servo.h>

    Servo right_prop;

    int16_t Acc_rawX, Acc_rawY, Acc_rawZ,Gyr_rawX, Gyr_rawY, Gyr_rawZ;

    float Acceleration_angle[2];
    float Gyro_angle[2];
    float Total_angle[2];

    float elapsedTime, time, timePrev;
    int i;
    float rad_to_deg = 180/3.141592654;

    double throttle=0; //initial value of throttle to the motors

    void setup() {
      Wire.begin(); //begin the wire comunication
      Wire.beginTransmission(0x68);
      Wire.write(0x6B);
      Wire.write(0);
      Wire.endTransmission(true);
      Serial.begin(250000);
      right_prop.attach(3); //attatch the right motor to pin 3

      time = millis();

      right_prop.writeMicroseconds(1000);
      delay(7000);

    void loop() {

    /////////////////////////////I M U/////////////////////////////////////
        timePrev = time;
        time = millis();
        elapsedTime = (time - timePrev) / 1000;

         Wire.beginTransmission(0x68);
         Wire.write(0x3B);
         Wire.endTransmission(false);
         Wire.requestFrom(0x68,6,true);

         Acc_rawX=Wire.read()<<8|Wire.read();
         Acc_rawY=Wire.read()<<8|Wire.read();
         Acc_rawZ=Wire.read()<<8|Wire.read();

         Acceleration_angle[0] = atan((Acc_rawY/16384.0)/sqrt(pow((Acc_rawX/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;
         /*---Y---*/
         Acceleration_angle[1] = atan(-1*(Acc_rawX/16384.0)/sqrt(pow((Acc_rawY/16384.0),2) + pow((Acc_rawZ/16384.0),2)))*rad_to_deg;

       Wire.beginTransmission(0x68);
       Wire.write(0x43); //Gyro data first adress
       Wire.endTransmission(false);
       Wire.requestFrom(0x68,4,true); //Just 4 registers

       Gyr_rawX=Wire.read()<<8|Wire.read();
       Gyr_rawY=Wire.read()<<8|Wire.read();

       /*---X---*/
       Gyro_angle[0] = Gyr_rawX/131.0;
       /*---Y---*/
       Gyro_angle[1] = Gyr_rawY/131.0;

       /*---X axis angle---*/
       Total_angle[0] = 0.98 *(Total_angle[0] + Gyro_angle[0]*elapsedTime) + 0.02*Acceleration_angle[0];
       /*---Y axis angle---*/
       Total_angle[1] = 0.98 *(Total_angle[1] + Gyro_angle[1]*elapsedTime) + 0.02*Acceleration_angle[1];

        Serial.println(Total_angle[1]);

    if( Total_angle[1]> 5 && Total_angle[1]< 45)
    {
    right_prop.write(Total_angle[1]*37);
    }
    else{
    right_prop.write(0);
    }
    }

    //end of loop void

title: Help with code for changing motor speed depending on MPU6050 angles read

Answers: 0


body:
I have a project on Arduino IDE. A .ino sketch with some extra .h/.cpp files and 2-3 libraries that I keep in ~/Arduino/libraries.

In addition to the IDE I do open the libraries as generic project in eclipse, of course this means no symbols resolution and no indexing which is bad for me.
So I wanted to give Solebera try. I can see that Soleber includes the directory above however when compiling, I can clearly see it doesn't include any of those libraries! Also trying to add them doesn't work as the preference screen doesn't allow it/lists it.

So you help please,

 1. how can i make it even compile?
 2. will eclipse index it? I mean if I press 'ctrl + shift + r' and start typing RH_RF95 (radiohead rf95 driver cpp file) will it let me open it? (it does for Platformio).

title: Arduino libraries development and Eclipse Soleber

Answers: 0


body:
can someone please point me at some code snippets to detect when the GPS is stationary. I am currently using tinyGPS library and it is working fine, but my data-logger has thousands of stationary details I'd like to not bother logging. Currently I am using this,

    uint8_t speedZero() {
    uint8_t spd = gps.speed.mph();
      if (spd < 5) {
        return 0;
      } else {
        return spd;
      }
    }

But it is too granular at slow speeds, but the NEO-6M drifts a lot and 5mph standing still is not uncommon.

I have tried comparing Last Lat/Lon but not having any success as this Math is waaaay out of my skill-zone.

title: GPS detecting stationary?

Answers: 1

body:
I found this to get me started.

http://apexlogic.net/code-bank/arduino/serial-gps-find-distance-between-two-points/


body:
[![MIT Code to receive and display bluetooth data][1]][1]
I'm trying to connect my arduino bluetooth sensor to an MIT App Inventor app I made, and in doing so display the readings of two of my sensors. Whenever I test the sensors in the serial monitor, I get normal readings, but sending them to MIT APP Inventor makes them glitch out and give me the error "Select list item: Attempt to get item number 2 of a list of length 1". I've reviewed all of my code for both the Arduino and the MIT App Inventor, and I haven't been able to find anything that may be hindering me. The timer interval for the MIT App inventor code is correct.

My Arduino code is below; the MIT app inventor code is shown in the above image

    #define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
    #include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

    //  Variables
    const int PulseWire = A1;       // PulseSensor PURPLE WIRE connected to ANALOG PIN A1
    int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
                                   // Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
                                   // Otherwise leave the default "550" value.
    const int PIEZO_PIN = A0; // Piezo output

    PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

    void setup() {
      Serial.begin(9600);          // For Serial Monitor
      // Configure the PulseSensor object, by assigning our variables to it.
      pulseSensor.analogInput(PulseWire);
      pulseSensor.setThreshold(Threshold);
      }
    void loop() {
      int piezoADC = analogRead(PIEZO_PIN); //Get the analog value of the Piezo sensor
      float piezoV = (piezoADC / 1023.0 * 5.0);  //Get the voltage of the Piezo sensor
      int myBPM = pulseSensor.getBeatsPerMinute(); //Get the BPM detected of the user

      Serial.print((double)piezoV); // Print Piezo voltage

      Serial.print("|"); //Use this character to separate the vibration from the heartbeat

      if (pulseSensor.getBeatsPerMinute() == 0){
      Serial.println("N/A");
     }
     else{
      Serial.println((int)myBPM); //Print the BPM
     }
      delay(5000);

    }

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

title: Help with sending data to MIT app inventor through bluetooth

Answers: 0


body:
I'm looking for a Normally-Open optocoupler board for arduino. I need to control power of a device (DC 12v, 500mA).
I tried to use TLP281 board, which works, except that it inverts the output: device is powered when there is no control signal (i.e., it is Normally-Closed).

For this reason, the TLP281 board is not useful in my project.

This is picture and schematics for TLP281 board:

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

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

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

I need an optoisolator board which works analogous to normally open mechanical relay: when there is no signal, device must not be powered; and when there is signal, device must be powered.

*NOTE: workaround by inverting the control signal in microcontroller firmware is not permitted, as the device must not be powered when microcontroller is off*

  [1]: https://i.stack.imgur.com/0EZ8l.png
  [2]: https://i.stack.imgur.com/VY0Og.jpg
  [3]: https://i.stack.imgur.com/iE7wD.jpg

title: Normally-Open opto-coupler board

Answers: 2

body:
I don't think there is a need for a specific "normally-open" opto-coupler. Same result can be easily achieved by using "normally-closed" opto-coupler and making a slightly modified "NOT" logic gate using three resistors and NPN transistor.

[![NOT gate design][1]][1]

 **1. When INPUT is LOW:**

Base of Q1 is shorted to ground through R1 so Q1 not letting the magic pixies go through. This makes OUTPUT show 5V and be in HIGH logic state.

 **2. When INPUT is HIGH:**

Base of Q1 is powered by voltage divider R/R1. R needs to be much lower than R1 to keep Q1 saturated. This makes Q1 to be passing current and setting OUTPUT to LOW state by creating a voltage divider R2/Q1(collector-emitter resistance) This means that value of R2 should be much higher then c-e resistance of Q1.

 **3. When INPUT is floating (microcontroller is turned off):**

Any voltage on INPUT caused by imperfections of the hardware, E-M noise induction, static electricity, etc. should be discharged to ground by resistors R+R1 keeping INPUT in LOW state. (This means that R+R1 cannot have to high value or the discharge speed might be to slow)

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

body:
For those, who are stumbling over this old thread and @igor-liferenko, since this board is still quite common:

This board definitely does *NOT* invert the inputs.

The comment of Igor Liferenko "tested it and I can say for sure that this board inverts the signal (on low input, there is power on output, on high input, there is no power on output)." is wrong. I don't know what he has tested, but both the schematics and tests show, that the board does not invert (or actually inverts twice -- once by the TLP281-4 itself and once by the following S8050-transistors).

So: low on input -> low on output; high on input -> high on output.


body:
My Problem seems to be that my I²C slave randomly disconnects.
I have an Arduino Due communicating with a Arduino Chestnut board (bought hardware).
I now measure data with the Due and then send the data via an I²C interface to the Chestnut. No other devices are on the I²C bus.

The problem is that I randomly receive the error code "2" from the endTransmission method which seems to imply that the slave device disapeared from the bus. The connection sometimes works fine, and then sometimes right after startup or some time later this error occurs. I measured the signals with an oscilloscope and the clock signal then is always low.

Has someone an Idea what could be the problem?

title: Problem I²C Communication between Arduinos

Answers: 0


body:
I am trying to send gps location data every 3 seconds to mqtt server if it's updated but my device shows weird stack errors and resets. What i am missing?

I am using tinygps++ and pubsubclient as libraries.

LOOP:

    void loop() {
      if (WiFi.status() != WL_CONNECTED)
      {
        connectWifi();
      }
      if (WiFi.status() == WL_CONNECTED && !client.connected())
      {
        mqtt_connect();
      }
      client.loop();

      if (WiFi.status() == WL_CONNECTED && client.connected())
      {
        long now = millis();
        if (ss.available() > 0)
        {
          if (now - lastMsg > 3000) {
            lastMsg = now;
            gps.encode(ss.read());
            display.setTextSize(1);
            display.setTextColor(WHITE);
            display.setCursor(0, 0);
            display.println("Lat:" + String(gps.location.lat(), 6));
            display.setCursor(0, 10);
            display.println("Lng:" + String(gps.location.lng(), 6));
            Serial.print("Latitude  : ");
            Serial.println(gps.location.lat(), 5);
            Serial.print("Longitude : ");
            Serial.println(gps.location.lng(), 4);
            if (gps.location.isUpdated())
            {
              String pos = String(gps.location.lat(), 6) + ";" + String(gps.location.lng(), 6);
              client.publish(mqtt_output, pos.c_str());
              display.setCursor(0, 50);
              display.println("Data Sent");
              m_alert();
            }
            display.setCursor(0, 30);
            display.println("Satellites: " + gps.satellites.value());
            display.setCursor(0, 40);
            display.println("HDOP: " + gps.hdop.value());
            display.display();
          }
        }
      }
    }

connectWifi :

    void connectWifi() {
      Serial.println('\n');

      WiFi.begin(ssid, password);             // Connect to the network
      Serial.print("Connecting to ");
      Serial.print(ssid); Serial.println(" ...");

      int i = 0;
      while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
        delay(1000);
        Serial.print("*"); Serial.print(' ');
      }
      w_alert();
      Serial.println('\n');
      Serial.println("Connection established!");
      Serial.print("IP address:\t");
      Serial.println(WiFi.localIP());
    }

mqtt_connect :

    void mqtt_connect() {
      Serial.print(F("MQTT Connecting..."));

      char* clientId = "app";
      while (!client.connected()) {
        mqttConnectAttempt = millis();
        if (client.connect(clientId, mqtt_user, mqtt_pass)) {
          s_alert();
          Serial.println(F("connected"));
          String ready = "Connection Success!\r\n";
          client.publish(mqtt_output, ready.c_str());
          client.subscribe(mqtt_output);
        }
        else {
          Serial.print(F("Failure, rc="));
          Serial.print(client.state());
          Serial.println(F("Connecting Again in "));
          Serial.print(MQTT_PERIOD + " Seconds");
          delay(MQTT_PERIOD);
        }
      }
    }

title: I can't send GPS data to server

Answers: 0


body:
I'm working in a project and part of this project is sending a .wav file from an Arduino to other device (for example anther Arduino).

I already am able to send a .txt file from an SD which was included in the Ethernet Shield to other Arduino SD card, but it doesn't work when I try to send a .wav file.

Any idea ?

    void loop() {
    if(digitalRead(push1) == LOW){
        writeanddeletSDcard();
          Serial.println("i will send now");
          Udp.beginPacket(destIp, port);
         Udp.write(a);
          Udp.endPacket();
          Serial.println("Sending UDP message");}}

    void writeanddeletSDcard(){
        SD.remove("S13.txt");
       myFile = SD.open("S13.txt", FILE_WRITE); // boolean
       data = myFile.size();
      // if the file opened okay, write to it:
      if (myFile) {
        Serial.println("i will Write now ");
        delay(2000);
        Serial.println(data);
        myFile.println("HELLO WORLD");
        myFile.close();

        // close the file:
      }
    else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");}

    // ---------------- here end of Writing an a massege on the SD Card
      // re-open the file for reading:
      myFile = SD.open("S2.WAV");
      if (myFile) {
        Serial.println("inside the file there's");

    c= 0 ;
        // read from the file until there's nothing else in it:
        while (myFile.available()) {
          a[c] = myFile.read();
          c++;
        }
        Serial.println(c);

       // close the file:
        myFile.close();
      } else {
       // if the file didn't open, print an error:
        Serial.println("error opening test.txt");}}

title: Sending .wav via network

Answers: 0


body:
I'm a new here and this is my first question.
I would like to read from serial monitor and stock the information in a array of bytes. then I want to print this array in serial monitor.
This is the code that I tried:

    byte A[6];

    void setup()
    {
    }

    void loop() {
      A[6] = Serial.read();
      Serial.write (A);
    }

title: Read from serial monitor and put it in a array of byte

Answers: 1

body:
If you want to print it only, I would suggest not to store it. But if you want to do some calculations, you might store it.

The problem you make is you always store the value in the 6th element of the array A, however A only has elements A[0] to A[5], so A[6] is beyond the storage space, and results in crashes (sometimes) or at least unexpected behavior.

To fix it you have to store the value in the correct element of A, and for that you need an index variable. Since you can only store 6 values, after the 6th, start with the 0 and process it.

Like:

    byte arr[6];
    index arrIndex;

    void setup()
    {
       arrIndex = 0;
    }

    void loop() {
      // Read serial.
      arr[arrIndex] = Serial.read();

      // Increase counter
      arrIndex++;

      // If the maximum is read, print values and reset it.
      if (arrIndex == 6) {
         // Print the elements.
         for (index = 0; index < 6; index++)
         {
            Serial.write(A[index]);
         }

         // Restart counter.
         arrIndex = 0;
      }
    }

An improvement: instead of 6 everywhere, use a define:

    #define MAX_ELEMENTS 6


body:
I am a hobbyist. Doing some experiments with sound quality. I'll pin point my problem and requirements.

1. **Problem statement** :I want to play audio files ( recorded in human voice, not music files, just some plain human speech files)

2. **I have tried** : a project with an Arduino microcontroller and MicroSD card but audio quality was not at all good from the link below
https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/
https://circuitdigest.com/microcontroller-projects/arduino-audio-music-player
It just used an arduino UNO board, microSD using SPI, a speaker and an LM386 Audio Amplifier.

I read about the details and got to know that I need a DAC for better quality (as PWM cannot serve the purpose), and a speaker also. But there are a number of things available and I dont understand which one to buy and start a project.

Can you share the details of some micro-controller board with a DAC which suffice my purpose, memory to store audio files (or I can use a microSD card device), and a speaker project which I can follow and make one.
I am looking for a board based solution, after getting some results, I can go for separate micro-controller and DAC.

Thanks in advance.

title: Good quality sound using a microcontroller

Answers: 2

body:
One would think that single channel for voice would be enough.  Remember the old Sprint commercials? "So quiet you can hear a pin drop", that was only single channel.  12 bits at 16 MHz for max 8 KHz bandwidth would be good.  Per Wikipedia "In telephony, the usable voice frequency band ranges from approximately 300 Hz to 3400 Hz. It is for this reason that the ultra low frequency band of the electromagnetic spectrum between 300 and 3000 Hz is also referred to as voice frequency, being the electromagnetic energy that represents acoustic energy at baseband. The bandwidth allocated for a single voice-frequency transmission channel is usually 4 kHz, including guard bands, allowing a sampling rate of 8 kHz to be used as the basis of the pulse code modulation system used for the digital PSTN. "

I think several folks, such as Adafruit.com, DFRobot.com, and others make cards with DAC outputs.  Or you could get a DAC only card from Gravitech.us

I started a project at Arduino.cc to sample 16 bits at 44.1KHz, store to SD card, then play it back later. I used external SPI ADC and DAC, and member fatlib16 there helped me to code it.  You can find it by searching "sample, record, playback later" and it should pull it up.

body:
Here is the schematic and breadboard layout I was using.
Coding can be found in this Arduino.cc thread

https://forum.arduino.cc/index.php?topic=180769.60

[![Analog Reference, ADC, DAC wiring][1]][1]

[![Layed out on breadboard before going to PCB][2]][2]

  [1]: https://i.stack.imgur.com/V4958.png
  [2]: https://i.stack.imgur.com/L7MxV.jpg


body:
I am looking for a digital temperature sensor with I2C interface.

I found the SHT31 and the DHT12 (compatible to DHT11). Both also include humidity sensors. And I found libraries for both of them. But I did not find a comparison.

https://sea.banggood.com/GY-SHT31-D-Digital-Temperature-and-Humidity-100-RH-I2C-Sensor-Module-For-Arduino-p-1167498.html

https://sea.banggood.com/KEYES-DHT12-Digital-Temperature-and-Humidity-Sensor-Module-Compatible-DHT11-For-Arduino-p-1400920.html

**What are the (significant) differences between those sensors and libraries?**

In the moment I want to use a sensor to measure the intake air temperature of a motorcycle. One degree celsius accuracy is good enough for this purpose. I don't want to calibrate them, this is why I looked for the digital sensors.

title: What is the difference between the digital temperature sensors SHT31 and DHT11 or DHT12?

Answers: 0


body:
How to combine two different sensor sketches to one complete sketch for a complete circuit that attaches to one Arduino Uno?

**Sharp Dust Sensor**

    int measurePin = A0; // Connect dust sensor to Arduino A0 pin
    int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

    int samplingTime = 280;
    int deltaTime = 40;
    int sleepTime = 9680;

    float voMeasured = 0;
    float calcVoltage = 0;
    float dustDensity = 0;

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

    void loop(){
      digitalWrite(ledPower,LOW); // power on the LED
      delayMicroseconds(samplingTime);

      voMeasured = analogRead(measurePin); // read the dust value

      delayMicroseconds(deltaTime);
      digitalWrite(ledPower,HIGH); // turn the LED off
      delayMicroseconds(sleepTime);

      // 0 - 5V mapped to 0 - 1023 integer values
      // recover voltage
      calcVoltage = voMeasured * (5.0 / 1024.0);
      dustDensity = 0.17 * calcVoltage - 0.1;

      Serial.print("Raw Signal Value (0-1023): ");
      Serial.print(voMeasured);

      Serial.print(" - Voltage: ");
      Serial.print(calcVoltage);

      Serial.print(" - Dust Density: ");
      Serial.println(dustDensity); // unit: mg/m3

      delay(1000);
    }

**MQ-135 Sensor**

    int airquality = A2;
    void setup()
    {
      Serial.begin(9600);

    }
    void loop()
    {

      int sensorValue = analogRead(A2);
      Serial.print("Air Quality = ");
      Serial.print(sensorValue);

      Serial.print("*PPM");
      Serial.println();
      delay(1000);

    }

title: How to combine two different sensor sketches to one complete sketch?

Answers: 2

body:
There is no way of "automatically" combine two sketches into one. That's because resources of Arduino are very limited. For example UNO it has only 4 timers. If both of the sketches want to use same resource they will not work properly.

If you want to combine two sketches into one you have to write a new sketch that combines mechanisms of both sketches. It's not easy, because `delay` and `delayMicroseconds` are going to give you problems, but you should be able to do that using `micros()` and `millis()` plus some modular math.

body:
I will leave a simplified answer and I would recommend to read https://www.makeuseof.com/tag/getting-started-with-arduino-a-beginners-guide/ or similar to get a understanding of how to code.

An Arduino sketch has a structure.

1. Initialising values
2. A `void setup()` this code only run once the MCU is started
3. A `void loop()` and this code runs continuously.

So to merge two sketches you need to combine the code that is in the same sections and of course avoid duplicate code and ensure that you have unique variable names

**Sharp Dust Sensor**

    int measurePin = A0; // Connect dust sensor to Arduino A0 pin
    int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2

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

**MQ-135 Sensor**

    int airquality = A2;
    void setup()
    {
      Serial.begin(9600);
    }

**Combined code**

    int measurePin = A0; // Connect dust sensor to Arduino A0 pin
    int ledPower = D8;   // Connect 3 led driver pins of dust sensor to Arduino D2
    int airquality = A2;

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


body: I want to send data to TFDI. It can be `hello world` or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.

title: Sending data to UART using Atmel Studio with Attiny84

Answers: 1

body:
The ATTiny84 does not have a hardware UART peripheral. Instead it has a USI (universal serial interface), which does not have all the capabilities needed for UART ("serial") interface.

You don't need to burn the Arduino bootloader to use libraries, that were written for the Arduino IDE. You only might need some of the definitions, which you can get by including the arduino.h file.

I think your best bet is to use existing libraries, like the SoftwareSerial library. There are also lots more libraries, that provide bit banged serial interfaces. You can also get them running in Atmel Studio, by including the source files. This is the easy way.

If you want to go the hard way, you might be able to program a hybrid software/hardware UART interface by utilizing some functions of the USI. In a search I found [this site](https://becomingmaker.com/usi-serial-uart-attiny85/), which is about implementing UART with the USI. They also link to Atmel's Application Note  AVR307, which is a good source for understanding this. From this starting point you might also find a ready to go implementation for the USI. If not, you will have to do the work yourself.


body:
I'm making an attendance System using an RFID scanner, scanning RFID Card & saving Data in Excel.

When I used this code with Arduino Uno (by changing `#define SS_PIN 12` and`#define RST_PIN 9`) it worked perfectly fine.

However, when I used the same code (by changing `#define SS_PIN 15` and `#define RST_PIN 5`) the RFID is unable to scan any of the RFID Cards.

`PIN CONNECTION Of ESP8266 & MFRC522
SDA to D8
SCK to D5
MOSI to D7
MISO to D6
GND to GND
RST to D1
3.3V to 3V3`

    #include <ESP8266WiFi.h>     //Include Esp library
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266HTTPClient.h>
    #include <SPI.h>
    #include <MFRC522.h>        //include RFID library

    #define SS_PIN 15 //RX slave select
    #define RST_PIN 5

    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

    byte card_ID[4]; //card UID size 4byte
    byte Name1[4]={0x36,0x69,0x25,0xD9};//first UID card 36 69 25 D9
    byte Name2[4]={0xA7,0xB5,0x33,0x04};//second UID card A7 B5 33 04

    int NumbCard[2];//the number of cards. in my case i have just two cards.
    int j=0;
    int statu[2];//the number of cards. in my case i have just two cards.
    int s=0;

    int const RedLed=6;
    int const GreenLed=5;
    int const Buzzer=8;

    String Log;
    String Name;//user name
    long Number;//user number
    int n ;//The number of card you want to detect (optional)

    void setup() {

      Serial.begin(9600); // Initialize serial communications with the PC
      SPI.begin();  // Init SPI bus
      mfrc522.PCD_Init(); // Init MFRC522 card

      Serial.println("CLEARSHEET");                 // clears starting at row 1
      Serial.println("LABEL,Date,Name,Number,Time IN,Time OUT");// make four columns (Date,Time,[Name:"user name"]line 48 & 52,[Number:"user number"]line 49 & 53)

      pinMode(RedLed,OUTPUT);
      pinMode(GreenLed,OUTPUT);
      pinMode(Buzzer,OUTPUT);

      delay(200);
       }

    void loop() {
      //look for new card
       if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;//got to start of loop if there is no card present
     }
     // Select one of the cards
     if ( ! mfrc522.PICC_ReadCardSerial()) {
      return;//if read card serial(0) returns 1, the uid struct contians the ID of the read card.
     }

     for (byte i = 0; i < mfrc522.uid.size; i++) {
         card_ID[i]=mfrc522.uid.uidByte[i];

           if(card_ID[i]==Name1[i]){
           Name="First Employee";//user name
           Number=123456;//user number
           j=0;
           s=0;
          }
          else if(card_ID[i]==Name2[i]){
           Name="Second Employee";//user name
           Number=789101;//user number
           j=1;
           s=1;
          }
          else{
              digitalWrite(GreenLed,LOW);
              digitalWrite(RedLed,HIGH);
              goto cont;//go directly to line 71
         }
    }
          if(NumbCard[j] == 1 && statu[s] == 0){
          statu[s]=1;
          Serial.print("DATA,DATE," + Name);//send the Name to excel
          Serial.print(",");
          Serial.print(Number); //send the Number to excel
          Serial.print(",");
          Serial.print("");
          Serial.print(",");
          Serial.println("TIME");

          }
          else if(NumbCard[j] == 0){
          NumbCard[j] = 1;
          n++;
          Serial.print("DATA,DATE," + Name);//send the Name to excel
          Serial.print(",");
          Serial.print(Number); //send the Number to excel
          Serial.print(",");
          Serial.print("TIME");
          Serial.print(",");
          Serial.println("");
          digitalWrite(GreenLed,HIGH);
          digitalWrite(RedLed,LOW);
          digitalWrite(Buzzer,HIGH);
          delay(30);
          digitalWrite(Buzzer,LOW);
          }
          else if(statu[s] == 1){
         //Turn Red LED when the employee Already Left
         digitalWrite(RedLed,HIGH);
          }
          delay(1000);
    cont:
    delay(2000);
    digitalWrite(GreenLed,LOW);
    digitalWrite(RedLed,LOW);

    //if you want to close the Excel when all card had detected and save Excel file in Names Folder. in my case i have just 2 card (optional)
    /*if(n==2){
        Serial.println("SAVEWORKBOOKAS,Names/WorkNames");
        Serial.println("FORCEEXCELQUIT");
        }*/
    }

title: Why is this Code not working with Esp8266 when it worked perfectly with Arduino Uno?

Answers: 0


body:
I want to send a file from an Arduino to the server or another Arduino.

I wrote a code that's open the file then write the content of the text on an array and then send it.

That would work if the data is small, but when i try to send, .wav it will takes lots of time if i do it that why (storing each byte in array).
I want to send the whole file at on time.
Is there a way or a library helps ?

    #include <SPI.h>
    #include <Ethernet.h>
    #include <EthernetUdp.h>
    #include <SD.h>

    const int push1 = 2;

    File myFile;
    char a[400];
    int c= 0;

    // network parameters
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x02 };  // ethernet interface MAC address
    IPAddress localIp(10,131,41,72);    // local ip address
    IPAddress destIp(10,131,41,74);      // destination ip address
    unsigned int port = 9631;               // destination port

    // EthernetUDP to send and receive messages.
    EthernetUDP Udp;

    // timing

    // setup the arduino and shields
    void setup() {

        pinMode(push1, INPUT);

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

      Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }
      Serial.println("initialization done.");

      // start ethernet and udp
      Ethernet.begin(mac, localIp);   // static ip version
      //if(Ethernet.begin(mac) == 0) {     // dhcp version
      // report failure to obtain network parameters
      // Serial.println("DHCP error");

      // no point in carrying on, loop indefinitely:
      // while(true)
      // ;
      //}

      // open UDP port
      Udp.begin(port);

      // show the local ip address (useful for dhcp)
      Serial.print("Local IP: ");
      Serial.println(Ethernet.localIP());

      // initialize previous millis variables

    }

    // do tasks
    void loop() {

    if(digitalRead(push1) == LOW){

       myFile = SD.open("R.wav" , FILE_READ);

      if (myFile) {
        // read from the file until there's nothing else in it:
        Serial.println("i will send now");
        while (myFile.available()) {
            a[i] = myFile.read();
            i++;
            }
          Udp.beginPacket(destIp, port);
         Udp.write(a);
          Udp.endPacket();
          Serial.println("Sending UDP message");
          Serial.println();
        }
        // close the file:
        myFile.close();
      } else {
       // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }  } }

title: Send files via network

Answers: 1

body:
You may try:

    Serial.println("Sending UDP message");
    Udp.beginPacket(destIp, port);
    while (myFile.available()) {
      Udp.write(a);
    }
    Udp.endPacket();
    Serial.println("Message sent!");

Or send the message part by part (for example 100bytes or [500bytes][1] at a time)

Though, what makes you think that Arduino would be a platform that can rapidly send large files over network?
Potentially you are better off with an Raspberry Pi.

  [1]: https://stackoverflow.com/questions/1098897/what-is-the-largest-safe-udp-packet-size-on-the-internet


body:
I have the following code that can read a web page using HTTP get but I can only do it because the website I am doing it to has a static IP address, but in my project I am just hosting it on a free service and IP changes rapidly. So is there a way to do the same with only the URL address?

    #include <SoftwareSerial.h>

    SoftwareSerial cell(2,3);  // Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin. connect this to the GSM module

    const String apn = "web2"; // access-point name for GPRS

    const String ip = "212.26.27.181"; // IP address of server we're connecting to
    const String host = "kfu.edu.sa"; // required in HTTP 1.1 - what's the name of the host at this IP address?
    const String request = "GET /sites/Home HTTP/1.1";
    const String useragent = "Mozilla/5.0"; // for our purposes the user agent doesn't matter - if I understand correctly it's helpful to use something generic the server will recognize

    void setup()
    {
      //Initialize serial ports for communication with computer
      Serial.begin(9600);

      Serial.println("Starting SM5100B Communication...");
      cell.begin(9600);

      waitTil("+SIND: 4"); // keep printing cell output til we get "+SIND: 4"
      Serial.println("Module ready");
    }

    void loop()
    {
      Serial.println("Attaching GPRS...");
      cell.println("AT+CGATT=1");
      waitFor("OK");

      Serial.println("Setting up PDP Context...");
      cell.println("AT+CGDCONT=1,\"IP\",\""+apn+"\"");
      waitFor("OK");

      Serial.println("Activating PDP Context...");
      cell.println("AT+CGACT=1,1");
      waitFor("OK");

      Serial.println("Configuring TCP connection to TCP Server...");
      cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");
      waitFor("OK");

      Serial.println("Starting TCP Connection...");
      cell.println("AT+SDATASTART=1,1");
      waitFor("OK");

      delay(5000); // wait for the socket to connect

title: Is it possible to make an HTTP get request using AT Commands without knowing the IP address of the web server?

Answers: 0


body:
I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind.  I'll try to include as much info as possible.

Some preface:
I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low  enough,  power is cut to the motor.

So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.

The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.

I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.

    const int sensorPin = A5;
    const int ledPin = 5;
    int lightLevel;

    void setup(){
      Serial.begin(9600);
      pinMode(12,OUTPUT);
      pinMode(9,OUTPUT);
      pinMode(ledPin, OUTPUT);
    }

    void loop(){
      lightLevel = analogRead(sensorPin);
      lightLevel = constrain(lightLevel, 0, 800);
      Serial.println(lightLevel);

      if(lightLevel < 200){
        digitalWrite(9,LOW);
        digitalWrite(12,HIGH);
        analogWrite(3,255);
      }
      if(lightLevel > 200){
        digitalWrite(9,HIGH);
        analogWrite(3,0);}
    }

title: Having trouble with motor shield running off external power source

Answers: 1

body:
Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +).
This will avoid micro power drops...
Verify that y hardware driving motor works below 9V.


body: I want to store noise data (basically from A0) from an Arduino Uno to an SD card with faster writing speed, preferably by using 512 data together and the write it at once. What should be the code?

title: Fast data logging

Answers: 1

body:
1. Read the values into an array big enough to store them
2. Write the array with the `write(const uint8_t *buffer, size_t size)` method.

Each `write` then gives you a block of binary data (512 values, 1024 bytes if they're 16-bit integers) written to the SD card. What you do with it then is up to you.

Note: an Arduino UNO only has 2kB of memory. If you have 512 integers that's half your memory gone. The SD card library needs another 512 bytes or more for its internal sector buffer. That's another 25% of your memory used. Already you're up to 75% of your memory gone.


body:
I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial.
Because library too libraries i don't know which one can help complete my project.

title: How to chose softserial library use on Arduino project?

Answers: 1

body:
I think your problem is that you need 4 serial ports.

With software serial that's just not going to happen:

* SoftwareSerial can only receive on **one** serial port at any given time.
* AltSoftSerial is limited to specific pins, and only one instance because there is only one set of pins
* NeoSWSerial is kind of between the two. More efficient than SoftwareSerial, but still (as far as I can tell) limited to one instance (it uses a timer interrupt to drive the communication, so can use any pins)

If you need communication between lots of devices over serial then you will either need devices with more hardware serial ports (Arduino Mega, for example), or implement a multi-drop bus system (like RS-485) which only needs one serial port to communicate with many devices. Extra external hardware is required though.


body:
For the XP under the Russian locale I'm getting the strange output when trying to compile Marlin project for Anycoubic 3d printer according to instruction https://3dtoday.ru/blogs/trialon/marlin119-for-anycubic-kossel-linear-plus

avr-g++: error: C:\DOCUME~1\ИЖИ: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\sketch\Marlin.ino.cpp: No such file or directory

avr-g++: error: Ь~1\LOCALS~1\Temp\arduino_build_153827\preproc\ctags_target_for_gcc_minus_e.cpp: No such file or directory

avr-g++: warning: '-x c++' after last input file has no effect

avr-g++: fatal error: no input files

compilation terminated.

exit status 1
Ошибка компиляции для платы Arduino/Genuino Mega or Mega 2560.

title: Path relater errors on compilation in Arduino IDE 1.8.5 under Windows XP

Answers: 1

body: I have realized that the root cause was the windows user with the Cyrillic name. So creating a new user wiht base Latin name and running Arduino IDE from it helped


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

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

How do I start this program???

    int x=0;
    int P1=A5;
    int P2=A4;
    int P3=A3;
    int R1=3;
    int G1=5;
    int B1=6;
    int R2=9;
    int G2=10;
    int B2=11;
    int sValue1;
    int sValue2;
    int sValue3;
    int oValue1;
    int oValue2;
    int oValue3;
    int timer(1000);

    void setup() {
     pinMode(P1,INPUT);
     pinMode(P2,INPUT);
     pinMode(P3,INPUT);
     pinMode(R1,OUTPUT);
     pinMode(G1,OUTPUT);
     pinMode(B1,OUTPUT);
     pinMode(R2,OUTPUT);
     pinMode(G2,OUTPUT);
     pinMode(B2,OUTPUT);

    }

    void loop() {

    sValue1=analogRead(P1);
    sValue2=analogRead(P2);
    sValue3=analogRead(P3);

    oValue1=map(sValue1,0,1023,0,255);
    oValue2=map(sValue2,0,1023,0,255);
    oValue3=map(sValue3,0,1023,0,255);

    if ((sValue1=0)&&(sValue2=0)&&(sValue3=0));
    {
      setColor1(0,255,255);
      delay(timer);
      setColor2(255,0,0);
    }
    }

    void setColor1(int red1, int green1, int blue1){
      {
        analogWrite(R1,red1);
        analogWrite(G1,green1);
        analogWrite(B1,blue1);
      }
    }

    void setColor2(int red2, int green2, int blue2){
      {
        analogWrite(R2,red2);
        analogWrite(G2,green2);
        analogWrite(B2,blue2);

      }
    }

title: RGB and Potentiometer

Answers: 3

body:
1. Install [Arduino IDE](https://www.arduino.cc/en/Main/Software)
1. New sketch
1. Paste code
1. Connect the Arduino board to your PC
1. Upload sketch

body:
> Also i get Error compiling from this program

Obviously B1 is already defined as something, like your A5, A4 and A3 are.<br>
You will very likely have the same issue with B2.

body:
Arduino has created binary numbers: B1, B101, B00111, and so on.

It is documented in the reference page "[Integer Constants][1]".
The "B1" is defined in "[binary.h][2]".

They should not have done that. Not a single C++ software engineer thinks that it was a good addition. The C++ language is perfectly fine for creating binary values: 0b1, 0b101, 0b00111, and so on.

It is not your fault, you can blame Arduino. Because of this, you should **never** create variables with the name: B1, B101, B00111, and so on.

  [1]: https://www.arduino.cc/reference/en/language/variables/constants/integerconstants/
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/binary.h#L31


body:
I am trying to send IMU sensor data via WiFi using ESP8266. Both MPU9250 and ESP8266 worked individually with 3.3 V when tested, but are not working when interfaced together. I am not sure what the problem is; it looks like the ESP8266 is getting connected to WiFi, but the IMU is having a problem.

First I connected the ESP and the IMU parallel with 3.3 V from the Arduino, but it did not work.
Then I connected the IMU separately with 5 V but still unsuccessful.

Connections of MPU9250

[![Arduino uno connection with imu][1]][1]

Connection of ESP8266

[![ESP8266 connection to arduino uno][2]][2]

note:-
3.3 supply is common to esp and imu
reset is connected to ground
board selected in Arduino IDE is 'generic ESP8266'

code:

    #include <ESP8266WiFi.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #include <PubNub.h>
    #define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
    #include "MPU9250.h"

    const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
    const char *pass =  "786110786";

    const char * pubkey = "pub-c-4a9cdbca-5688-4939-a852-f63cf6743980";
    const char * subkey = "sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094";

    const char * pubchannel = "demo_keyset";
    const char * subchannel = "demo_keyset";

    MPU9250 IMU(Wire,0x68);
    int status;

    void setup() {
        /* For debugging, set to speed of your choice */
        Serial.begin(115200);

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

           WiFi.begin(ssid, pass);
           while (WiFi.status() != WL_CONNECTED)
              {
                delay(500);
                Serial.print(".");
              }
          Serial.println("");
          Serial.println("WiFi connected");

        /* Start the Pubnub library by giving it a publish and subscribe
           keys */
        PubNub.begin(pubkey, subkey);

        while(!Serial) {}

      // start communication with IMU
      status = IMU.begin();
      if (status < 0) {
        Serial.println("IMU initialization unsuccessful");
        Serial.println("Check IMU wiring or try cycling power");
        Serial.print("Status: ");
        Serial.println(status);
        while(1) {}
      }
    }

    void loop() {
        // read the sensor
      IMU.readSensor();
      // display the data
      Serial.print(IMU.getAccelX_mss(),6);
      Serial.print("\t");

        /* Publish message. You could use `auto` here... */
        PubNonSubClient *pclient = PubNub.publish(pubchannel, "String(IMU.getAccelX_mss())");
        if (!pclient) return;
        PublishCracker cheez;
        cheez.read_and_parse(pclient);
        /** You're mostly interested in `outcome()`, and,
            if it's "failed", then `description()`.
        */
        Serial.print("Outcome: "); Serial.print(cheez.outcome());
        Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
        Serial.print("description: "); Serial.println(cheez.description());
        Serial.print("timestamp: "); Serial.println(cheez.timestamp());
        Serial.print("state: "); Serial.print(cheez.state());
        Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
        pclient->stop();

        /* Wait for news. */
        PubSubClient *sclient = PubNub.subscribe(subchannel);
        if (!sclient) return; // error
        String msg;
        SubscribeCracker ritz(sclient);
        while (!ritz.finished()) {
            ritz.get(msg);
            if (msg.length() > 0) {
                Serial.print("Received: "); Serial.println(msg);
            }
        }
        sclient->stop();

        delay(1000);
    }

I didn't get any error but here is the serial port message:-

    .....
    WiFi connected
    IMU initialization unsuccessful
    Check IMU wiring or try cycling power
    Status: -1

    Soft WDT reset

    >>>stack>>>

    ctx: cont
    sp: 3ffffdf0 end: 3fffffc0 offset: 01b0
    3fffffa0:  3fffdad0 00000000 3ffeec60 40206dd0
    3fffffb0:  feefeffe feefeffe 3ffe8538 4010150d
    <<<stack<<<

     ets Jan  8 2013,rst cause:2, boot mode:(1,7)

What could be the problem here?

  [1]: https://i.stack.imgur.com/y4nwl.png
  [2]: https://i.stack.imgur.com/7hwpD.jpg

title: MPU9250 and ESP8266 are not working together with Arduino Uno

Answers: 0


body:
I have two encoders; I connected them to pin 2 and 3 and I want to count the pulses of them to make two DC motors to work until it reaches a specified number of pulses, than stop working. I have finished the code of one encoder, but the other one I can't put in the same code.

    byte pin = 2;
    volatile float elapsed;
    volatile float previous;
    float rpm;
    volatile int pulses;
    volatile bool flag;

    void setup() {
      Serial.begin(9600);
      pinMode(pin, INPUT);
      attachInterrupt(0, elapse, RISING);
      previous = millis();
    }

    void loop() {
      pulses = 0; // reset pulses counter

      attachInterrupt(0, elapse, RISING); // attach interrupt for rpm counter
      delay(500);
      detachInterrupt(0); // detach interrupt for rpm counter

      if (flag == true) {
        attachInterrupt(1, count, RISING); // attach interrupt for pulses counter
        delay(elapsed);
        detachInterrupt(1); // detach interrupt for pulses counter
        flag = false; // reset flag
      }

      rpm = 1000 / elapsed * 60;

      Serial.print("elapsed: "); // print resuslts
      Serial.println(elapsed);
      Serial.print("rpm: ");
      Serial.println(rpm);
      Serial.print("pulses: ");
      Serial.println(pulses);
    }

    void elapse() {
      elapsed = millis() - previous;
      previous = millis();
      flag = true; // set flag to activate pulses counter
    }

    void count() {
      pulses++;
    }

title: How can I get the count of pulses of two encoders on the serial monitor?

Answers: 0


body:
So I've been happily making away with these nodeMCU boards now for a while but I came across a strange issue when updating some code on my board.The problem was that I couldn't flash anymore with Arduino's IDE (OR the NodeFlasher tool)

The error I was getting in Arduino's IDE was:

    warning: espcomm_send_command: didn't receive command response
    warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed

I tried flashing over all the memory with the flash tool but that didn't work, I also tried connecting D3 to 3.3v output, that did nothing. I've also tried holding the flash button down while flashing without any effect.

title: Can't flash ESP8266 anymore (NodeMCU)

Answers: 1

body:
The fix ended up being to use a 220ohm resistor between D3 and GND (It has been pointed out, though I haven't tested it, that just wiring D3 to ground on startup should have the same effect). Then unplugging the USB cable, plugging it back in, then flashing the blink program to test. That got it going. I tried a 10kohm resistor too per some documentation I read but that didn't end up working. Wanted to post in case someone else stumbled on this issue.

**Source**

[GitHub Issue][1]

**Helpful Articles:**

[ESP8266 bootloader modes][2]

[NodeMCU Pinout][3]

  [1]: https://github.com/esp8266/Arduino/issues/2428#issuecomment-413730207
  [2]: https://zoetrope.io/tech-blog/esp8266-bootloader-modes-and-gpio-state-startup
  [3]: https://pradeepsinghblog.files.wordpress.com/2016/04/nodemcu_pins.png?w=616


body:
function `splitter` is designed to get a string of parameters and create a an array of parameters. If only part of parameters were given, the rest of them will get default values.

for example : input string `1,2,3,4` would fill `parameters` array with values `{"1","2","3","4"}`, but  if input string is `1,2`, `parameters={"1","2","20","0"}` while `parameters[3]` and `parameters[2]` were given its default values.

**BUT**

when assigning default values, inside `splitter` the correct values are stored in `parameters` but when using `print_output` function to show `parameters` values - different values are shown.

in output supplied, when input is `1,2`,  default values should be pasted, to `parameters[2]`, and `parameters[3]` , while input is `1,2,3,4` no need to use defaults.

**OUTPUT:**

    Running string 1,2
    param_2 was set to default value:20
    param_3 was set to default value:0
    output:
    1
    2
    0
    0
    Running string 1,2,3,4
    output:
    1
    2
    3
    4

**CODE:**

    #define PARAM_AMOUNT 4
    #define COLOR 1
    #define LED_DELAY 20
    #define BRIGHTNESS  50
    #define LED_DIRECTION 0

    char *parameters[PARAM_AMOUNT] = {"0", "0", "0", "0"};
    int param_def[] = {COLOR, BRIGHTNESS, LED_DELAY, LED_DIRECTION};

    void setup() {
      Serial.begin(9600);
      Serial.println("Running string 1,2");
      splitter("1,2");
      print_output();

      Serial.println("Running string 1,2,3,4");
      splitter("1,2,3,4");
      print_output();
    }

    void splitter(char *inputstr) {
      char * pch;
      int i = 0;

      pch = strtok (inputstr, " ,.-");
      while (pch != NULL)
      {
        parameters[i] = pch;
        pch = strtok (NULL, " ,.-");
        i++;
      }

      //  update default values
      for (int n = i ; n <= PARAM_AMOUNT - 1; n++) {
        sprintf(parameters[n], "%d", param_def[n]);
        Serial.print("param_");
        Serial.print(n);
        Serial.print(" was set to default value:");
        Serial.println(parameters[n]);
        delay(50);
      }
    }

    void print_output() {
      Serial.println("output:");
      for (int n = 0 ; n <= PARAM_AMOUNT - 1; n++) {
        Serial.println(parameters[n]);
      }
    }

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

title: Getting different values inside vs. outside a function while using global array

Answers: 1

body:
It is not a good practice to reserve memory for a string with a constant string. Allocate an array of char arrays with:
```
char parameters[PARAM_AMOUNT][PARAM_LEN];
```

Now with "0" you allocate 2 bytes for each string. The '0' and a terminating 0.

Then in `splitter` function you write 3 bytes into one of the parameters with value "20". This writes outside of the 2 bytes of memory reserved for the string.

`strcpy(parameters[i], pch);` will copy the token returned by `strtok` into your array. `pch` points into `inputstr` and the delimiters in `inputstr` are replaced by 'strtok' with zeros


body: I had a very vague thought. I was wondering if I could I create a dual power supply using an Arduino uno and a nano. Can the  ground terminals of both the boards be shorted and the 5 volt terminals be used as +5v and -5v . Is this possible? Would it damage the board??

title: Dual power supply using Arduino uno and nano

Answers: 1

body:
No, because both 5V terminals are +5V.

If both boards are powered by completely isolated power supplies then you could connect the +5V of one to GND on the other. One will then have all its signals and logic negative to your ground level, but normal compared to its own ground level. Managing it though and keeping things separate (no shared ground between two sets of peripherals, etc), would be tricky. And the moment you plug one into your computer the whole lot could go up in smoke.


body:
I am trying to store and use a pointer to a global function.
The function ***global_f*** returns a String and takes an object as parameter:

    String global_f(Request r){
        // ...
        return "This is it";
    }

I have also declared a type:

    typedef String (*f_type)(Request);

And this is the class that stores the function:

    class T {
        f_type f;

        void setF(f_type fFunc){ // called as: setF(&global_f)
            f = fFunc;
            f(Request());        // This Works
        }

        void callF(){
            f(Request());       // This Freezes the arduino
        }
    }

So I can call ***f*** in the instructor, but it freezes the Arduino in other methods.

***Follow-up:*** It runs in all methods, that the function is being passed as a parameter and stored in the object.
This is where this functions is called in the actual code: GitHub

title: Using pointer to a Global function

Answers: 0


body:
I don't get it. I'm new to Arduino, but not to programming. I don't understand why led pin 13 keeps blinking.

here is my code..

    #include <Servo.h>

    // X servo angle will stay in [min_x, max_x] range
    // Y servo angle will stay in [min_y, max_y] range
    // to be adjusted to the size of your living room

    float min_x = 5;
    float max_x = 50;
    float min_y = 5;
    float max_y = 35;
    int min_freeze = 200;
    int max_freeze = 3000;
    float minimal_movement = 5;

    // finding center of square for starting point
    int random_delay;
    float x_position = min_x + (max_x - min_x)/2;
    float y_position = min_y + (max_y - min_y)/2;
    float x_old_position = x_position;
    float y_old_position = y_position;
    float x_new_position;
    float y_new_position;
    float x_speed;
    float y_speed;
    int movement_time;

    // Instantiating two servos
    Servo x_servo;
    Servo y_servo;
    int pos = 0;

    void setup() {
      y_servo.attach(6);  // attaches the y servo on pin 6 to the servo object
      x_servo.attach(9);  // attaches the x servo on pin 9 to the servo object
      pinMode (13, OUTPUT);
      digitalWrite (13, HIGH);  // switch on  the laser

      //Place the servos in the center at the beginning
      y_servo.write(y_position);
      x_servo.write(x_position);

    }

    void loop() {
      movement_time = random(10,40);
      random_delay = random(min_freeze, max_freeze);
      x_new_position = random(min_x+minimal_movement, max_x-minimal_movement);
      y_new_position = random(min_y+minimal_movement, max_y-minimal_movement);

      if( (y_new_position > y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
        y_new_position = y_new_position + minimal_movement;
      }  else if ( (y_new_position < y_old_position) && (abs(y_new_position - y_old_position) < 5 )) {
        y_new_position = y_new_position - minimal_movement;
      }

      if( (x_new_position > x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
        x_new_position = x_new_position + minimal_movement;
      }  else if ( (x_new_position < x_old_position) && (abs(x_new_position - x_old_position) < 5 )) {
        x_new_position = x_new_position - minimal_movement;
      }

      x_speed = (x_new_position - x_old_position)/movement_time;
      y_speed = (y_new_position - y_old_position)/movement_time;
      for (pos = 0; pos < movement_time; pos += 1) {
          x_position = x_position + x_speed;
          y_position = y_position + y_speed;
          x_servo.write(x_position);
          y_servo.write(y_position);
        delay(10);
      }
      x_old_position = x_new_position;
      y_old_position = y_new_position;
      delay(random_delay);

    }

Nowhere in this sketch, the line "digitalWrite (13, LOW);" is contained, yet I am unable to keep the LED on solid without blinking when the Arduino is looping. I've other people do it, with this code, I don't get what I'm missing!

Windows 7 64bit, Arduino Uno board, Arduino 1.8.9 program

title: Stop led from blinking when running

Answers: 1

body:
I tried your sketch on an Arduino Uno, with no servos connected, and the LED on pin 13 did not blink.

DataFiddler makes a good point in their comment. To be sure you are actually uploading the sketch, try uploading the `Blink` sketch that comes with the IDE. Change the delays from 1000ms to 200ms then upload it. The difference in flash rates should confirm or deny the ability to successful upload sketches.

You don't say which servos you are using, so I'll assume they are SG90. I'm not sure if the data sheet for every SG90 servo is the same, but if you [look at this one][1], SG90 Specifications, you'll see the "stall current" can be between 570mA and 730mA, **each**. If you are powering them from the Uno, it can't supply that much current. Another limiting factor is the computer's USB maximum current output, (if you are powering the Uno with a USB port). FWIW, my computer can only provide 500mA per USB.

I would suggest powering the servos with a separate power supply, then see what happens.

  [1]: https://arduino.stackexchange.com/questions/49727/servo-causes-disconnection/49755#49755


body:
I have a NodeMCU (ESP8266) board that I use to control some devices over the internet. To be able to access it I have to enable port forwarding on my router and set the port manually like in the image below:

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

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

But with Smart Plugs (that use a cloud based app) I don't have to set up anything on my router. I am only required to type my Wi-Fi password. So my question is how Smart Plugs are accessed over the router (why they don't need manual port forwarding setting), and how to apply this to my NodeMCU so I don't have to set port forwarding manually.

title: Why Smart Plugs don't require setting port forwarding on router and how to accomplish this with NodeMCU (ESP8266)

Answers: 1

body:
Port forwarding is required to allow a device outside your router to access a device inside a router that performs NAT (Network Address Translation).

When a NodeMCU is acting as a simple server to respond to requests, it is inside your network, and so the port-forwarding is required so that your phone or computer on the Outside can access it.

However, for the cloud-based "smart" devices, it is different. The smart device opens a connection from itself to a server (the cloud) outside your network. In this case, the router understands that a new two-way connection is created between the cloud server and your smart device.

The only communication to your smart device is from the cloud server to the smart device. If you have an app on your mobile device or computer, that app or website only accesses the cloud server, when then passes the instruction on to your smart device. Reverse direction for status info from the smart device to your app, etc.

These smart devices rely on the infrastructure of their creators to continue to work. There are no LAN-to-LAN connections from the client to the device. Everything goes through the Internet to the remote cloud server, and back.

Many home routers support a protocol called uPNP, that allows a device inside the network to request port forwarding to itself. Some routers require this to be explicitly enabled, because it's a security risk to allow any device to be able to open holes in your firewall/router.

To have your NodeMCU device do this, look for libraries for ESP8266 that implement uPNP. I did a quick search and found https://github.com/ofekp/TinyUPnP though I cannot vouch for it's effectiveness or safety.


body:
I have built a kitchen timer and it is supposed to spend most of its life in sleep mode in order to save power. I am using the SSD1306Ascii library (SPI) by William Greiman.

In this library I have found hints to power on and off commands but I don't know how to use them:

    /** Set Display off. */
    #define SSD1306_DISPLAYOFF 0xAE
    /** Set Display on. */
    #define SSD1306_DISPLAYON 0xAF
From what I could gather from the web, I need to re-initialize the display after turning it off and on again. But before I take care of that (which should be simple as it is done in setup anyway) I need to find out how to use these commands.

Would you help out a rookie?

title: How can I put this display SSD1306 to sleep?

Answers: 0


body:
I think i've reached my limit. I can't get Wire to work between an Uno or ESP8266 or ESP32S. On the Uno I had them connected like SDA via Uno SDA -> ESP32 GPIO21 SCL via Uno SCL -> ESP32 GPIO22.

I also tried flipping them like this:

- SDA via Uno SDA -> ESP32 GPIO22
- SCL via Uno SCL -> ESP32 GPIO21

Connections are as follows:

- SDA via ESP32 GPIO21 -> ESP8266 GPIO4
- SCL via ESP32 GPIO22 -> ESP8266 GPIO5

I also tried flipping them, as follows:

- SDA via ESP32 GPIO21 -> ESP8266 GPIO5
- SCL via ESP32 GPIO22 -> ESP8266 GPIO4

I have present a 4.7 kOhm pull-up resistor from SDA and SCL to +3.3 V.

All these combinations led to nil result on I2C bus scanners. I tried 5 scanners and 3 Wire libs. I tried having the ESP32 as slave because I heard the ESP8266 won't work as slave. I know I'm doing something wrong but can't figure it out, I've been at it all day.

title: Wire doesn't work between Uno & ESP32S & ESP8266

Answers: 0


body:
I have a rock solid voltage on my analog input with ADC values jumping around by about 15% on the Serial monitor and LCD display
Never had anything like this before

Seeeduino V4.2
pinMode(A1, INPUT_PULLUP);
volt = analogRead(A1)

Am I the proud owner of a faulty board? ( wish I had a spare one to test )

regards
Wilfried

title: Unstable analog results

Answers: 0


body:
I think my if statement can't be read here in my program. The RGBs should light up and change color when the potentiometer is turned but instead the RGBs just light up immediately and change color simultaneously. How do I fix this?

    int POT1=A0;
    int POT2=A1;
    int POT3=A2;
    int Red1=9;
    int Green1=10;
    int Blue1=11;
    int Red2=3;
    int Green2=5;
    int Blue2=6;
    int sValue1=0;
    int sValue2=0;
    int sValue3=0;
    int oValue1=0;
    int oValue2=0;
    int oValue3=0;
    int value1=0;
    int value2=0;
    int value3=0;
    int timer(250);

    void setup() {
     Serial.begin(9600);
     pinMode(Red1,OUTPUT);
     pinMode(Green1,OUTPUT);
     pinMode(Blue1,OUTPUT);
     pinMode(Red2,OUTPUT);
     pinMode(Green2,OUTPUT);
     pinMode(Blue2,OUTPUT);

    }

    void loop() {

    sValue1=analogRead(POT1);
    sValue2=analogRead(POT2);
    sValue3=analogRead(POT3);

    oValue1=map(sValue1,0,1023,0,255);
    oValue2=map(sValue2,0,1023,0,255);
    oValue3=map(sValue3,0,1023,0,255);

    if ((sValue1<=127)&&(sValue2<=127)&&(sValue3<=127));
    {
      setColor1(0,255,255); //red
      setColor2(255,255,0); //blue
      delay(timer);
      value1=0;
      value2=0;
      value3=0;

    }

    if ((sValue1<=127)&&(sValue2<=127)&&(sValue3>127));
    {
      setColor1(255,255,0); //blue
      delay(timer);
      setColor2(255,0,255); //green
      delay(timer);
      value1=0;
      value2=0;
      value3=1;
    }

    if ((sValue1<=127)&&(sValue2>127)&&(sValue3<=127));
    {
      setColor1(255,0,255); //green
      delay(timer);
      setColor2(0,255,255); //red
      delay(timer);
      value1=0;
      value2=1;
      value3=0;
    }

    if ((sValue1<=127)&&(sValue2>127)&&(sValue3>127));
    {
      setColor1(0,255,255); //red
      delay(timer);
      setColor2(255,0,255); //green
      delay(timer);
      value1=0;
      value2=1;
      value3=1;
    }

    Serial.print("POT 1=");
    Serial.print(value1);
    Serial.print("\t POT 2=");
    Serial.print(value2);
    Serial.print("\t POT 3=");
    Serial.print(value3);

    if ((value1==0)&&(value2==0)&&(value3==0))
    {
     Serial.print("\t RGB1=");
     Serial.print("RED");
     Serial.print("\t RGB2=");
     Serial.print("BLUE");
    }

    else if ((value1==0)&&(value2==0)&&(value3==1))
    {
      Serial.print("\t RGB1=");
      Serial.print("BLUE");
      Serial.print("\t RGB2=");
      Serial.println("GREEN");
      Serial.println(" ");
    }

    else if ((value1==0)&&(value2==1)&&(value3==0))
    {
      Serial.print("\t RGB1=");
      Serial.print("GREEN");
      Serial.print("\t RGB2=");
      Serial.println("RED");
      Serial.println(" ");
    }

    else if ((value1==0)&&(value2==1)&&(value3==1))
    {
      Serial.print("\t RGB1=");
      Serial.print("RED");
      Serial.print("\t RGB2=");
      Serial.println("GREEN");
      Serial.println(" ");
    }

    }

    void setColor1(int red1, int green1, int blue1){
      {
        analogWrite(Red1,red1);
        analogWrite(Green1,green1);
        analogWrite(Blue1,blue1);
      }
    }

    void setColor2(int red2, int green2, int blue2){
      {
        analogWrite(Red2,red2);
        analogWrite(Green2,green2);
        analogWrite(Blue2,blue2);

      }
    }

title: RGBs and Potentiometers

Answers: 1

body:
I haven't traced through your if statement logic in detail to see what you are trying to do, BECAUSE I found that you have statements like this:

    //            Get rid of this semicolon in every if statement.
    //            |
    //            V
    if (condition); {
        //        ^
        //        |

        //Code that will always be executed
    }

You should **NOT** have a semicolon after an if statement like that. That says "if (condition) then do nothing" (A semicolon creates a blank "do-nothing" statement that becomes the code that is executed if the if statement is true. Then the code in the braces gets executed every time.)

It is parsed as:

    if (condition) <empty_statement;>

    {
        code that always executes
    }

That is one of the hidden "nasties" of C and it's close cousins like C++, Java, and Objective-C. Another nasty is typing:

    if (a=b)

...when you mean `if (a==b)`. (The first version puts the value of b into a, and then evaluates b as a boolean. If it's 0, the if statement is treated as false. If it's non-zero, the if statement is evaluated as true.

Another one is the fall-through cases in C `switch` statements. If you forget to add a `break` statement at the end of each case it falls through to the next case.


body:
I've been trying to get an Arduino and ESP8266 to communicate with each other over serial. The ESP8266 uses the `Serial` class for communications, while the Arduino uses `SoftwareSerial`.

The problem is that when I try to send data from the Arduino to the ESP8266,  only the first character of the string sent gets received by the ESP8266. For example, if I send a string "leather", the ESP8266 only receives an 'l'. Both devices are operating at 38400 baud, although I have tried 9600 baud with similar results (apparently `SoftwareSerial` is more reliable at lower baud rates).

Here is the relevant code that's running on both devices:

Arduino code:

    #include <stdlib.h>
    #include <SoftwareSerial.h>

    #define COMMAND_TILT                'c'
    #define SOFTWARE_SERIAL_BAUD_RATE   38400
    #define ESP_RX                      8
    #define ESP_TX                      9

    SoftwareSerial esp(ESP_RX, ESP_TX);

    void setup()
    {
        ...
        esp.begin(SOFTWARE_SERIAL_BAUD_RATE);
        ...
    }

    void loop()
    {
       if (esp.available() > 0) {
            String data;
            while (esp.available() > 0) {
                data += (char) esp.read();
            }

            char command = data.charAt(0);
            data.remove(0, 1);
            int value = data.toInt();
            char buf[STR_BUF_LEN];

            switch (command) {
                 case COMMAND_TILT:
                     ...
                     sprintf(buf, "%c%d", COMMAND_TILT, value);
                     esp.write(buf);
                     break;
                 ...
            }
        }

        delay(100);
    }

    ...

ESP8266 code:

    #define SERIAL_BAUD_RATE 38400

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

    void loop()
    {
        ...

        if (Serial.available() > 0) {
            String data;
            while (Serial.available() > 0) {
                data += (char) Serial.read();
            }

            char command = data.charAt(0);
            data.remove(0, 1);

            // problem: now, data.c_str() is blank when it should contain an integer in string format

            ...

            delay(100);
        }
    }

    ...

If it helps to know, I'm running an MQTT client on the ESP8266 and controlling some steppers and relays on the Arduino.

title: Problems with serial communication from Arduino to ESP8266

Answers: 1

body: The cause of the issue was that the ESP was reading `char`s too quickly, meaning that it would give up before the next `char` could be sent from the Arduino. To fix the issue I simply added a 10 ms delay between each `Serial.read()` call on the ESP.


body:
Hi guys I am new to this language and i just tested the code to control a servo motor
Can anybody help me please ? here is the code

    void setup() {

      servo_test.attach(3);
      pinMode(9, INPUT);

    }

    void loop() {

     if ( digitalRead (9 == HIGH)) {

       for(angle = 0; angle < 180; angle += 5)    to 180 degrees
      {
        servo_test.write(angle);
        delay(5);
      }

      delay(4000);
      for(angle = 180; angle>=1; angle-=5)      to 0 degrees
      {
        servo_test.write(angle);               specified angle
        delay(5);
      }

        delay(4000);
    }

    }

It is just like the arduino completely ignore the if statement and start the loop wheter pin 9 is in high or low state  even if  i wire it directly to gnd

title: arduino is skipping the if statement

Answers: 1

body:
In your code this line:

     if ( digitalRead (9 == HIGH)) {

...is likely passing the function "digitalRead()" the value zero as "9 == HIGH" is likely false.

Likely what you want to do is check if the value returned by the function "digitalRead()" is high.  Try:

     if ( digitalRead (9) == HIGH) {

...instead.


body:
I bought a few MCP4651 dual 8 bit I2C pots for a project. After browsing the arduino libraries and finding nothing,"No big deal" I thought to myself ... I've already written I2C libraries for other parts that were much more complicated! (e.g: ADS1219 24 bit ADC)! so just load up the datasheet and watch the memory maps and commands! ok, there are some stuff on page 49 which seem useful! oh boy was I ever wrong! this data sheet looks like nightmare! the worst documentation for any I2C device I've seen so far. The commands I wrote based on that did absolutely nothing!

I found a code for controlling an I2C pot in one of the arduino examples which is something like this:

    #include <Wire.h>

    void setup() {
      Wire.begin(); // join i2c bus (address optional for master)
    }

    byte val = 0;

    void loop() {
      Wire.beginTransmission(44); // transmit to device #44 (0x2c)
      // device address is specified in datasheet
      Wire.write(byte(0x00));            // sends instruction byte
      Wire.write(val);             // sends potentiometer value byte
      Wire.endTransmission();     // stop transmitting

      val++;        // increment value
      if (val == 64) { // if reached 64th position (max)
        val = 0;    // start over from lowest value
      }
      delay(500);
    }

I decided to just try it and see what happens (changed the address to the correct value) and crazy enough it actually worked! so I hacked this piece of code to get the first pot to work!

    void setPot0(int n){
      if (n>256) n=256;
      if (n<0) n=0;
      Wire.beginTransmission(address);
      if (n<256){
        Wire.write(0x00);
        Wire.write(n);
      } else{
        Wire.write(0x01);
        Wire.write(0);
      }
      Wire.endTransmission();
    }
and somehow this works! I still can't find this pattern in any of the pages on datasheet, but hey! it works so I'm not gonna complain about that?
I still haven't managed to make the pot1 to work, only pot0 ... if you can make sense of how the commands and data bytes should be like, please help me. It's so much more clear in T.I datasheets; you just use the command to write to the register you want and they detail what each register does:
[![enter image description here][1]][1]
[![enter image description here][2]][2]

Edit: here is a link to the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/22096b.pdf

  [1]: https://i.stack.imgur.com/Ss0he.jpg
  [2]: https://i.stack.imgur.com/c8GJw.jpg

title: I2C potentiometer mess

Answers: 1

body:
The registers are listed in table 4-1. Clearly enough.

The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.

Two bytes are needed to set a register.  The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register).  The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data.  Following that are the lower 8 bits of data.

So to write a pot 0 value of 0x23 you would write:

    0x00 0x23

To write a pot 1 value of 0x65 you would write:

    0x10 0x65

To write a pot 1 value of 0x13D you would write:

    0x11 0x3D

You can make a simpler function to wrap it for you:

    void writePot(uint8_t address, uint8_t pot, uint16_t val) {
        Wire.beginTransmission(address);
        Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
        Wire.write(val & 0xFF);
        Wire.endTransmission();
    }