body:
Hey guys I am a noob when it comes to data structures and storing types of data, I have been recently working on a project where I needed to store long term data for later retrieval. I decided to buy a Adafruit 10$ 32kb i2c fram Which works, it can store a byte Of data per address which I can successfully do, I can also read those bytes on any address no problem.

One issue I first came across was storing floats into the chip which only took bytes, After googling I managed to spit a float using a union successfully and also storing those in a 4 byte array. Now I did this with 3 different float values which means every 4 bytes stored is basically one split float value.

The second issue is how do I retrieve this data in an organized way and also as a float. I found out you can use a union to do the opposite as well. But how do I tell my code to read every 4 bytes and convert back to float?

Is there a system that can allow me to store data in a structured way using the arduino? Like a time stamped data using an external rtc? Such that when I click retrieve it will print that data in an organized fashion.

title: Arduino I2C external 32Kb fram data organization

Answers: 1

body:
It'll be easier if you use a `struct`, not a `union`. Store all the data you want to preserve in a struct, then cast a pointer to it to be a `byte` pointer and just treat it as an array of bytes and read and write those bytes to the FRAM.

The `union` you were using explicitly did the same thing, but it's not easy to scale to multiple items.

Some caveats about what you can safely keep in the `struct`:
 - do not store pointers in it. A `char` array is fine because the entire array will take up space in the `struct`. A `char *` is not because all you'll save is the value of the pointer, not what it points at.

 - do not store objects (like `String`) in it. You don't know (and shouldn't know) how the object is composed internally. If need to use objects, they should have `serialize` and `deserialize` methods which would store or restore the contents of an object into an array of bytes which you could then store or restore with the FRAM.

Also remember that the C/C++ `sizeof` function (used below) tells you the size of thing at compile-time. So if you use it on a `struct` it will tell you the number of bytes it takes to store the `struct`. If you use it on a `char *`, it will tell you the number of bytes in a pointer to a `char`, not the number of bytes in the C string that the `char *` points at. If you use it on an object - like `String str; sizeof(str);` - it will tell you how many bytes it takes to store the `String` object, which will include the length of the string it stores.

Psuedo-code follows. There are more compact ways to write this; I'm aiming for clarity here.

```
#include <Arduino.h>

struct program_data {
  float first_thing;
  unsigned long second_thing;
  char third_thing[55];
  char fourth_thing;
  uint16_t fifth_thing;
} data;

void save_data(struct program_data *data_ptr) {
  byte *ptr = (byte *)data_ptr;

  for(size_t i = 0; i < sizeof(struct program_data); i++)
    store_byte_in_fram(ptr[i], i);
}

void restore_data(struct program_data *data_ptr) {
  byte *ptr = (byte *)data_ptr;

  for(size_t i = 0; i < sizeof(struct program_data); i++)
    retrieve_byte_from_fram(ptr[i], i);
}

// call when you want to save your data
  save_data(&data);

// call when you want to restore your data
  restore_data(&data);

```


body:
I have configured a hc-05 bluetooth module as master and a hc-06 module as slave an since the LED on the hc-05 is blinking in a 2s delay they should be paired but no matter what I do I can't send data between the two Arduinos.

Here is the code for the slave
(I use the example code from the EasyTransfer module github repo: https://github.com/madsci1016/Arduino-EasyTransfer):

        #include <Wire.h>
        #include <EasyTransferI2C.h>

        //create object
        EasyTransferI2C ET;

        struct RECEIVE_DATA_STRUCTURE{
          //put your variable definitions here for the data you want to receive
          //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
          int16_t blinks;
          int16_t pause;
        };

        //give a name to the group of data
        RECEIVE_DATA_STRUCTURE mydata;

        //define slave i2c address
        #define I2C_SLAVE_ADDRESS 9

        void setup(){
          Wire.begin(I2C_SLAVE_ADDRESS);
          //start the library, pass in the data details and the name of the serial port. Can be Serial, Serial1, Serial2, etc.
          ET.begin(details(mydata), &Wire);
          //define handler function on receiving data
          Wire.onReceive(receive);

          pinMode(13, OUTPUT);

        }

        void loop() {
          //check and see if a data packet has come in.
          if(ET.receiveData()){
            //this is how you access the variables. [name of the group].[variable name]
            //since we have data, we will blink it out.
            for(int i = mydata.blinks; i>0; i--){
              digitalWrite(13, HIGH);
              delay(mydata.pause * 100);
              digitalWrite(13, LOW);
              delay(mydata.pause * 100);
            }
          }
        }

        void receive(int numBytes)

here is the code for the master:

    #include <Wire.h>
    #include <EasyTransferI2C.h>

    //create object
    EasyTransferI2C ET;

    struct SEND_DATA_STRUCTURE{
      //put your variable definitions here for the data you want to send
      //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
      int16_t blinks;
      int16_t pause;
    };

    //give a name to the group of data
    SEND_DATA_STRUCTURE mydata;

    //define slave i2c address
    #define I2C_SLAVE_ADDRESS 9

    void setup(){
      Wire.begin();
      //start the library, pass in the data details and the name of the serial port. Can be Serial, Serial1, Serial2, etc.
      ET.begin(details(mydata), &Wire);

      pinMode(13, OUTPUT);

      randomSeed(analogRead(0));

    }

    void loop(){
      //this is how you access the variables. [name of the group].[variable name]
      mydata.blinks = random(5);
      mydata.pause = random(5);
      //send the data
      ET.sendData(I2C_SLAVE_ADDRESS);

      //Just for fun, we will blink it out too
       for(int i = mydata.blinks; i>0; i--){
          digitalWrite(13, HIGH);
          delay(mydata.pause * 100);
          digitalWrite(13, LOW);
          delay(mydata.pause * 100);
        }

      delay(5000);
    }

title: Is it possible using a hc-05 bluetooth module as master and pair it to a hc-06 module?

Answers: 0


body:
Actually I need to make HTTPS post request using SIM7000 and ESP32 but the available libraries don't have a function for HTTPS post request, I wanna make this request using AT Commands. I need a example code to send AT Commands to sim7000e using esp32 hardware serial or software serial whichever is the best.

I am using the botlectics library but it has function only for HTTP GET/POST not HTTPS. I am looking for HTTPS request using Sim7000. As there is no function for HTTPS in botletics I thought of sending AT Commands using hardware serial from esp32 to SIM7000 . For example,

```HardwareSerial mySerial(1) ,```

```mySerial.begin(9600,Serial_8N1,13,12)```

And I have connected SIM7000 TX RX with esp32 GPIO 13,12.

then I send AT commands like

```mySerial.print("AT+HTTPINIT\r");```

And I connect FTDI to UOR AND UOT of esp32 which makes Serial.... So no anything done with Serial is with esp32 and writing to mySerial means Sim7000.

I have done this before but with arduino and GSM module through Software Serial and it worked fine.

I think I am missing something in case of ESP32 and Sim7000. In which I need help.

title: I need an example of how to send AT COMMANDS to SIm7000E GPS+LTE module from ESP32 and reading those response in Serial monitor

Answers: 0


body:
Hi everyone I am beginning learn coding and the second language English. I have small project I use **Arduino uno , esp8266 , dht11 , lcd I2C and use blynk app** in my project I have the code and work probably when WiFi ON but I have question How I can get the information data from dht to lcd without open the WiFi. Now I get information ( Temp and humidity ) on LCD when WiFi ON only. **How I can make Temp and humidity display on LCD with and without WiFi.**
```
#include <BlynkSimpleShieldEsp8266.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);
char auth[] = "*******************************";
char ssid[] = "***********";
char pass[] = "*********";
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2, 3); // TX, RX
#define ESP8266_BAUD 9600
ESP8266 wifi(&EspSerial);
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  EspSerial.begin(ESP8266_BAUD);
  Blynk.begin(auth, wifi, ssid, pass);
  dht.begin();
}

void loop()
{
  LCD();
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  Blynk.virtualWrite(V1, t);
  Blynk.virtualWrite(V2, h);
}
void LCD()
{
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(" ******************");
  lcd.setCursor(3, 1);
  lcd.print("TEMP: ");
  lcd.print(t);
  lcd.setCursor(3, 2);
  lcd.print("HUM : ");
  lcd.print(h);
}
```

title: How I can send data information without work WiFi to LCD?

Answers: 1

body:
`Blynk.connected()` returns true when hardware is connected to Blynk Server, so you can guard Blynk code with

```
if( Blynk.connected() ){
  // do Blynk things here
}

// Update the LCD anywhere outside of the above "if" statement.
```


body:
This thought came into my mind on thinking about smartwatches.

Although those I saw on YouTube are really good, they don't seem to provide a real experience of a real smartwatch - one that has an OS embedded in it. If some code in Arduino C/c++ can be compiled into some binary code that works on being called from the flash memory (where the main program resides), is there a possibility that we will be able to make an OS for Arduino ?

title: If the code used for Arduino can be embedded into a permanent , callable memory, is there a way to create an OS for Arduino that runs on call?

Answers: 1

body:
An AVR-based Arduino is a poor choice for writing an "OS" in the modern sense. It's just too resource constrained. It doesn't have enough RAM, it doesn't have enough flash memory, it's too slow, it doesn't have protected memory or paging, it doesn't have video display, it doesn't have a file system, and on and on.

If you look at an Apple II, something like Apple DOS or ProDos gives you an idea of the sort of thing you can do (minus the video output.)

If you want to develop something like a smart watch an ARM processor is a much better choice. It packs a lot more performance into a small package. You might pick an ARM based Arduino, but you would be fighting against the lack of an OS, the lack of preemptive multi-tasking, etc.

As an alternative, a Raspberry Pi has just about everything you need. It doesn't have as many hardware interfacing options as an Arduino, but a LOT more processing power. Likewise, UNIX is a better choice as the basis for the OS for such a device. It is a protected memory OS that is made to run on relatively modest hardware.


body:
I have a Generic code for some IOT devices which vary in some parameters ( lets say it is only its MQTT name and subscriptions).

Since I use OTA to update sketch, I'm looking for a way to A) write those parameters into the ESP32/ ESP8266 FS, and B) They will survive an update.

My only solution come into mind is using an SD card which does not get erased after OTA, and I'm looking for a way doing it not involving SD or external memory.

Guy

title: Store & retrieve parameters after sketch update

Answers: 1

body:
There is no need for an SD card.
You can write all relevant parameters into a file in SPIFFS (e.g. json if you like) before starting the OTA update. During initialization you read the file and set the parameters accordingly.
SPIFFS does not get erased when doing an update (at least that's true for the OTA library that I'm using). If it does get erased in your case, there probably is an option in the OTA lib to disable flash erase, just like there is the same option when uploading a sketch via serial.


body:
How do I wire an L293D motor controller chip to a nodeMCU?<br>
I have tried to follow the instructions from this tutorial: [lastminuteengineers.com][1]

One problem. I don't have a 5v pin?
Are there any alternative ways to wire this?

All of the other tutorials i see, only say to use a special other motor driver board with an L293D embedded in it, and with extras connected to the board.

  [1]: https://lastminuteengineers.com/l293d-dc-motor-arduino-tutorial/

title: How to wire L293D chip to a nodeMCU?

Answers: 1

body: I figured it out. I am putting a logic level converter On the 3v pin to step it up to 5v


body:
For one of my projects, I need to transmit data from NodeMCU to my Arduino Nano, in real time, I used S-Bus, but it quite unsatisfies me, as, slight latency is taking place.
I am transmitting a JSON file, with 4 signed 16 bit integeres.

Now,I need to know, what is the fastest and most reliable way to transmit data from NodeMCU to an Arduino Nano. Any detailed description, or even suggestion will be very much helpful. Thanks in advance !

title: Fastest Communication from NodeMCU to Arduino Nano

Answers: 1

body:
If it comes to speed and reliability you have to choose an interface that is handled in hardware on both sides. For the arduino nano you have the following options (nodeMCU supports all of them):

 - UART:
    - not very fast (order of 10kbit/s), but it's full-duplex (asynchronous communication in both directions)
    - implementation is trivial due to `Serial.h`
    - long distance (order of meters)
 - I2C:
    - not very fast either (order of 100kbit/s), but not full-duplex
    - implementation is straight forward because both slave and master are implemented in arduino library
    - only over short distance (order of cm)
 - SPI:
    - quite fast (>1Mbit/s), full-duplex
    - implementation might require some experience (as far as I know, slave mode is not supported by `SPI.h`)
    - long distance (order of meters)

Which of those is the best option still depends on your specific requirements, but personally I like SPI very much because it is very fast and stable.


body:
The code I used was this

    int servo = 5;
    int angle;

    void setup() {

      pinMode(servo, OUTPUT);

    }

    void loop() {

      for (angle = 0;angle<180;angle++){

        digitalWrite(servo, HIGH);
        delayMicroseconds((angle*(11))+365);
        digitalWrite(servo,LOW);
        delay(65);
      }

      for (angle = 179;angle>0;angle--){

        digitalWrite(servo, HIGH);
        delayMicroseconds((angle*(11))+650);
        digitalWrite(servo,LOW);
        delay(65);

    }
    }

as u can see I have set the delay after a particular step to be 65 milliseconds but it won't work, any delay greater than 64 milliseconds do not work and the motor just stops rotating.

what is the reason for this??

title: Why delay of more than 64 millisecond stops the servo motor from rotating? I am not using "Servo.h" instead i am just managing the length of pulse

Answers: 1

body:
A servo motor doesn't just require a single pulse to send it to a specific angle. It requires a constant stream of pulses at the right frequency for it to track what the angle should be.

By sending one pulse you're just hinting where it might like to go to, then stopping. It's never going to get there, unless you keep sending those pulses fast enough.

Also if you don't send pulses then the servo will go into a "low power sleep mode" where it's not actively driving the output and it will go "floppy" where you can move the servo by hand.

Typically you need to send pulses at about 50Hz, which is one pulse every 20ms. Many servos will be more forgiving, but if you send too slowly they just won't know what to do.

If you want to be handling the pulses yourself then you need to do it in the right way.  That is:

1. Send a pulse of your desired length
2. Delay for 20ms minus your desired length
3. Go to 1 until your desired elapsed time has been reached.

For example:

```
for (angle = 0; angle<180; angle++){
  uint32_t ts = millis();
  while ((millis() - ts) < 100) { // 100ms delay
    digitalWrite(servo, HIGH);
    delayMicroseconds((angle * 11) + 650);
    digitalWrite(servo,LOW);
    delayMicroseconds(20000 - ((angle * 11) + 650));
  }
}
```

That won't be exact, owing to the latency of the loop instructions, but it will be close enough.


body:
Is there a way to define class variables in the constructor or in a method rather than at the top of the document?

I have the following code in my custom library:

    #include "DHT.h"

    // DHT settings.
    #define DHTPIN 7 // Digital pin connected to the DHT sensor.
    #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
    DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor.

    void DhtLib::doSomeStuff() {
      dht.begin();
      float temp = dht.readTemperature();
      ...
    }

I would like to be able to set the pins with a function. But for this to work I have to find a way to define the `dht` variable in a different place than at the top of the document within the `// DHT settings.`. Best would be in a method such as:

    void DhtLib::begin(int dhtPin) {
      DHT dht(dhtPin, DHTTYPE);
    }

This works, but only within this function. I need this to be accessible in the entire document, not just a single function.

How can I achieve that?

**EDIT 1:**

Entire code of the custom DhtLibrary.h file:

    #ifndef DhtLibrary_h
    #define DhtLibrary_h

    #if (ARDUINO >= 100)
      #include "Arduino.h"
    #else
      #include "WProgram.h"
    #endif

    class DhtLib {
      private:
        DHT dht;
        float readTemperatureFromDHT();
        float readHumidityFromDHT();
        float calculateHeatIndex(float temperature, float humidity);

      public:
        // Constructor.
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}

        // Methods.
        void begin();
        String getHumiTempJson();
    };

    #endif

The error with this above code is:

    In file included from /home/myuser/Documents/Codes/temperature-control/slave2-arduino/slave2-arduino.ino:2:0:
    DhtLibrary.h:12:5: error: 'DHT' does not name a type
         DHT dht;

title: Instantiate class in the constructor rather in the top end?

Answers: 1

body:
There's numerous ways of doing this. The best is probably to have a DHT object as a class property and set it up with an *initializer list*:

```
#include "DHT.h"

class DhtLib {
    private:
        DHT dht;

    public:
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}
        void begin();
        void doSomeStuff();
};

void DhtLib::begin() {
    dht.begin();
}

void DhtLib::doSomeStuff() {
    float temp = dht.readTemperature();
}

DhtLib thing(7);

void setup() {
    thing.begin();
}

void loop() {
    thing.doSomeStuff();
}
```


body:
I will show a connection diagram between my Arduino Uno and a DSC HS2032 panel (alarm system).

The DSC panel uses 12V and I don't know the voltage fluctuation.

The yellow and green are RX/TX ports.

Github file: https://github.com/taligentx/dscKeybusInterface/blob/master/examples/Arduino/KeybusReader/KeybusReader.ino

DIAGRAM (I assume the vertical "+--+" means a simple "OR" connection):

      DSC Aux(+) --- Arduino Vin pin

      DSC Aux(-) --- Arduino Ground

                                     +--- dscClockPin (Arduino Uno: 2,3)
      DSC Yellow --- 15k ohm res ----|
                                     +--- 10k ohm resistor --- Ground

                                     +--- dscReadPin (Arduino Uno: 2-12)
      DSC Green ---- 15k ohm res ----|
                                     +--- 10k ohm resistor --- Ground

I need to make sure this diagram is SAFE, and will not overheat or do something risky to my Arduino.

Why is this circuit not going to burn my Arduino if it is using 12V?

title: Is this circuit risky for an Arduino Uno?

Answers: 1

body:
That circuit is fine as long as the input signals don't go above 12.5V.  You can protect it further by adding a 5.2V zener diode across each of the signals as they enter the Arduino:

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

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

<!-- End schematic -->

> Why is this circuit not going to burn my Arduino if it is using 12V?

Because it uses a [voltage divider](https://en.wikipedia.org/wiki/Voltage_divider) to reduce the voltage to 4.8V.


body:
I have a quirky question today.

I have an Arduino MEGA 2560 with a very simple setup. It's connected to my pc over usb, and has one device connected on its onboard TX/RX2 port group. Whenever I open the COM port on my pc I see a short spike in voltage on the TX2 pin. An analogous behavior happens on even the simplest sketches so I don't think it's the library I'm using to talk to this device.

With the sketch below instead of a short spike in voltage, the TX2 line stays high and when the pc's COM port is opened that TX2 line drops to 0v for maybe a half second.

Not super relevant info about device

```
It's a Noritake GU140X32F-7000 display. The mfg website doesn't list it's model directly but the
info on the 'B' variant, and it's supplied AVR code, work just fine.

MFG Website for this model>> https://noritake-vfd.com/gu140x32f-7000b.aspx
Code Library>> https://www.noritake-elec.com/codeLibrary.php#gu7000
```

Relevant bare-minimum code to see this effect on an oscilloscope connected
GRD <-> AVR Ground, POS <-> Pin16(TX2)
```
void setup() {
  Serial.begin(115200); // Connection to computer
  Serial2.begin(38400); // Connection to TX2 pin 16
  Serial2.write('akjlahsdkjahsdkjlhasdkjhaskldjhaksjhd');
}

uint8_t serialByte = 0;
void loop() {
  if (Serial.available() > 0) {
    serialByte = Serial.read();
  }
}
```

What happens, which I don't want happening, is after I've had the Arduino draw to the Noritake screen, and I open or reopen the COM port from my pc to the Arduino, the screen blanks itself. Doesn't matter if I use PUTTY, python's serial library with

`ser = serial.Serial('COM4', 115200, R timeout=0,parity=serial.PARITY_NONE, rtscts=1)`

or Serial Port Monitor's trial version from https://www.com-port-monitoring.com/ via the send dialog - it happens either way.

Especially weird is I don't see data going over this COM port in the Serial Monitor software when the COM port is opened and yet my oscilloscope (fairly crappy DSO138) catches a spike in voltage happen the moment this serial line is opened from my pc. When I use the Noritake library the TX line is normally low when there's no data, whereas the Arduino built in Serial2 line is normally high until there's data. Then when I connect it goes low for about a half second. The code Noritake uses to communicate over this serial line is a bit odd, not actually using the Serial or Stream built in classes, instead opting to write data manually to this port and only including these two external libraries.
```
#include <avr/pgmspace.h>
#include <util/delay_basic.h>
```

What causes Serial2 to go low when my PC opens the COM port to Serial on my Arduino? What can I do to prevent it from writing to Serial2?

title: Strange Arduino Serial Behavior

Answers: 1

body:
As to why this happens: connecting to the Arduino with the built in USB port would wipe the display because the Arduino would reset and re-initiate the display initialization routine. The spike in current was actually the initialization signal. In the bare minimum sketch the signal going high, low, then back high was again due to the Arduino resetting.

The solution I'm going with is just changing how I connect to my Arduino with python by adding `dsrdtr = 1` to my serial declaration. I tested this and my Arduino no longer resets, and uploading sketches is not impacted.

```
# Python 3.7.5
import serial
ser = serial.Serial('COM4', 115200, timeout=0, parity=serial.PARITY_NONE,
                   rtscts=1, dsrdtr = 1)
```


body:
For my head mouse project which is based on the voice recognition module V3.1 for left click, double click, right-click operations, I am facing a problem. I am using 433Mhz Radio Frequency one-way Transceiver for sending data. When I use the MPU 6050 accelerometer and gyroscope for mouse cursor movement and the voice recognition module together on only one Arduino board, the mouse cursor moves smoothly and the voice commands work smoothly. But when I use the 433Mhz RF one-way transmitter for one Arduino board to calculate the mouse movement and figure out the voice command to send it in a wireless manner and receive the values and voice commands using the receiver module of the rf433 Mhz, the mouse cursor starts to lag. It doesn't move smoothly. Please help me solve the problem. The code and circuit diagram are given below:

[![RF 433 Mhz Transmitter Circuit of Arduino Micro with Elechouse Voice Recog Module V3.1 and MPU6050 motion gyro-accel IMU with][1]][1]

[![RF 433Mhz receiver circuit using Arduino micro][2]][2]

**Transmitter.ino**

      /*433 MHz RF Module Transmitter Demonstration 1
      RF-Xmit-Demo-1.ino
      Demonstrates 433 MHz RF Transmitter Module
      Use with Receiver Demonstration 1

      DroneBot Workshop 2018
      https://dronebotworkshop.com
    */

    // Include RadioHead Amplitude Shift Keying Library
    #include <RH_ASK.h>
    // Include dependant SPI Library
    #include <SPI.h>
    #include <SoftwareSerial.h>
    #include "VoiceRecognitionV3.h"
    #include <Mouse.h>
    #include <Wire.h>
    #include <I2Cdev.h>
    #include <MPU6050.h>

    VR myVR(8,9);    // 9:RX 8:TX

    uint8_t records[7]; // save record
    uint8_t buf[64];

    MPU6050 mpu;
    int16_t ax, ay, az, gx, gy, gz, oax, oay, oaz, ogx, ogy, ogz;
    int16_t vx, vy;
    //
    #define leftRecord    (0)
    #define rightRecord   (1)
    #define doubleRecord  (2)

    /**
      @brief   Print signature, if the character is invisible,
               print hexible value instead.
      @param   buf     --> command length
               len     --> number of parameters
    */
    void printSignature(uint8_t *buf, int len)
    {
      int i;
      for(i=0; i<len; i++){
        if(buf[i]>0x19 && buf[i]<0x7F){
          Serial.write(buf[i]);
        }
        else{
          Serial.print("[");
          Serial.print(buf[i], HEX);
          Serial.print("]aurav");
        }
      }
    }

    /**
      @brief   Print signature, if the character is invisible,
               print hexible value instead.
      @param   buf  -->  VR module return value when voice is recognized.
                 buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
                 buf[1]  -->  number of record which is recognized.
                 buf[2]  -->  Recognizer index(position) value of the recognized record.
                 buf[3]  -->  Signature length
                 buf[4]~buf[n] --> Signature
    */
    void printVR(uint8_t *buf)
    {
      Serial.println("VR Index\tGroup\tRecordNum\tSignature");
      Serial.print(buf[2], DEC);
      Serial.print("\t\t");

      if(buf[0] == 0xFF){
        Serial.print("NONE");
      }
      else if(buf[0]&0x80){
        Serial.print("UG ");
        Serial.print(buf[0]&(~0x80), DEC);
      }
      else{
        Serial.print("SG ");
        Serial.print(buf[0], DEC);
      }
      Serial.print("\t");

      Serial.print(buf[1], DEC);
      Serial.print("\t\t");
      if(buf[3]>0){
        printSignature(buf+4, buf[3]);
      }
      else{
        Serial.print("NONE");
      }
      Serial.println("\r\n");
    }

    struct dataStruct{
      int16_t moveX;
      int16_t moveY;
      int flag;
      }myData;

    byte tx_buf[sizeof(myData)] = {0};

    // Create Amplitude Shift Keying Object
    RH_ASK rf_driver;
    int flag = 15;

    void setup()
    {

       /** initialize */

      Wire.begin();
      mpu.initialize();
      if (!mpu.testConnection()) {
        while (1);
        }

      myVR.begin(9600);
      Serial.begin(115200);
      Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");

      if(myVR.clear() == 0){
        Serial.println("Recognizer cleared.");
      }else{
        Serial.println("Not find VoiceRecognitionModule.");
        Serial.println("Please check connection and restart Arduino.");
        while(1);
      }

      if(myVR.load((uint8_t)leftRecord) >= 0){
        Serial.println("leftRecord loaded");
      }

      if(myVR.load((uint8_t)rightRecord) >= 0){
        Serial.println("rightRecord loaded");
      }

      if(myVR.load((uint8_t)doubleRecord) >= 0){
        Serial.println("doubleRecord loaded");
      }

        // Initialize ASK Object
        rf_driver.init();
        if(!rf_driver.init()) Serial.println("Init failed");

    }

    void loop()
    {

      int ret;

      ret = myVR.recognize(buf, 50);
        const char *msg = "Welcome to the Workshop!";

      if(ret>0){

      switch(buf[1]){

        case leftRecord:
        flag = 0;
        break;

        case rightRecord:
        flag = 1;
        break;

        case doubleRecord:
        flag = 2;
        break;

        default:
        flag=3;
        Serial.println("Record function undefined");
        break;
        }
        /** voice recognized */
        printVR(buf);
      }

      mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

      oax = ax+72;
      oay = ay-382;
      oaz = az-505;
      ogx = gx+99;
      ogy = gy-29;
      ogz = gz-50;

      vx = gx/200;
      vy = -gz/200;
      myData.moveX = vx;
      myData.moveY = vy;
      myData.flag = flag;

      memcpy(tx_buf, &myData, sizeof(myData));
      byte bufSize = sizeof(myData);
      Serial.println("movX\tmovY\tmovZ\toax\toay\toaz\togx\togy\togz\tvx\tvy:");
      Serial.print(myData.moveX, HEX);
      Serial.print("\t");
      Serial.print(myData.moveY, HEX);
      Serial.print("\t");
      Serial.print(myData.flag, HEX);
      Serial.print("\t");
      Serial.print(oax, DEC);
      Serial.print("\t");
      Serial.print(oay, DEC);
      Serial.print("\t");
      Serial.print(oaz, DEC);
      Serial.print("\t");
      Serial.print(ogx, DEC);
      Serial.print("\t");
      Serial.print(ogy, DEC);
      Serial.print("\t");
      Serial.print(ogz, DEC);
      Serial.print("\t");
      Serial.print(vx, HEX);
      Serial.print("\t");
      Serial.println(vy, HEX);

      rf_driver.printBuffer("Buffer values [vx, vy, status flag respectively]: ", tx_buf, bufSize); //each value is 16 bit. and serail monitor will show in 8 + 8 = 16 bit format
        rf_driver.send((uint8_t *)tx_buf, bufSize);
        //Serial.println();
        rf_driver.waitPacketSent();

        flag = 15;
        delay(1);

    }

**Receiver.ino**

    // Include RadioHead Amplitude Shift Keying Library
    #include <RH_ASK.h>
    // Include dependant SPI Library
    #include <SPI.h>
    #include <Mouse.h>
    #include <Wire.h>
    #include <I2Cdev.h>
    #include <MPU6050.h>

    #define leftRecord    (0)
    #define rightRecord   (1)
    #define doubleRecord  (2)
    // Create Amplitude Shift Keying Object
    RH_ASK rf_driver;

    struct dataStruct{
      int moveX, moveY, flag;
      }myData;

    void setup()
    {
        // Initialize ASK Object
        Wire.begin();
        rf_driver.init();
        // Setup Serial Monitor
        Serial.begin(115200);
        if(!rf_driver.init()) Serial.println("Init failed");
    }

    void loop()
    {
        // Set buffer to size of expected message
        uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
        uint8_t buflen = sizeof(buf);
        // Check if received packet is correct size
        if (rf_driver.recv(buf, &buflen))
        {
          int i;

          // Message with a good checksum received, dump it.
      rf_driver.printBuffer("Got:", buf, buflen);
            memcpy(&myData, buf, sizeof(myData));
            Serial.println("");

            Serial.print("moveX: ");
            Serial.print(myData.moveX);

            Serial.print("  moveY: ");
            Serial.print(myData.moveY);

            Serial.print("  Command Status: ");
            Serial.print(myData.flag);

          // Message received with valid checksum
          Serial.print(" Message Received: ");
          Serial.println((char*)buf);

          Mouse.move(myData.moveX, myData.moveY);

      if(myData.flag!=15){

      switch(myData.flag){

        case leftRecord:
        Mouse.click(MOUSE_LEFT);
        delay(10);
        break;

        case rightRecord:
        Mouse.click(MOUSE_RIGHT);
        delay(10);
        break;

        case doubleRecord:
        Mouse.click(MOUSE_LEFT);
        Mouse.click(MOUSE_LEFT);
        delay(10);
        break;
        default:
        break;
        }

        }
    }
    }

  [1]: https://i.stack.imgur.com/KnDSd.jpg
  [2]: https://i.stack.imgur.com/oJAtD.jpg

title: How to Fix mouse cursor lag on voice & movement based head mouse in wireless setting?

Answers: 1

body:
In general, you want to stream some data. and the mouse lag is one of the main obstacles in data streams; lag. so many classic causes such as buffer over-runs and timing problems come to mind.

The cheap 433MHz modules are not a good choice in case of streams. they lack any robust protocol, ACKing and security.

I would do this things to make it better:

 - use a better transmitter. maybe the cheap nRF24L01 ones.
 - use a bigger buffer
 - use two threads on the transmitter side. (e.g. use something like [this][1], but two threads). one thread to collect data and writing it to a buffer, the next one to send data using nrf. furtunately, the nRF24 can send up to 32Bytes in one buffer transmission and the SPI interface is fast enough to fill it's buffer as quick as possible.
 - if you have to, use another thread to calculate movements from MPU6050. so you don't have to read it continuouesly and send all that raw data to reciever. you may use some interpolation on the receiver side though.

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
Hello I'm trying to send some Structs such as:

    typedef struct __attribute__ ((__packed__)) myohw_command_set_mode {
        myohw_command_header_t header; ///< command == myohw_command_set_mode. payload_size = 3.
        uint8_t emg_mode;              ///< EMG sensor mode. See myohw_emg_mode_t.
        uint8_t imu_mode;              ///< IMU mode. See myohw_imu_mode_t.
        uint8_t classifier_mode;       ///< Classifier mode. See myohw_classifier_mode_t.
    } myohw_command_set_mode_t;

To another device via BLE using the Arduino BLE library.
I have the services and characteristics all set up correctly.
My problem is that arduino BLE .writeValue() function expects some specific formats and i'm not quite sure the best way to convert this struct to one of them.

      int writeValue(const uint8_t value[], int length);
      int writeValue(const void* value, int length);
      int writeValue(const char* value);
      int writeValue(uint8_t value);
      int writeValue(int8_t value);
      int writeValue(uint16_t value);
      int writeValue(int16_t value);
      int writeValue(uint32_t value);
      int writeValue(int32_t value);

What format should i use? And what is the best way to cast the Struct to the format?

Thanks,

title: Write a Struct using ArduinoBLE library

Answers: 1

body:
> What format should i use?

    int writeValue(const uint8_t value[], int length);

> And what is the best way to cast the Struct to the format?

    writeValue((uint8_t *)&myStruct, sizeof(myStruct));


body:
```
Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

IROM   : 228624          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1248  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 688   ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 24880 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 257316 bytes (26%) of program storage space. Maximum is 958448 bytes.

Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Reghunaath A A\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.2/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

_

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
```
I'm getting the above stated error message while I'm trying to upload a code to esp8266 via an arduino(I've removed the ATMEGA32 from my arduino). Sometimes it gets uploaded without a problem(very rarely) but mostly the upload fails.
I connected rx of arduino to rx of esp and same for tx too. 3.3v of arduino to enable and vcc of esp. graund of arduino to ground of esp and gpio0.

The code that I'm trying to upload:
```
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forevervoid lop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}
```
My settings:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/fv7X7.png
 EDIT: Also, I want to add one more thing when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading

title: I'm getting an error while uploading my code to esp8266 via an arduino (FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error)))

Answers: 1

body:
You need to set esp 8266 to flash mode.
Please connect en PIN to Gnd pin.
Then flash again.


body:
Pretty similar to what is described [here](https://arduino.stackexchange.com/questions/67102/power-supply-affecting-sensor-readings-esp8266-and-jsn-sr04t-2-0#) I have the strange problem that my sensor readings are affected by the type of power supply I use.

Whenever I connect my D1 mini through USB with laptop everything works fine. The readings make sense and are quite accurate.
But as soon as I disconnect it from the laptop and use a USB power supply (I tested different ones) the readings do not make sense anymore.

I also tried to apply the sketch to a NodeMCU board. The results are the same. So I assume it has something to do with either the sensor or the ESP 12E.

Any suggestions?

title: Wemos D1 mini and JSN-SR04T-2.0: Type of power supply affects the sensor readings

Answers: 1

body: Try a different supply or computer, it sounds like that one has a lot of ripple and or noise on it.  Not all USB power supplies are clean and some do not have much filtering.


body:
I am doing a project and using NodeMCU ESP8266. My project includes sensors for UART, I2C and 4 interrupts. I need to read the data from these sensors and get these data via microUSB in real time. While reading about NodeMCU ESP8266 there are so many points that came across and have certain questions.

1. Do flash uses GPIO6-11 all the time? Can we use any of these pins for our purpose? What if someone needs an SPI communication, as these pins are locked by flash.
2. Can I use GPIO-0 (flash pin) for my purpose, as after flashing the MCU the pin will get free.
3. Do CP2102 uses GPIO 1 and GPIO 3? Can I use these pins for my purpose? (Given I need the data via USB, which I guess comes through CP2102)
4. Can I receive the sensor data from SoftUART bus and get that data to my computer via USB?

I am confused from the articles given over internet. I request if anyone knows how these work, please explain.

Thank you

title: NodeMCU ESP8266

Answers: 1

body:
> Do flash uses GPIO6-11 all the time? Can we use any of these pins for our purpose? What if someone needs an SPI communication, as these pins are locked by flash.

It is Quad SPI. The CS pins for this SPI interface are controlled by low level code. So you can't use this pins as GPIO and they have limited use as SPI too. If the flash access is set to normal SPI, the two pins io 9 and io 10 used for quad mode can be used as GPIO.

> Can I use GPIO-0 (flash pin) for my purpose, as after flashing the MCU the pin will get free.

You can use io 0 as GPIO. Only make sure it is HIGH at boot. The bootloader reads it at boot to determine if it should go to flashing mode. Other boot config pins are io 2, it must be HIGH at boot and io 15, which must be LOW at boot.

> Do CP2102 uses GPIO 1 and GPIO 3? Can I use these pins for my purpose? (Given I need the data via USB, which I guess comes through CP2102)

Pins io 1 and io 3 are wired to the USB chip and used for Serial. They can be used as io pins, if you don't need Serial communication over them. Serial in esp8266 Arduino can be swapped to different set of pins for use with a serial device. For output printing you can use Serial1 which has only TX. To [relay this output to USB][1] bridge io 2 (Serial1 TX) to io 4 (Serial TX wired to USB).

> Can I receive the sensor data from SoftUART bus and get that data to my computer via USB?

You can use SoftwareSerail or the trick mentioned above.

see [NodeMCU pins][2]

  [1]: https://arduino.stackexchange.com/questions/76299/nodemcu-wiring-for-serial1/76309#76309
  [2]: https://arduino.stackexchange.com/questions/75704/what-are-the-best-gpio-pins-to-use-for-my-project/75706#75706


body:
I am newbie. In my application Arduino Due is configured as Master and Arduino Uno as Slave. I need to transfer 24-bit Hexadecimal data of about 79-registers to slave device. At the slave end in serial monitor window I would like to display the transmitted data. I have developed an array at slave side, and I am comparing the master data with slave one. I have divided the 24-bit data into 3 Bytes. I will attach the Master and Slave codes below. I am getting Invalid data in serial monitor window as the data (Hexa Decimal) transmitted by Master is converted into decimal format internally and I think this was the reason I am not able to print the Valid data in serial monitor window.

Any help will be greatly appreciated. Thanks in Advance.

**MASTER Code**

    #include <SPI.h>

    SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
    const uint8_t ss = 10;

    //pinMode(10, OUTPUT)
    void setup() {
      pinMode(ss, OUTPUT);

      SPI.begin();
    SPI.beginTransaction(mySettting);

     digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0x1C);
      SPI.transfer(0x25);
      SPI.transfer(0x00);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0x08);
      SPI.transfer(0x08);
      SPI.transfer(0x01);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0x00);
      SPI.transfer(0x05);
      SPI.transfer(0x02);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0x42);
      SPI.transfer(0x06);
      SPI.transfer(0x03);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0x43);
      SPI.transfer(0x0A);
      SPI.transfer(0x04);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0xC8);
      SPI.transfer(0x00);
      SPI.transfer(0x05);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0x02);
      SPI.transfer(0xC8);
      SPI.transfer(0x6C);
      SPI.transfer('$');
      delay(100);
      digitalWrite(ss, HIGH);

    digitalWrite(ss, LOW);
      SPI.transfer('@');
      SPI.transfer(0xB2);
      SPI.transfer(0x40);
      SPI.transfer(0x07);
      SPI.transfer('$');
      SPI.transfer('&');
      delay(100);
      digitalWrite(ss, HIGH);
    SPI.endTransaction();
    }

    void loop() {
    }

**SLAVE Code**

    #include <SPI.h>
    #include <stdio.h>
    #include <string.h>
    int buff[100] = {0x001C2500,0x00080801,0x00000502,0x00420603,0x430A04,0xC80005,0x02C806,0xB24007};

    uint32_t buff_1 [100];
    volatile byte indx;
    volatile boolean process;
    int i = 0;
    uint32_t var_byte = 0x00000000;
    uint32_t var_byte_1 = 0x00000000;
    int byte_pos = 0;
    short int status_1 = 0;

    void setup (void) {
       Serial.begin (115200);
       pinMode(MISO, OUTPUT); // have to send on master in so it set as output
       SPCR |= _BV(SPE); // turn on SPI in slave mode
       indx = 0; // buffer empty
       process = false;
       SPI.attachInterrupt(); // turn on interrupt
       memset(buff_1,'\0',sizeof(buff_1));
    }

    ISR (SPI_STC_vect) // SPI interrupt routine
    {
       byte c = SPDR; // read byte from SPI Data Register

       if(c == '@')
       {
          var_byte = 0x00000000;
          byte_pos = 2;
       }
       else if(c == '$')
          buff_1 [indx++] = var_byte;
       else if(c == '&')
          process = true;
       else
       {
          var_byte_1 = 0x00000000;
          var_byte_1 = (var_byte_1 | c) << byte_pos;
          var_byte |= var_byte_1;
          byte_pos--;
       }

    }
    void loop (void) {
       if (process) {
          process = false; //reset the process
          status_1 = 0;
          for(i=0;i<79;i++)
          {
            if (buff[i]==buff_1[i])
            {
              Serial.println ("Valid data_1");
            }
            else
            {
              status_1 = 1;
              break;
              //Serial.println ("Inavlid data");
            }
          }
          if (status_1 == 0)
            Serial.println ("Valid data");
          else
            Serial.println ("Inavlid data");
          indx= 0; //reset button to zero
          memset(buff_1,'\0',sizeof(buff_1));
       }
    }

title: Arduino Due Master Programming

Answers: 0


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

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

I have connected pin D2 on my arduino nano to high, and tried it out with an arduino c program and it works.  However, when I load standard firmata onto the the controller from the arduino IDE and try the following python program:

```
import pyfirmata

board = pyfirmata.Arduino('/dev/ttyUSB0')

for x in range(2,14):
    print("%s %s" % (x, board.get_pin("d:%s:i" % x).read()))
```

I get this:

```
$ venv/bin/python test.py
2 None
3 None
4 None
5 None
6 None
7 None
8 None
9 None
10 None
11 None
12 None
13 None
```

I can write digital pins with fermata and pyfirmata, but I can't _read_.

I have also tried this:

```
import pyfirmata

board.digital[2].mode = pyfirmata.INPUT
board.digital[3].mode = pyfirmata.INPUT

for x in range(2,14):
    print("%s %s" % (x, board.digital[x].read()))
```

and other combinations, and always get None

(disconnecting the wire in the picture doesn't change anything either)

----

I have also just repeated the experiment with an arduino uno and get the same result

----

so I guess my questions are:
 - Can anybody spot anything obvious that I am doing wrong?
 - Can anybody confirm that pyfirmata input ever works?
 - What did you do that I am not doing?

title: digital input pins on arduino nano with standard firmata and pyfirmata are always 'None'

Answers: 1

body:
"None" indicates that there is no data to be found by read() because the incoming serial stream has never been serviced.  Launch an Iterator to start a new Python thread that services the serial port in the background.

    it = pyfirmata.util.Iterator(board)
    it.start()


body: im new to arduino and am making an arduino car. the motor driver shield covers the ports (am connecting an ultrasonic sensor) and i know that we can connect it to the 'holes' on the motor driver shield (l293d) but i do not have a solder or header pins. there's a lockdown and i cannot get any of those. can i make a makeshift arrangement? (refer img): it is a little loose, is there any fix using jumper wires or any other arrangement? please let me know!![enter image description here](https://i.stack.imgur.com/XkQ7z.jpg)

title: motor driver shield covering ports for ultrasonic sensor

Answers: 0


body:
We are building a circuit based on ATMega328* that :

1. Reads 32 current transducers, multiplexed into one Analog Input,
2. Reads 12 voltage transducers, multiplexed into one Analog Input,
3. Reads 6 temperature sensors, multiplexed into one Analog Input,
4. Manipulates all the readings with some math (like scaling, averaging etc.),
5. Calculates new variables (power, crest factor, etc.),
6. Tracks trends (max/min/avg) of certain (calculated) readings,
7. Stores some events (peaks/dips - max/min values) etc. with time stamps from RTC,
8. Generates Alarm Flags (by comparing readings to software-set thresholds),

The circuit should be connected as a ModBus Device (Slave) to an existing
Modbus network with several other devices on an RS485 interface.

The circuit should communicate all these calculated values and alarms
as well as some other info, like peak/max values with date and
time stamps that were recorded at their time of occurrence, to the
Modbus Master. We have the freedom of allocating the register numbers
and their formats etc. (Modbus Map) to the controller's vendor (SAUTER).
For example we tell them Register 30001 is the current sensor x,
30002 is voltage sensor y, etc.

We think that sending time stamps (of certain events) will be based on
"agreed-upon" coding of register values (MM, DD, YYYY, etc.) and the
same for alarms (to be sent as hex codes).

We have searched for libraries and got really confused from the
multitude of libraries out there, as well as the lack of documentation -:)

Can you please kindly help us :
select the proper Arduino Modbus Slave Library that :
1. Has MAX485 support,
2. Assigns Modbus registers to any arbitrary variables,
3. Issues Exception Responses to Modbus requests (e.g. non-existing registers
or un-supported Function Codes.
4. Complies to Modbus Standards
5. Has a manual !!

We found the "yaacov" library on Github but it assigns registers directly to "Pins".
Also we looked at its "issues" and one of them was very serious : in which frames
coming from the Master with corrupted CRC gets responded to and causes collision
with other slaves. We dont like that ! as it indicates that the library was not tested
in true industrial environment.

We also found that the Library at :

https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/

somewhat fits to our requirements, however it lacks the RS485 support, and more
important, it has no documentation.

We really appreciate any kind support.

* The ATmega328 will be probably replaced with a larger CPU, but we are still
in development phase.

Thank you.

title: Arduino Modbus Slave Library Needed

Answers: 2

body:
With my post approaching one month without a single reply  :smiley-confuse: !
(for whichever reason) I would like to post for those who may need this library :

-------------------------------------------------------------------------------------
https://drive.google.com/file/d/0Bx5wWRfN_z7oMDlZMDhWbXM2VFU/view
-------------------------------------------------------------------------------------

The library is based on the original one written by Jason Vreeland [CodeRage]
Released 3/7/2010 under GNU license

and was used (and possibly modified) by "jhottell" on electronhacks.com :

https://electronhacks.com/2014/04/arduino-modbus-plc-rtu/

The major difference is the use of RS485.

I have written code and tested it on an "UNO" which worked perfectly with more
than one ModBus Slave Simulator under windows, including DAQ Factory which
is a professional package used in actual industry.

body:
## This is an awesome Modbus slave and Master Library

Required this library [<ModbusRtu.h>][1]

    #include <ModbusRtu.h>
    unsigned long TIME = 0;
    unsigned long LASTTIME = 0;
    unsigned long INTERVAL = 5000;

    int i = 0;
    // data array for modbus network sharing
    uint16_t au16data[16] = {
      3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, 11 };

    /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  port : serial port
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
    Modbus slave(1,Serial,0); // this is slave @1 and RS-232 or USB-FTDI

    void setup() {
      Serial.swap();
      Serial.begin( 19200 ); // baud-rate at 19200
      Serial1.begin( 19200 );
      slave.start();
    }

    void loop() {

      if ((millis() - TIME) > INTERVAL) {
        i++;

        if(i == 16){
          i = 0;

          for (int ii = 0; ii < 16; ii++)
          {
            au16data[ii] = 0;
          }
        }

        au16data[i] = 1;

        TIME = millis();
      }

      slave.poll( au16data, 16 );
    }

  [1]: https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino


body:
Is it valid configuration using hardware I2C pins:

[![I2c bus configuration][1]][1]

Especially: can `NanoEvery` initialize communication with `DS2482`, while it is slave for `Mega2560`? Using Wire library or should I use software I2C when talking to `Mega2560` and leave `NanoEvery` as master to `DS2482`?

*Needed to use additional Nano due to long times of reading temperatures connected to DS2482 that blocks Mega controller.*

[Graph source][2]

  [1]: https://i.stack.imgur.com/Iwfoy.png
  [2]: https://bit.ly/2OH0I4X

title: 2xArduinos, 2xDevices, I2C setup

Answers: 0


body:
I have an ESP8266 in a project.  It's specifically this [ESP8266 SMT Module - ESP-12F][1] item.  It's been working great with OTA, but I realized belatedly that I didn't change the flash settings when I started compiling through the Arduino IDE several versions ago.  I had been using the setting "1 MB (FS:64KB OTA:~470KB)", and I've updated OTA over multiple versions with the same basic structure of firmware and using the same server-side set-up.

I can no longer update with that setting because my compiled sketch is now over the OTA size limit.  My chip actually has 4 MB, however, so this limit is artificial.  I tried changing to "4 MB (FS:2 MB OTA:~1019KB)", and that works under the following test conditions:

 1. I compile the "old" program with the 4-MB settings and I re-upload the old program via wired connection.
 2. I compile the "new" program that's to come via OTA with those same 4-MB settings.

That's fine for a test, but I already have one of these chips "deployed" in a location where it's hard to access it.  I'd like to update that deployed chip OTA while also changing the flash partition.  I'm willing to lose any files stored outside of the program itself.  So I'd like instead to have:

 1. A deployed, OTA-enabled chip with firmware running on the 1-MB partition structure noted above:
 2. (Any intermediate step needed)
 3. OTA update to new firmware that has been compiled with the 4-MB partition structure.

I'm willing to upload a dummy sketch at "Any intermediate step needed" to work around the current size of the sketch, but, after some experimentation, OTA seems to fail when the partition structure is different regardless of the size of the binary.

That's consistent with #2 in the answer here: https://arduino.stackexchange.com/questions/74750/esp8266-ota-issue, but that older question took a different direction with the OP and the #2 point there is stated without any detail.  I understand that in a broad sense, the prior answer covers my case, but I'm looking for more detail on the specific aspect of the flash partition settings.  Especially for these related questions:
 - Is there any work-around strategy available to change the flash partitioning between different versions served OTA?
 - If no, is the limitation determined by the software in the current OTA framework in the public libraries, or is it somehow fundamental to how the program is laid out in the hardware memory?

In theory at least, it seems like I ought to be able to force the new program to be written OTA at the same location that it would have been written had the old program also had the 4-MB partition. (Again noting that I'm willing to lose any other data in the flash to make this update work.)

  [1]: https://www.adafruit.com/product/2491

title: ESP8266 OTA update with different flash size settings?

Answers: 1

body:
The basic problem is that when you upload over OTA you don't upload the partition structure.

The ESP32's flash is split into a number of "partitions" or areas.  It might look something like:

```
+----+-+-------------+-------------+---------------------+
|BOOT|P|OTA Program 1|OTA Program 2| SPIFFS              |
+----+-+-------------+-------------+---------------------+
```

When you upload over UART you upload all that structure, and that structure can be changed.  When you upload over OTA you only upload one of "OTA Program 1" or "OTA Program 2". One of those is active and the other is inactive. You upload to the inactive one and then at the next reboot that becomes the active one. This allows the system to confirm that the program has been written correctly before running it to reduce the chances of bricking a device in the field.

Because of this you can *never* upload anything that doesn't fit into one of the OTA program partitions.

One risky option which you would have to do thorough local testing of first, is to write a program which, when executed, will change the partitioning. You would have to make sure that it runs in the lower OTA partition so that the inactive one is the one that gets both moved and expanded, which may take a little trial and error.

Once that has happened you should be able to upload a larger OTA program into the new, bigger, inactive OTA segment.

But that's only supposition and it's not something I have ever done or heard of anyone doing.


body:
Can I use OTA along with FreeRTOS tasks on ESP32. I ask this because in the following  [example][1] OTA seems to be enabled if FreeRTOS is disabled. Can for example upload firmware that runs on both cores over OTA?
Example taken from OTA [template project][2] by Andrea's Speiss

  [1]: https://github.com/SensorsIot/ESP32-OTA/blob/master/0TA_Template_Sketch/0TA_Template_Sketch.ino
  [2]: https://github.com/SensorsIot/ESP32-OTA

title: Esp32: is OTA compatible with FREERTOS

Answers: 2

body:
You can't *not* use FreeRTOS. The whole ESP-IDF is based around it. The Arduino `setup()` and `loop()` run in their own FreeRTOS thread.

If you "turn off" FreeRTOS then nothing will work.

Whatever that "template" is from it's of no use to you.

body:
I was also believing that it is not possible but I handle it thanks to this post below;

https://github.com/SensorsIot/ESP32-OTA/issues/8

I applied what ever shared and it works like a charm together both FreeRTOS and OTA features.

As summary you need to create 2 custom header which includes your wifi credentials and OTA function. The remaining is same mostly.

credentials.h

    #pragma once
    const char* mySSID = "SSID of your AP";
    const char* myPASSWORD = "Password of your AP";

OTA.h

    #ifdef ESP32
    #include <WiFi.h>
    #include <ESPmDNS.h>
    #else
    #include <ESP8266WiFi.h>
    #include <ESP8266mDNS.h>
    #endif

    #include <WiFiUdp.h>
    #include <ArduinoOTA.h>

    #if defined(ESP32_RTOS) && defined(ESP32)
    void ota_handle( void * parameter ) {
      for (;;) {
        ArduinoOTA.handle();
        delay(3500);
      }
    }
    #endif

    void setupOTA(const char* nameprefix, const char* ssid, const char* password) {
      // Configure the hostname
      uint16_t maxlen = strlen(nameprefix) + 7;
      char *fullhostname = new char[maxlen];
      uint8_t mac[6];
      WiFi.macAddress(mac);
      snprintf(fullhostname, maxlen, "%s-xxx", nameprefix, mac[3], mac[4], mac[5]);
      ArduinoOTA.setHostname(fullhostname);
      delete[] fullhostname;

      // Configure and start the WiFi station
      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);

      // Wait for connection
      while (WiFi.waitForConnectResult() != WL_CONNECTED) {
        Serial.println("Connection Failed! Rebooting...");
        delay(5000);
        ESP.restart();
      }

      // Port defaults to 3232
      // ArduinoOTA.setPort(3232);

      // No authentication by default
      // ArduinoOTA.setPassword("admin");

      // Password can be set with it's md5 value as well
      // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
      // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

      ArduinoOTA.onStart([]() {
        String type;
        if (ArduinoOTA.getCommand() == U_FLASH)
          type = "sketch";
        else // U_SPIFFS
          type = "filesystem";

        // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
        Serial.println("Start updating " + type);
      });

      ArduinoOTA.onEnd([]() {
        Serial.println("\nEnd");
      });

      ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
      });

      ArduinoOTA.onError([](ota_error_t error) {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("\nAuth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("\nBegin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("\nConnect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("\nReceive Failed");
        else if (error == OTA_END_ERROR) Serial.println("\nEnd Failed");
      });

      ArduinoOTA.begin();

      Serial.println("OTA Initialized");
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());

    #if defined(ESP32_RTOS) && defined(ESP32)
      xTaskCreate(
        ota_handle,          /* Task function. */
        "OTA_HANDLE",        /* String with name of task. */
        10000,            /* Stack size in bytes. */
        NULL,             /* Parameter passed as input of the task */
        1,                /* Priority of the task. */
        NULL);            /* Task handle. */
    #endif
    }

OTA Template sketch.ino

    #define ESP32_RTOS  // Uncomment this line if you want to use the code with freertos only on the ESP32
                        // Has to be done before including "OTA.h"

    #include "OTA.h"
    #include "credentials.h"

    void setup() {
      Serial.begin(115200);
      Serial.println("Booting");

      setupOTA("TemplateSketch", mySSID, myPASSWORD);

      // Your setup code
      /*  Example
      pinMode(2, OUTPUT);
      */
    }

    void loop() {
    #ifdef defined(ESP32_RTOS) && defined(ESP32)
    #else
      ArduinoOTA.handle();
    #endif

      // Your code here
      /* Example
      digitalWrite(2, HIGH);
      delay(500);
      digitalWrite(2, LOW);
      delay(1000);
      */
    }


body:
I'm making a project that requires me to display Chinese and Japanese characters on an LCD. However, the 16x2 LCD display I have does not seem to support displaying Chinese and Japanese characters.

If I do something like `lcd.print("おはよう世界");` or `lcd.print("简体中文测试");`, it seems to display just a bunch of jumbled random characters (which I am assuming have their character values add up to the values of the characters in the code).

How can I get my LCD to display Chinese and Japanese characters?

Or, if there's no way to do it without buying a new one that supports it, where can I buy one?

title: How can I get my LCD display to display Chinese and Japanese characters?

Answers: 2

body:
Displaying Kanji or Chinese characters is way beyond the ability of an LCD that displays 5 pixel by 7 pixel characters.

To understand the limitations, take a piece of graph paper and draw out a set of 5x7 rectangles. See if you can define ANY recognizable Japanese or Chinese characters on your graph paper.

Maybe a couple of characters? (Then again, maybe not.)

You need a display with a lot more resolution, like an OLED graphics display. You are also struggling against a microcontroller that doesn't have support for Unicode. It's just not up to the job. You'd be much better off with a Raspberry Pi and a screen like a smart-phone color LCD screen. Install Linux and you can have native support for Unicode.

As others have pointed out, hiragana or katakana would be more practical, and there are some low-res LCDs that support those characters.

body:
Your LCD uses a single byte for the character to display, so there are < 256 characters possible. 8 of them are userdefineable, the others are predefined in the LCD-ROM.

The Arduino IDE uses utf-8 code, which takes more than a single byte for all non-ascii characters like in your "おはよう世界".

Even if the character set contains the ones you want to display, you need an escape sequence to have them properly in your print statement.


body:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

c:\program files (x86)\arduino\hardware\tools\avr\bin\../lib/gcc/avr/7.3.0/../../../../avr/bin/ar.exe: unable to rename 'core\core.a'; reason: Permission denied

exit status 1

Error compiling for board Arduino Uno.

continue error is coming having downloading over more than 15 times. How can i overcome this problem

title: regarding ardunio error

Answers: 0


body:
I am using MPU6050 as a part of IMU of my drone, and I wrote this program for Arduino Nano to fetch the orientation of the MPU6050 module in 3D space. And that works perfectly fine, but when I uploaded this exact code to a NodeMCU, the output started getting increased only, i.e., whenever there's any change of orientation of the module, the output, instead of showing the specific orientation, gets increased on and on. Can you please help me out with interfacing the MPU6050 with my NodeMCU. I am providing the program underneath.

```
#include <Wire.h>
const int MPU = 0x68; // MPU6050 I2C address

char status;                // Declaring all the necessary variables
double T, P;
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll_sensor, pitch_sensor, yaw_sensor;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;

void setup() {
  Serial.begin(115200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        // end the transmission
  calculate_IMU_error();  // Call this function if you need to get the IMU error values for your module
  delay(20);
}
void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 14, true); // Read 6 registers total, each axis value is stored in 2 registers

  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value

  // Calculating roll_sensor and pitch_sensor from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * (180 / PI)) - AccErrorX;
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * (180 / PI)) - AccErrorY;

  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 14, true); // Read 4 registers total, each axis value is stored in 2 registers

  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;

  // Correct the outputs with the calculated error values
  GyroX = GyroX - GyroErrorX;
  GyroY = GyroY - GyroErrorY;
  GyroZ = GyroZ - GyroErrorZ;

  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + (GyroX * elapsedTime); // deg/s * s = deg
  gyroAngleY = gyroAngleY + (GyroY * elapsedTime);
  yaw_sensor =  yaw_sensor + (GyroZ * elapsedTime);

  // Complementary filter - combine acceleromter and gyro angle values
  roll_sensor = (0.94 * gyroAngleX) + (0.06 * accAngleX);
  pitch_sensor = (0.94 * gyroAngleY) + (0.06 * accAngleY);

  // Print the values on the serial monitor
  Serial.print("                   roll_GY: "); Serial.print(roll_sensor);
  Serial.print("         pitch_GY: "); Serial.print(pitch_sensor);
  Serial.print("         yaw_GY: "); Serial.print(yaw_sensor);
  Serial.println();

}
void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 300 times
  while (c < 300) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * (180 / PI)));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * (180 / PI)));
    c++ ;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 300;
  AccErrorY = AccErrorY / 300;
  c = 0;
  // Read gyro values 300 times
  while (c < 300) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);

    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();

    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }

  //Divide the sum by 300 to get the error value
  GyroErrorX = GyroErrorX / 300;
  GyroErrorY = GyroErrorY / 300;
  GyroErrorZ = GyroErrorZ / 300;
}
```

title: MPU6050 Problem with NodeMCU

Answers: 1

body:
I see that you are reading 16-bit integers from the IMU like this:

    // doesn't work on 32-bit systems
    void loop() {
        ...
        AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
        AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
        AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
        ...
        GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // ...
        GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
        GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
        ....
    }

While all too often I am forced to use "#ifdef" to set up platform-specific code for each platform,
in this case I'm pretty sure it's possibly to write cross-platform compatible code that will work on both platforms;
perhaps something more like this:

    // warning: untested, but I think it should work
    int16_t wire_read_16(){
        int16_t value = (Wire.read() << 8 | Wire.read());
        return value;
    }

    void loop() {
        ...
        AccX = (wire_read_16()) * (1.0f / 16384.0f); // X-axis value
        AccY = (wire_read_16()) * (1.0f / 16384.0f); // Y-axis value
        AccZ = (wire_read_16()) * (1.0f / 16384.0f); // Z-axis value
        ...
        GyroX = (wire_read_16()) * (1.0f / 131.0f); // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
        GyroY = (wire_read_16()) * (1.0f / 131.0f);
        GyroZ = (wire_read_16()) * (1.0f / 131.0f);
        ....
    }

I see that
onehorse is apparently having exactly the same problem at
["integer type definitions on Teensy 3.1"][1]

It sounds like maybe you've stumbled over a quirk of the C programming language where "int" varies from system to system.
(See Ido Gendel, ["The problem with ints"][2]).
The "int" in some systems (such as the ATmega based Arduinos) is a 16-bit integer.
The "int" in some other systems (such as the ARM based Arduinos, perhaps including NodeMCU) is a 32-bit integer.
(
https://arduino.stackexchange.com/questions/41879/inttypes-vs-arduino-defined-integral-types
; ["Arduino reference: int"][3]
)
In yet other systems, "int" is a variety of other sizes.

For example, when your IMU is trying to send you a "-2",
it sends 0xFFFE.
When the nano puts that into its "int" which is a 16-bit integer, it then later properly interprets that as meaning "-2".
I suspect what's happening is that
when the other system puts that value into its "int" which is a 32-bit integer, that somehow ends up containing
0x0000FFFE which means +65534,
but what *should* have happened is "sign extension" so that 32-bit integer ends up containing
0xFFFFFFFE which means "-2".
By sticking that value into an intermediate "int16_t" variable, we're explicitly telling the compiler that it's a signed 16-bit integer,
so later when that compiler sticks it into a 32-bit integer it sign-extends properly.

The C compiler (correctly) handles an int divided by a float by converting both values to floats (and sign extending properly), and then dividing. Likewise with an int divided by a double.

  [1]: https://forum.pjrc.com/threads/25799-integer-type-definitions-on-Teensy-3-1
  [2]: https://www.idogendel.com/en/archives/104
  [3]: https://www.arduino.cc/en/Reference.Int


body:
```
#include <IRremote.h>
#include <AFMotor.h>
AF_DCMotor motor(1);

int RECV_PIN = 14;//The definition of the infrared receiver pin 11
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
  Serial.begin(9600); //Open serial
  irrecv.enableIRIn(); // Initialization infrared receiver
  motor.setSpeed(255);
  motor.run(RELEASE);
  Serial.println("start");
  motor.run(FORWARD);
  delay(1000);
}

void loop()
{
  if (irrecv.decode(&results)) {
    if(results.value==0x3D9AE3F7)
    {

      motor.run(FORWARD);
      delay(2000);
    }
    else if(results.value==0x1BC0157B)
    {
      motor.run(RELEASE);
      motor.run(BACKWARD);
    }
    Serial.println(results.value, HEX);//Wrap output in hex receive code
    Serial.println();//For ease of viewing the output to add a blank line
    irrecv.resume(); //Receiving the next value
  }
}
```
Motor shield is not working when I use an IR receiver.
I tried connecting the ir receiver in different analog pins but it didn't work. I guess it's due to some error in my code but unable to figure out.

title: Unable to use ir receiver and motor shield together

Answers: 0


body: something I've never understood and still don't is, what does the return type do specifically? Everyone in tutorials just say that void returns nothing and int returns int, etc. But what does that mean? Where is it returning to?  I can't seem to understand what everyone's talking about when they discuss functions.

title: What exactly does the return type do in a function?

Answers: 2

body:
It returns it to whatever the function is being assigned to.

Take the function:

```cpp
int plus(int a, int b) {
    return a + b;
}
```

That function takes two integers, adds them together, and "returns" them *as an integer*.

You can then do:

```cpp
int c = plus(3, 4);
```

and `c` will be handed the value `7` by the function.

Equally you can do:

```cpp
Serial.println(plus(3, 4));
```

And the `Serial.println()` function will be handed the value `7` for printing.

The type of the return defines the kind of data that *can* be returned.

Oh, and `void` doesn't mean "returns nothing", but means "doesn't return anything" - which means you can't assign it to anything since there's nothing returned to assign.

body:
The reason is that a function is evaluated just as any other expression would be. Every expression - `(x**x - 3*x + 5), for instance - has a value and a type (unless the type is void, then it has no value, or not a defined one), and that includes functions. The compiler needs to know the type of every element of the expression in order to know how to use that element in an operation (arithmetic or other kinds). Sometimes a value has to be converted from one type to another to combined with another element or assign to a variable, and knowing the type of each element is the only the compiler knows how to accomplish this.

Here is an example:

`float squareroot(float x);` could declare a function that takes a floating point number and returns its square root as a floating point number. If you assign that value to an integral of variable, the compiler needs to see that the functions does not return an integer but a float, so it includes the appropriate code to convert the float to an integer (by truncating the fractional part, in this case).

If the function could be written without declaring its return value type, the compiler would be unable to make the conversion, or even to know whether one will be needed.


body:
Totally new to Arduino, 3 weeks old!

I am doing a project with 2 inputs (2 x ultrasonic sensors) and 2 outputs (buzzer and send SMS)

The code to run the buzzer and sms works perfectly individually. For the buzzer, it will stop buzzing after approx 5 seconds.

I would love them to run **concurrently** but it didn't work as planned when I upload the code on the board.

I've read on forums to use **millis / blinkwithoutdelay** but am unsure how I can incorporate those functions on my mode as the examples posted online are different from my project.

The following is the code I have created.

Would appreciate if I can get some help from the experienced folks here.

```cpp
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

int ctn = 0;

void setup() {
  Serial.begin(9600); // Serial monitoring
  pinMode(TRIG, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT); // Initializing Trigger Output and Echo Input
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {

  digitalWrite(TRIG, LOW); // Set the trigger pin to low for 2uS
  delayMicroseconds(2);

  digitalWrite(TRIG, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG, LOW); // Send pin low again
  delayMicroseconds(2);

  digitalWrite(TRIG1, LOW); // Set the trigger pin to low for 2uS. Give a short LOW pulse beforehand to ensure a clean HIGH pulse
  delayMicroseconds(2);

  digitalWrite(TRIG1, HIGH); // Send a 10uS high to trigger ranging according to specs
  delayMicroseconds(20);

  digitalWrite(TRIG1, LOW); // Send pin low again
  delayMicroseconds(2);

  int distance = pulseIn(ECHO, HIGH, 26000); // Read in times pulse
  int distance1 = pulseIn(ECHO1, HIGH, 26000); // Read in times pulse
  distance = distance/58;
  distance1 = distance1/58;

  if (distance < 25) {
    Serial.print("\r");
    delay(1000);
    Serial.print("AT+CMGF=1\r");
    delay(1000);
    /*Replace XXXXXXXXXX to 10 digit mobile number & ZZ to 2 digit country code*/
    Serial.print("AT+CMGS=\"+YYXXXX\"\r"); // YY is the country code XXX is the number
    delay(1000); //
    //The text of the message to be sent.
    Serial.print("HELLO There");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);
  }
  else {}

  if (distance1 < 25 && ctn < 150) {
    ctn += 1;
    digitalWrite(Buzzerpin, HIGH);
  }
  else {
    digitalWrite(Buzzerpin, LOW);
  }

  if (distance1 > 25 && ctn >= 150) {
    ctn = 0;
    digitalWrite(Buzzerpin, HIGH);
  }
}
```

title: Running Arduino with 2 outputs and 2 inputs

Answers: 2

body:
First thing: you should call `pulseIn()` right after sending the TRIG
pulse. If you wait too much, you will miss the start of the echo pulse.
For instance, here:

```cpp
int distance = pulseIn(ECHO, HIGH, 26000);
int distance1 = pulseIn(ECHO1, HIGH, 26000);
```

the second `pulseIn()` is starting too late, because of the time taken
by the first one.

Next, the general approach for doing things is a non-blocking fashion
(and thus being able to handle concurrent tasks) is to program each task
in the form of a [finite state machine][fsm]. Combine this with the
timing technique used in the “Blink without delay” Arduino tutorial if
you need time-triggered actions.

Here I would use one state machine for sending the SMS and another one
for the buzzer. The first one is the most complex:

**Edit**: I expanded on how I designed this state machine.

In a canonical finite state machine implementation, each action is
associated with a state transition. We then have a transition for each
command sent to the GSM module, and we can label the states according to
which commands have already been sent, like this:

SENT\_NOTHING → SENT\_CR → SENT\_CMGF → SENT\_CMGS → SENT\_MSG →
SENT\_ALL.

All of the above transitions send a string to the GSM module. The first
one (SENT\_NOTHING → SENT\_CR) is triggered by the distance detected
being less than 25 cm. The following ones are time-triggered one
second after the previous one. We have to add one final transition
(SENT\_ALL → SENT\_NOTHING) that performs no action but lets the system
“forget” it has sent an SMS and thus makes it ready to send a new one.
This transition would also be time-triggered, after a potentially long
delay (how often would the user like to receive those reminders?). In
the code below, this last delay is one second, which I believe is too
short, but matches the last `delay(1000)` in the code you posted. The
implementation would be like this:

```cpp
static enum {
  SENT_NOTHING, SENT_CR, SENT_CMGF, SENT_CMGS, SENT_MSG, SENT_ALL
} sms_state = SENT_NOTHING;
static uint32_t time_last_command_sent;
uint32_t now = millis();
switch (sms_state) {
  case SENT_NOTHING:
    if (distance < 25) {
      Serial.print("\r");
      time_last_command_sent = now;
      sms_state = SENT_CR;
    }
    break;
  case SENT_CR:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGF=1\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGF;
    }
    break;
  case SENT_CMGF:
    if (now - time_last_command_sent >= 1000) {
      Serial.print("AT+CMGS=\"+YYXXXX\"\r");
      time_last_command_sent = now;
      sms_state = SENT_CMGS;
    }
    break;
  // and so on for the cases SENT_CMGS and SENT_MSG...
  case SENT_ALL:
    if (now - time_last_command_sent >= 1000) {
      sms_state = SENT_NOTHING;  // forget we sent an SMS
    }
    break;
}
```

I have an issue with this implementation though: it is overly
repetitive, as the cases SENT\_CR, SENT\_CMGF, SENT\_CMGS and SENT\_MSG
are essentially copies of the same code. In order to make the code
[dryer][dry], I prefer merging them into a single state, and splitting
the state information into two variables: `sms_state` and
`commands_sent`. The new possible values for `sms_state` are now:

* SMS\_READY: the code is ready to send the message as soon as it is
  required by the detected distance.
* SMS\_SENDING: it has started to send the commands to the GSM module,
  but is not done yet.
* SMS\_DONE: the SMS has been sent, but no other one will be sent until
  some time has elapsed, after which it will transition to SMS\_READY.

The mapping to the “full” machine states is then:

     full state    │ sms_state   commands_sent
    ───────────────┼───────────────────────────
     SENT_NOTHING  │ SMS_READY         0
     SENT_CR       │ SMS_SENDING       1
     SENT_CMGF     │ SMS_SENDING       2
     SENT_CMGS     │ SMS_SENDING       3
     SENT_MSG      │ SMS_SENDING       4
     SENT_ALL      │ SMS_DONE          5

It could be argued that `sms_state` is redundant, as all the state
information is contained in `commands_sent`. I still wanted to keep
`sms_state` in order to easily `switch` on it. This is not the only
possible approach though, and it would be perfectly sensible to write
something like

```cpp
if (commands_sent == 0) {
  // handle the case SMS_READY
} else if (commands_sent < command_count) {
  // handle the case SMS_SENDING
} else {
  // handle the case SMS_DONE
}
```

For the buzzer, there are only two states: BUZZER\_OFF and BUZZER\_ON.
The transitions are conditioned by the measured distance and, for the ON
→ OFF transition, also by the time it has been ON.

Here is my tentative, untested implementation of this approach:

```cpp
#define TRIG A0 //Module pins
#define ECHO A1
#define TRIG1 A2 //Module pins
#define ECHO1 A3
#define Buzzerpin 13

// Commands to be sent to the GSM module.
const int command_count = 5;
const char * const commands[command_count] = {
  "\r",
  "AT+CMGF=1\r",
  "AT+CMGS=\"+YYXXXX\"\r",
  "HELLO There",
  "\x1a"
};

void setup() {
  Serial.begin(9600);
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT_PULLUP);
  pinMode(TRIG1, OUTPUT);
  pinMode(ECHO1, INPUT_PULLUP);
  pinMode(Buzzerpin, OUTPUT);
}

void loop() {
  // Measure both distances.
  digitalWrite(TRIG, LOW);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG, LOW);
  int distance = pulseIn(ECHO, HIGH, 26000) / 58;
  digitalWrite(TRIG1, HIGH);
  delayMicroseconds(20);
  digitalWrite(TRIG1, LOW);
  int distance1 = pulseIn(ECHO1, HIGH, 26000) / 58;

  // Timing for both state machines.
  uint32_t now = millis();

  // Send the SMS.
  static enum {SMS_READY, SMS_SENDING, SMS_DONE} sms_state;
  static uint32_t time_last_command_sent;
  static int commands_sent = 0;
  switch (sms_state) {
    case SMS_READY:
      if (distance < 25) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        sms_state = SMS_SENDING;
      }
      break;
    case SMS_SENDING:
      if (now - time_last_command_sent >= 1000) {
        Serial.print(commands[commands_sent++]);
        time_last_command_sent = now;
        if (commands_sent >= command_count) {
          sms_state = SMS_DONE;
        }
      }
      break;
    case SMS_DONE:
      if (now - time_last_command_sent >= 1000) {
        commands_sent = 0;
        sms_state = SMS_READY;
      }
      break;
  }

  // Drive the buzzer.
  static enum {BUZZER_OFF, BUZZER_ON} buzzer_state;
  static uint32_t time_buzzer_started;
  if (buzzer_state == BUZZER_OFF && distance1 < 25) {
    digitalWrite(Buzzerpin, HIGH);
    buzzer_state = BUZZER_ON;
    time_buzzer_started = now;
  } else if (buzzer_state == BUZZER_ON && distance1 >= 25
             && now - time_buzzer_started >= 2000) {
    digitalWrite(Buzzerpin, LOW);
    buzzer_state = BUZZER_OFF;
  }
}
```

[fsm]: https://majenko.co.uk/blog/finite-state-machine
[dry]: https://en.wikipedia.org/wiki/Don't_repeat_yourself

body:
Using the blinkwithoutdelay approach is not incorporating functions, it is a coding style.

The idea is that you write your loop code to pass through without any delays, or with only very tiny delays. On each pass through the loop, you see how much time has passed, and if it's been 5 seconds since you started the buzzer, you turn off the buzzer.

You can probably get away with the microsecond delays that you use in your ultrasonic sensor code. Those delays are so small that they will only cause **very** short pauses in your app.

The `delay(1000)` calls in your loop are not going to work. Each one of those causes EVERYTHING to stop for a full second. You won't check the ultrasonic sensor, you won't change the buzzer state, you won't do ANYTHING, for 5 seconds, once you enter the body of that `if` statement. Those delay calls have to go.


body:
I am new to arduino and need help with a couple projects I am working on. One involves the use of 2 sensors - one pulse sensor, and one vibration sensor. Both need to be plugged into the "5v" pin but there seems to be only one. Is there a way I could split the pins to add multiple sensors? Will data be taken in simultaneously, and be cross compared with each other for code execution? I dont want to use breadboaard and want to wire directly to chip.

Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.

I also need to wire a multicolor LED to the board, but do I need any resistors? I see them often for others people projects, but I do not have any and am wondering if I need them.

Thanks if you can answer any of these questions. Totally new to EE

title: Arduino Nano - How to add multiple sensors? Lithium battery requirements? LED requirements?

Answers: 4

body:
Warning: unexperienced experiments even with low voltage may result in dangerous situations. E.g. a typical 10 Ohm resistor on 5 V may get so hot that it starts burning. Make yourself familiar with basic electronics, ideally with the help of someone else who can explain it to you. That person should especially explain the safety instructions first.

> Both need to be plugged into the "5v" pin but there seems to be only one.

5 Volts means that this is a voltage source. In an ideal voltage source, you can basically plug in as many components as you like.

A real world voltage source will have a power limit. So you need to find datasheets of all components: the Arduino and the sensors. You can then read how much power the Arduino can provide and you can read how much power the sensors need.

As long as the Arduino can provide more power than the sensors need, that's ok. If it can't stuff will become more complicated, since you'll need another 5 V source and find a way to connect them safely.

>  Is there a way I could split the pins to add multiple sensors?

One does not split pins, one connects additional wires to a pin.

> Will data be taken in simultaneously, and be cross compared with each other for code execution?

The 5V pin is only a voltage source. It will not provide or receive data. You'll need another pin or even multiple other pins to send and receive data.

Sometimes you can only have one device per pin (like a digital out pin), sometimes you can have multiple devices on a few pins (like I²C, SPI, 1Wire).

Typically, you would define what you need and then buy the components so you can build it. This requires a bit of knowledge, so watch some tutorials or introduction videos first.

> I dont want to use breadboaard and want to wire directly to chip.

Sorry to be that direct, but at your level of understanding, that's probably not a good idea. Build it on a breadboard first and once it works as intended, make it a soldered circuit.

> I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more?

As you said your components need 5 V, a 3.7 V battery will not help you at all.

You also need to be careful with the terms: a Mah is something totally different than a mAh. Don't confuse other people by mixing Mega (millions) with milli (1/1000).

Other than that, again, read the data sheets, find out how much current each component needs and sum it up. Then divide the 1000 mAh by the value you found, e.g. 100 mA and you'll get 10 h. That's how long it will last. Maybe it's good for your purpose, maybe not. How should we know that?

> I want to make sure it will work with just those 2 parts.

That's great. Just consider all the aspects written in the data sheets of the components and it'll be fine.

> I also need to wire a multicolor LED to the board, but do I need any resistors?

Yes. Read the data sheet of the multicolor LED and build a voltage dividor according to the values you find.

> Totally new to EE

That's probably true. Maybe you want to start at the beginning and not jump into such a complex project. Get some resistors, measure voltages, measure currents. Make an LED light up. Learn about Ohms law, you'll need it very often. Once you got familiar with the basic stuff, come back to this project.

Honestly, I think you'll destroy components if you start with "a couple of projects".

body:
This is an addition to the answer of Thomas Weller.

> Also, I need to wire up a rechargeable lithium battery to both projects, I have a 3.7v 1000 Mah lithium battery and a charging port, but do I need more? Ive seen battery regulators, and other parts people recommend, but I want to make sure it will work with just those 2 parts.

I guess with "charging port" you simply mean a plug, where you can connect a power supply to charge the Li battery. Then the answer is: No, you cannot do it with only the battery and the plug. Lithium batteries are rechargeable, yes, but there is much to consider for charging. You must never ever overcharge the battery or discharge it beyond a certain point. Otherwise the battery gets broken (the result can be between simply holding less and less or no power, to the battery exploding).

Also you need to know the battery level to accurately charge or turn of the device, when the battery is empty. Lithium batteries mostly don't change their voltage enough between the full and empty states. Thus Li battery devices have a circuit, that measures, how much power is coming in (while recharging) and how much power is taken out (for powering a device), to determine the current battery level.

At your stage you cannot build that yourself, and also I wouldn't recommend that to anyone. You can by Li battery charger/regulator boards, which will do all that for you, and they are not expensive. There are also microcontroller boards, that incorporate that support for Li batteries.

body:
A multicolor LED as in an RGB LED?

To power and LED you will need current limiting resistors.

For an RGB LED you'll need 3, one each for the red, green, and blue channels. You'll need to do some math to figure out what resistance values you need. You need to know the supply voltage (5V) the voltage drop of the LED, and the current to supply to the LED.

Here is a link to an LED resistor calculator: https://ohmslawcalculator.com/led-resistor-calculator

The formula is R = (source_voltage -  LED_voltage_drop) / LED_current

So if you have a 20 mA LED with a 1.3V voltage drop, and you are powering it from 5V (all fairly common values) you'd get:

(5-1.3)/0.02 = 185 Ω.

Then you would round up to the nearest resistor value.

You can safely use a higher resistance value than what you calculate. That will cause the LED to be dimmer. If you use a lower resistance you risk burning out the LED, or even burning out your Arduino.

For 20% resistors, that would be a 220Ω resistor. (The percent is a tolerance value. 20% resistors can have their actual resistance vary by as much as 20% from one to the next. You can get resistors in 20%, 10%, 5%, 2%, 1% tolerances, and even lower. The lower the tolerance value, the more they cost, and the more resistors you need to have all the possible values.

Don't use that value however. Look up the voltage drop and current for your LED and plug them into the above formula.

If you want to vary the apparent color of an RGB LED through software you can hook each color channel to a different PWM output pin on your Arduino. You then set each color channel to a different "duty cycle" to vary the brightness of that color.

body:
**For the 5v pin:**
If you wire 2 sensors to the 5v pin, it will not effect sensor readings of either sensors, and should return separate sensor values regardless of whether or not they are both wired to the 5v pin.

In order to wire both sensors to 1 5v pin, without involving a breadboard you have 2 options:

 1. wire both sensor pins, and the 5v pin onto a custom pin header PCB that connects 3 or more pin headers together
 2. Strip 3 jumper wires and solder them together (2 for the sensors and 1 for the 5v pin)

**For the lithium batteries:**
It says on their website: that the operating voltage is 5v, So your battery voltage needs to be at least that. It might be a good idea to get 2
[(store.arduino.cc)](https://store.arduino.cc/usa/arduino-nano#:~:text=The Arduino Nano is a,instead of a standard one.)

**For the LEDs:**
If it is a standard LED, it should be able to withstand voltages of 3.3v or under. Thus the resistor is only absolutely essential for higher voltages. However, it is recommended to use a resistor even with voltages of 3.3v or below, because low resistance could shorten the lifespan of the LED