body:
N00b question,

Is there a better way for readability / elegance / DRY etc to check various sensor values for high/low record value?  This code works, but looks like the long way round.

      void checkRecord() {

    if ( temp.current > temp.high) {
      temp.high = temp.current;
    }

    if ( temp.current < temp.low) {
      temp.low = temp.current;
    }

    if ( pressure.current > pressure.high) {
      pressure.high = pressure.current;
    }

    if ( pressure.current < pressure.low) {
      pressure.low = pressure.current;
    }
    if ( humidity.current > humidity.high) {
      humidity.high = humidity.current;
    }

    if ( humidity.current < humidity.low) {
      humidity.low = humidity.current;
    }

    if ( rainfall.current > rainfall.high) {
      rainfall.high = rainfall.current;
    }

    if ( rainfall.current < rainfall.low) {
      rainfall.low = rainfall.current;
    }
    if ( altitude.current > altitude.high) {
      altitude.high = altitude.current;
    }

    if ( altitude.current < altitude.low) {
      altitude.low = altitude.current;
    }
    }

Thanks!

title: Is there a more elegant way to check highest / lowest sample data?

Answers: 3

body:
If the temperature, pressure, humidity, rainfall, and altitude structs were elements of an array of structs, you could iterate over those elements setting each one's high and low values with only two handwritten 'if-then' statements. If you also used an enum to name the indices of the structs, then in other parts of your code you could address each of them by a descriptive name:

    // Declare a data struct and define an array of them.
    struct {
       int16_t current;
       int16_t high;
       int16_t low;
    } data[5] = {0, 0, 0, 0, 0};

    // Name the structs by index
    enum kind {
       temperature = 0,
       pressure,
       humidity,
       rainfall,
       altitude
    };

    // Assign one kind of data:
    data[temperature].current = getTermperature();

    // Set maxes & mins for all of the kinds of data:
    for( i = 0; i < sizeof(data)/sizeof(data[0])); ++i ){
       if ( data[i].current > data.high) {
          data[i].high = data[i].current;
       }

       if ( data[i].current < data[i].low) {
          data[i].low = data[i].current;
       }
    }

Update:

> I'm strugling with the data[5] {0,0...} part in struct.

I can't see your whole sketch but you probably have allocated 5 separate structs named "temp", "pressure", ... , etc. I'm suggesting you allocate an array of 5 structs (which I collectively called "data"), one for each of your individual ones. I included an initializer ( '= {0,0,0,0,0}') to set everything to zero before the start of the run.

> all of enum kind{} and how it becomes data[pressure] etc.,

The enum is a quick way to make 5 symbols that stand for consecutive integers, in this case, the index into the array of each struct, using a descriptive name for that struct's data. So 'data[pressure]' is the same as data[1] (in this case) but is more understandable.

> the sizeof(data)/sizeof(data[0]) in the loop

That expression gives the number of structs in the array (the total byte-size of the array divided by the byte-size of one struct). We could write '5' instead, but when you someday add another member or two (wind_direction, wind_speed, perhaps?), you'd have to remember to also fix your for() loop. By using this calculation, the compiler will do it for you, leaving you one less opportunity to make a mistake you'd then need to debug.

> and finally I think
> altitude.high in the if statement is a paste typo? should be
> data[i].high?

Absolutely right! Fixed now.

Update:

> For defining initial values can you just assign an initial value in
> the struct such as int16_t low = INFINITY; and so on instead of
> {0,0,0,0,0}?

Yes - Without knowing your data and application, I chose the simplest initializer. The full syntax to do what you want would look like this:

    // Declare a data struct and define an array of them.
    struct {
       int16_t current;
       int16_t high;
       int16_t low;
    } data[5] = {
      {0, 0, INFINITY},
      {0, 0, INFINITY},
      {0, 0, INFINITY},
      {0, 0, INFINITY},
      {0, 0, INFINITY}
    };

You don't need (and may not) specify each data type and name; the struct declaration already provides that information. The initializers are positional and each one must be compatible with the data-type it matches up to.

body:
You could write something like:

    temp.high = (temp.current > temp.high) ? temp.current : temp.high;
    temp.low  = (temp.current < temp.low) ? temp.current : temp.low;
    ...

Most of the time there are min/max macros defined already like:

    #define MAX(a, b)   ((a > b) ? a : b)
    #define MIN(a, b)   ((a < b) ? a : b)

So you can then simply write:

    temp.high = MAX(temp.current, temp.high);
    temp.low  = MIN(temp.current, temp.low);
    ...

Which expands to the exact code as given above.

body:
This is a variation on the `struct` idea with an object-oriented flavor.

If you put the current, low and high values of any sensor inside a
`struct`, you could also morph this `struct` into a `class` and give it
an `update()` method that, in addition to updating the current value,
keeps the low and high updated:

<!-- language-all: lang-c++ -->

    class LowHigh
    {
    public:
        LowHigh() : current(0), low(INFINITY), high(-INFINITY) {}
        void update(float value) {
            current = value;
            if (current < low)
                low = current;
            if (current > high)
                high = current;
        }
        float get_low() { return low; }
        float get_high() { return high; }
    private:
        float current, low, high;
    };

I am assuming `float` data here, you may have to adapt to whatever type
is appropriate for your sensors.

You would use the class as this:

    LowHigh temp, pressure, humidity, rainfall, altitude;

    void loop()
    {
        temp.update(temp_sensor.get_reading());
        pressure.update(pressure_sensor.get_reading());
        humidity.update(humidity_sensor.get_reading());
        // ...
    }


body:
I'm trying to send data from my ESP8266 to a NodeJS TCP server, the connection and basic charakters (48-90) are working fine, but if I use others like ASCII-Code (0,1,2,3...)  I don't get any usefull data out of it. So what I was thinking about that there are some character which aren't allowed to send over TCP/IP.

By the way,
I'm using this to write to the server, and I work with the standard WiFi Client library

    char arr[255]
    for(int i = 0; i < 255; i++){
       arr[i] = (char)i;
    }
    client.print(arr);

Nodejs File:

    // Load the TCP Library
    net = require('net');

    var mysql = require('mysql');

    // Keep track of the chat clients
    var clients = [];
    var uploadCounter = 0;

    initMySQLConnection();

    // Start a TCP Server
    net.createServer(function (socket) {

        // Identify this client
        socket.name = socket.remoteAddress + ":" + socket.remotePort

        // Put this new client in the list
        clients.push(socket);

        // Send a nice welcome message and announce
        socket.write("Welcome " + socket.name + "\n");
        broadcast(socket.name + " connected\n", socket);

        // Handle incoming messages from clients.
        socket.on('data', function (data) {
            broadcast(">> " + data, socket);

            uploadData(data);
        });

        // Remove the client from the list when it leaves
        socket.on('end', function () {
            clients.splice(clients.indexOf(socket), 1);
            broadcast(socket.name + " disconnected.\n\n");
        });

        // Send a message to all clients
        function broadcast(message, sender) {
            clients.forEach(function (client) {
                // Don't want to send it to sender
                if (client === sender) return;
                //client.write(message);
            });
            // Log it to the server output too
            process.stdout.write(message)
        }

    }).listen(10101);

    // Put a friendly message on the terminal of the server.
    console.log("Chat server running at port 10101\n");

    var connection;
    function initMySQLConnection() {
        connection = mysql.createConnection({
            host: "host",
            user: "user",
            password: "pass",
            database: "database"
        });

        connection.connect(function (err) {
            if (err) {
                console.log('error when connecting to db:', err);
            }
        });

        connection.on('error', function (err) {
            console.log('db error', err);
            if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                                        // lost due to either server restart, or a
            } else {                                      // connnection idle timeout (the wait_timeout
                throw err;                                  // server variable configures this)
            }
        });

        setInterval(function () {
            connection.query('SELECT 1');
        }, 60000);
    }

    function uploadData(data) {
        data = String(data);

        console.log("Package Length: " + data.length);
        console.log("GOT ASCII CODE: ");
        for (var i = 0; i < 255; i++) {
            console.log(data.charCodeAt(i));
        }

        //upload Code
    }

title: Forbidden characters in TCP/IP

Answers: 1

body:
The `print` function takes an array of characters as zero terminated c-string. It prints until a byte with value 0. You have zero at `arr[0]` so it is an empty string.

To send bytes, `write` function is used. The `print` functions convert parameters to text or expect text as zero terminated char array.

In your case it should be `client.write(arr, length);` where `length` is the number of bytes you want to send from the buffer `arr`.


body: I am new to arduino but I know basic concepts. How do I make the motor move at sinusoidal acceleration? I used the accelstepper library and it seems that at the end of each loop of distance with acceleration, the motor abruptly stops and begins accelerating again. Is there any way to stop this abrupt pause?

title: How to make a stepper motor move at sinusoidal acceleration?

Answers: 0


body:
I am weirded about the built-in "latest Temboo library" with the latest Arduino IDE; when a previous older code says to download the latest Temboo version < 2?
(which I found this: https://temboo.com/download)

http://wirebeings.com/arduino-intruder-alarm.html

I am using Arduino Uno or Arduino Leonardo + an iDuino Yun shield to recreate the experiment above.

I keep getting errors like this:

https://arduino.stackexchange.com/questions/60674/no-matching-function-for-call-to-temboochoreotemboochoreo-temboochoreo-se?noredirect=1#comment128974_60674

Arduino: 1.8.8 (Windows 10), Board: "Arduino Leonardo"

Build options changed, rebuilding all
In file included from C:\Users\user\Documents\Arduino\intruderAlarmTest\intruderAlarmTest.ino:6:0:

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:43: error: expected identifier before '(' token

 #define TEMBOO_ERROR_ACCOUNT_MISSING      (201)

                                           ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'

             TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

             ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:43: error: expected '}' before '(' token

 #define TEMBOO_ERROR_ACCOUNT_MISSING      (201)

                                           ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'

             TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

             ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:44: error: expected unqualified-id before numeric constant

 #define TEMBOO_ERROR_ACCOUNT_MISSING      (201)

                                            ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'

             TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

             ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/Temboo.h:86:44: error: expected ')' before numeric constant

 #define TEMBOO_ERROR_ACCOUNT_MISSING      (201)

                                            ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:264:13: note: in expansion of macro 'TEMBOO_ERROR_ACCOUNT_MISSING'

             TEMBOO_ERROR_ACCOUNT_MISSING       = 201,

             ^

In file included from C:\Users\user\Documents\Arduino\intruderAlarmTest\intruderAlarmTest.ino:7:0:

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: In member function 'char* TembooCoAPChoreo::getResponseData()':

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:247:41: error: 'm_respData' was not declared in this scope

         char* getResponseData() {return m_respData;}

                                         ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: In member function 'char* TembooCoAPChoreo::getHTTPResponseCode()':

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:248:45: error: 'm_httpCodeStr' was not declared in this scope

         char* getHTTPResponseCode() {return m_httpCodeStr;}

                                             ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h: At global scope:

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:277:5: error: expected unqualified-id before 'protected'

     protected:

     ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:280:27: error: 'm_client' declared as reference but not initialized

         TembooCoAPClient& m_client;

                           ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:311:5: error: expected unqualified-id before 'protected'

     protected:

     ^

E:\arduino\arduino-1.8.8\libraries\Temboo\src/TembooCoAPEdgeDevice.h:314:1: error: expected declaration before '}' token

 };

 ^

exit status 1
Error compiling for board Arduino Leonardo.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Update:
I found that   by adding #include TembooYunShield.h
and TembooYunShieldChoreo  SendSMSChoreo;
instead of TembooChereo SendSMSChoreo;

fixes most of the errors

except the @Temboo and @Twilio problem.

title: Arduino IDE 1.8.8 built in 1.2.1 Temboo Library?

Answers: 0


body:
When I run the program, there are no syntax errors or anything. All it does is give me values for the temperature in the hundreds. I don't know if there is a way to turn these abstract and unexpected values into the actual temperature.

I originally expected that it would print out the temperature around 20 Celsius, but instead, it prints around 600. This is my code:

    #include <Adafruit_Sensor.h>
    #include "DHT.h"

    int sensor_pin = A0; // Analog Pin sensor is connected to
    int output_value ;

    void setup(){

      Serial.begin(9600);
      delay(5000);//Delay to let system boot
      Serial.println("DHT11 Humidity & temperature Sensor\n\n");
      delay(5000);//Wait before accessing Sensor

    }//end "setup()"

    void loop(){
      //Start of Program

        output_value= analogRead(sensor_pin);

        Serial.println("temperature = ");
        Serial.println(output_value);
        Serial.println("*C");
        if (output_value < 60) {
        Serial.println("Increase temperature by ");
        Serial.println(output_value);
        Serial.println("*C");
    } else {
        Serial.println("Temperature does not need to be increased.");
    }

        delay(5000);

    }// end loop()

title: DHT11 Reading Too High Values

Answers: 1

body:
The DHT11 is a **digital** device. You cannot read from it with `analogRead()`.

While temperature is an *analog* value, that's not how the DHT11 communicates with an Arduino. There is a specific digital protocol.

In your code, it appears you have added the headers for the Adafruit Sensor library and DHT library, but you never actually call the functions provided therein.

The Adafruit repository for the DHT sensor library has an example:
https://github.com/adafruit/DHT-sensor-library/blob/master/examples/DHTtester/DHTtester.ino

You can see how to create an object from the `DHT` class, and how to call it's member functions, such as `readTemperature()` and so on.


body:
I'm trying to write a simple code for initializing and running the PCA9685. I tested the board with Adafruit library and it's working.

But I just want to develop a simple code to include it in my various modules library for future projects.

I wrote a code, but I think I'm not understanding the work of the internal registers.

But according to the datasheet I configured only the auto increment and left the rest to default settings. Then I headed up to the last registers which are the `all_led_on` and `all_led_off`as wanting to run the outputs on/off to blink the LEDs. But I think these two registers are for enabling/disabling the pins. Is that right?

This is my code:

 void pca9685_init(void){
  uint8_t i,val[]={0x20,0x04};
  i2c_start(PCA9685_BASE_WR);
  i2c_tx(PCA9685_MODE1);
  for(i=0;i<2;i++)i2c_tx(val[i]);
  i2c_stop();
 }

 void pca9685_all_on(void){
  uint8_t i,val[]={0x00,0x10};
  i2c_start(PCA9685_BASE_WR);
  i2c_tx(PCA9685_ALL_LED_ON_L);
  for(i=0;i<2;i++)i2c_tx(val[i]);
  i2c_stop();
 }

 void pca9685_all_off(void){
  uint8_t i,val[]={0x00,0x10};
  i2c_start(PCA9685_BASE_WR);
  i2c_tx(PCA9685_ALL_LED_OFF_L);
  for(i=0;i<2;i++)i2c_tx(val[i]);
  i2c_stop();
 }

title: How to initialize and run PCA9685?

Answers: 1

body:
The registers aren't for just turning the LEDs on or off.  They are for setting the ON and OFF times of the PWM. Bit 12 of each combined value is used as a "full" setting, so:

To set the LEDs on to full brightness you need to set:

* `PCA9685_ALL_LED_OFF_L` to 0x00
* `PCA9685_ALL_LED_OFF_H` to 0x00
* `PCA9685_ALL_LED_ON_L` to 0x00
* `PCA9685_ALL_LED_ON_H` to 0x10

This sets the off time to 0 counts and the on to be "full on".

It doesn't really matter what value you set the OFF to as long as you set ON to "full on" and off *isn't* set to "full off".

For off you should set the ON to 0 and the OFF to "full off" (reverse the above settings).

Section 7.3.3 of the datasheet says:

> The turn-on time of each LED driver output and the duty cycle of PWM can be controlled independently using the LEDn_ON and LEDn_OFF registers.
>
> There will be two 12-bit registers per LED output. These registers will be programmed by the user. Both registers will hold a value from 0 to 4095. One 12-bit register will hold a
value for the ON time and the other 12-bit register will hold the value for the OFF time. The ON and OFF times are compared with the value of a 12-bit counter that will be running
continuously from 0000h to 0FFFh (0 to 4095 decimal).
>
> **Update on ACK requires all 4 PWM channel registers to be loaded before outputs will change on the last ACK.**
>
> The ON time, which is programmable, will be the time the LED output will be asserted and the OFF time, which is also programmable, will be the time when the LED output will be
negated. In this way, the phase shift becomes completely programmable. The resolution for the phase shift is 1⁄
4096 of the target frequency.

So you *have* to set all 4 registers together for anything to happen.

There are also some examples shown in the datasheet as well which explain it better.

In simple terms:

* There is a free-running counter that counts from 0 to 4095
* When the ON time matches the counter the LED turns on.
* When the OFF time matches the counter the LED turns off.
* If a channel is "FULL OFF" it will be off regardless.
* If a channel is "FULL ON" and *not* "FULL OFF" it will be on regardless.
* **"FULL OFF" always takes priority over everything else - even "FULL ON".**

Some simple examples:

* All off: ON=0x0000 OFF=0x1000
* All on full: ON=0x1000 OFF=0x0000
* 50% duty: ON=0x0000 OFF=0x0800
* 25% duty: ON=0x0000 OFF=0x0400
* 25% duty with phase shift: ON=0x0100 OFF=0x0500


body: I don't know how to connect between matlab simulik and arduino card in isis proteus by using a virtual ports

title: How to use virtual connection between matlab simulik and arduino in isis proteus?

Answers: 0


body:
I am trying to read a specific register from a device. In this case I am trying to read the value stored in register 0X1F from slave device 0x08. On the scope I see writes for

    ADDRESS_SLAVE(Wire.beginTransmission), ADDRESS_TESTCOMP0 (Wire.write)

and

    ADDRESS_TESTCOMP0 (Wire.requestFrom(ADDRESS_TESTCOMP0,8))

but I don't see the register values reading out.  Here is my code:

    #include <Wire.h>

    int ADDRESS_SLAVE = 0X08;
    int ADDRESS_TESTCOMP0 = 0X1F;

    void setup()
    {
     Wire.setClock(3400000);
     Wire.begin();
     Serial.begin(9600);
    }

    void loop()
    {
       Wire.beginTransmission(byte(ADDRESS_SLAVE));
       Wire.write(byte(ADDRESS_TESTCOMP0));
       Wire.endTransmission(byte(ADDRESS_TESTCOMP0));

       Wire.requestFrom(ADDRESS_TESTCOMP0,8);
       char read = Wire.read();
       Serial.println(read);

       delay(1000);
    }

title: Arduino I2C Register Read

Answers: 1

body:
errors corrected

    #include <Wire.h>

    byte ADDRESS_SLAVE = 0X08;
    byte REGISTER_XY = 0X1F;
    byte READ_LENGTH = 8;

    void setup()
    {
     Wire.begin();
     Wire.setClock(400000); // set I2C 'full-speed'
     Serial.begin(9600);
    }

    void loop()
    {
       Wire.beginTransmission(ADDRESS_SLAVE);
       Wire.write(REGISTER_XY);  // set register for read
       Wire.endTransmission(false); // false to not release the line

       Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH); // request bytes from register XY
       byte buff[READ_LENGTH];
       Wire.readBytes(buff, READ_LENGTH);
       for (int i = 0; i < READ_LENGTH; i++) {
         Serial.println(buff[i], HEX);
       }
       Serial.println();
       delay(1000);
    }

if you read only one register of the device, you can setup the device in `setup()` and in `loop()` only read the data from the register:

    #include <Wire.h>

    byte ADDRESS_SLAVE = 0X08;
    byte REGISTER_XY = 0X1F;
    byte READ_LENGTH = 8;

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

      Wire.begin();
      Wire.setClock(400000); // set I2C 'full-speed'

      Wire.beginTransmission(ADDRESS_SLAVE);
      Wire.write(REGISTER_XY);  // set register for read
      Wire.endTransmission();
    }

    void loop() {
       Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
       byte buff[READ_LENGTH];
       Wire.readBytes(buff, READ_LENGTH);
       for (int i = 0; i < READ_LENGTH; i++) {
         Serial.println(buff[i], HEX);
       }
       Serial.println();
       delay(1000);
    }


body: I have three arduino **ATMega2560** boards, all have **xbee pro s2c** attached to them. Now i want to update the code i had previously written on the arduino board but without connecting it to the computer. So basically I want to upload a code to arduino board via the xbee module I have attached to it, code is transmitted to this xbee from another xbee. Anyone with any type of ideas please share....

title: How to upload arduino code using xbee module ( pro s2c)?

Answers: 0


body:
Having really bad day with concat. I'm not quite sure where i did wrong..
Have a look at my function below.

    void sim900aSendHttp(String bid, String lati, String longi) {
      Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);
      String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";
      //String httpget = "http://uumresearch.com/bustracking/update_location.php?busid=KDF8860&latitude=6.533415&longitude=106.33345";
      Serial.println(httpget);
      serialSIM800.println("AT+HTTPPARA=\"URL\",\"" + httpget + "\"");
      delay(3000);
      serialSIM800.println("AT+HTTPACTION=0");
      delay(8000);
    }

The problem is with:

    String httpget = "http://uumresearch.com/bustracking/update_location.php?busid="+bid+"&latitude="+lati+"&longitude="+longi+"";

where serial monitor only  shows

    http://uumresearch.com/bustracking/update_location.php?busid=KDF8860

missing "lat" and "longi" variables in the string concat.

Both variable confirmed available to the function as printed by

    Serial.println("BUSID:"+bid+",LAT:"+lati+"LONG:"+longi);

title: Having really weird experience with string concat

Answers: 1

body:
`+` on `const char *` increments the pointer. only String has `+` overloaded as concatenation of the right operand (not left). so `"abc" + str + "efg"` will not work even if `str` is String. What will work is `String("abc") + str + "efg"`, but [small Strings will fragment the heap memory][1] of the MCU very fast and the sketch will crash.

Print the parts directly to `serialSIM800` or use `snprintf` to build the strings or try CStringBuilder from my StreamLib

  [1]: https://majenko.co.uk/blog/evils-arduino-strings


body: So I have recently been trying to use the Myoware Muscle sensor to control an 3d printed arm, but it is only able to read the muscle of the entire arm. Is there anyway i could make the Myoware sensor read different fingers at the same time?

title: Myoware reading multiple fingers?

Answers: 1

body:
Our MyoWare sensor is a single channel EMG sensor and should only be used to detect a single muscle at a time. BUT, if you have 5 sensors, then you can indeed use them to measure each finger's flexion or extension individually. It would take 10 sensors to do both flexion and extension of all your fingers.

However, keep in mind that there are many muscle groups on top of each other in the forearm (e.g. finger muscles, wrist muscles, forearm rotation muscles) and the MyoWare uses surface electrodes. The sensor will detect the activity of any muscle(s) that get activated under the area of the electrodes and you could get a lot of cross-talk between these muscles. For example, the muscles that control your wrist are under the muscles that control your fingers. Any activation of your wrist muscles when trying to measure the finger muscles would cause the sensor to falsely register activity for your finger muscles.

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

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

If you are thinking of using it to detect finger position, I would advise using a flex sensor or something similar than a muscle sensor. Muscle sensor sensors are usually used to detect force or as an on/off switch given a threshold value to activate the switch.


body:
 I want to measure power consumption and calculate the mAH value to know how much time would my battery can run the circuit.
I only got a multimeter and DC power supply.(Im not sure if this is enough to measure)

My project has a temp sensor and measures it every 15 mins. It's going to deep sleep mode and wakes up again to measure.

So how to measure the mAH for this circiut?

title: How to calculate battery usage of my arduino project?

Answers: 2

body:
I suggest using a second Arduino to make yourself an "Energy Meter".

Get a very small power resistor (0.1 Ohm) and power your project through it.

Second Arduino will measure voltage drop on it and that way you can get the current that goes through it using Ohms law. You can also measure the battery/power supply  voltage. Knowing those two values and `micros` each `loop` you can calculate actual hourly power consumption of the device.

body: Use the multimeter to measure the current. Put it in mA current mode, and wire it in series from the DC power supply + to the Arduino positive connection. With an Uno, readings will likly be in the 10s of mA all the time, and maybe a little higher when not in deep sleep mode. This assumes you are not powering the Uno from the USB port.


body:
I am trying to receive data through the serial port from my SBC (a TS-7200), i am working with linux and handle serial communication using C/C++.To send data to the SBC  i'am using an arduino uno.

So basically the arduino is printing ASCII text data through Pin1 (Hardware Serial) in a loop with a 3ms delay.

From the SBC i read raw data in no canonical mode, ( in the code below are the parameters and configurations for the serial port) i'am trying to read one characters at a time, following the example from this page :
https:/ from this page/chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/.

but when i run the code it print the number 2 as 3, and the number 3 as f, I am not able to read ASCII characters.

I have tried several things but I have not been able to find the problem, Hope someone can help me.

Here is the Arduino code:

     #include <SoftwareSerial.h>
     SoftwareSerial mySerial(2,3); // RX, TX

     void setup() {

        Serial.begin(9600);
        mySerial.begin(9600);

      }

     void loop() {

       Serial.print(2);

       delay(3000);

       Serial.print(3);

       delay(3000);

    }

The c code from the linux side:

    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/ioctl.h>
    #include <fcntl.h>
    #include <termios.h>

    char *portname = "/dev/ttyAM1";
    char buf[256];

    int main(int argc, char *argv[])
    {
      int fd,stop = 0;

    /* Open the file descriptor in non-blocking mode */
    fd = open(portname, O_RDWR | O_NOCTTY);

    /* Set up the control structure */
    struct termios toptions;

    /* Get currently set options for the tty */
    tcgetattr(fd, &toptions);

    /* Set custom options */

    /* 9600 baud */
    cfsetispeed(&toptions, B9600);
    cfsetospeed(&toptions, B9600);
    /* 8 bits, no parity, no stop bits */
    toptions.c_cflag &= ~PARENB;
    toptions.c_cflag &= ~CSTOPB;
    toptions.c_cflag &= ~CSIZE;
    toptions.c_cflag |= CS8;
    /* no hardware flow control */
    toptions.c_cflag &= ~CRTSCTS;
    /* enable receiver, ignore status lines */
    toptions.c_cflag |= CREAD | CLOCAL;
    /* disable input/output flow control, disable restart chars */
    toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
    /* disable canonical input, disable echo,
       disable visually erase chars,
       disable terminal-generated signals */
    toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    /* disable output processing */
    toptions.c_oflag &= ~OPOST;

    /* wait for 1 character to come in before read returns */
    /* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */
    /* CHARACTERS HAVE COME IN! */
    toptions.c_cc[VMIN] = 1;
    /* no minimum time to wait before read returns */
    toptions.c_cc[VTIME] = 0;

    /* commit the options */
    tcsetattr(fd, TCSANOW, &toptions);

    /* Wait for the Arduino to reset */
    usleep(1000*1000);
    /* Flush anything already in the serial buffer */
    tcflush(fd, TCIFLUSH);

    while(stop == 0){

      /* read up to 128 bytes from the fd */
      int n = read(fd, &buf, 128);
      usleep(3000*1000);
      /* print how many bytes read */
      printf("%i bytes got read...\n", n);
      /* print what's in the buffer */
      printf("Buffer contains...\n%s\n", buf);
     }
     return 0;
    }

This is what i see:

    2 bytes got read...
    Buffer contains...
    f
    2 bytes got read...
    Buffer contains...
    3
    2 bytes got read...
    Buffer contains...
    f
    2 bytes got read...
    Buffer contains...
    3

title: Read Serial data from an arduino with c code

Answers: 1

body: RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents `0` and -12V represents `1`; inverted from normal TTL.


body:
With my ESP32 Board, Wemos Lolin32, I would like to make a http GET request to "http://www.arduino.cc/asciilogo.txt", read the text file and print the text file to the serial monitor.

**The question is:** Why isn't basically the txt file written to the serial monitor? How can it be achieved? Do I need some kind of conversion of the char?

I am using similar code to that from this example https://www.arduino.cc/en/Tutorial/HttpClient.
Basically the code can be reduced to this minimal example:

    #include <WiFi.h>
    #include <HttpClient.h>

    void setup() {

      Serial.begin(9600);

      WiFi.begin(ssid, password);
      Serial.println("Connecting to WiFi..");
      while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println(".");
      }
      Serial.println("Connected to the WiFi network");

      pinMode(LED_BUILTIN, OUTPUT);
      Serial.println("SETUP FINISHED");
    }

    void loop() {
      Serial.println("Connecting to httpClient");

     HttpClient httpClient;
      httpClient.get("http://arduino.cc/asciilogo.txt");
      while (httpClient.available()) {
        char c = httpClient.read();
        //Serial.print(c);
        Serial.write(c);
      }
    }

**The expected result is:** I would like to see the characters from the txt file (https://www.arduino.cc/asciilogo.txt) in the serial monitor.

**The actual result is:** The connection to the WiFi can be established. In the serial monitor either question marks or strange symbols are displayed.

I have checked the baud and it is the same in the code and in the monitor. I tried to change this value, but it did not help.
[![Serial monitor][1]][1]

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

title: How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)?

Answers: 2

body: it is `http://arduino.cc/asciilogo.txt`. without www. www is redirected to https. you can verify it from a browser

body: When switching from HttpClient to HTTPClient and using String payload = http.getString(); Serial.println(payload); I can achieve the expected result.


body:
I would like to trigger a simple wireless doorbell.
The doorbell uses 433Mhz. To read and send signals I am using the FS1000A Set (sender and receiver).

I've started by connecting the receiver to the Arduino and afterwards I uploaded the ReceiveDemo_Advanced (RCSwitch library). If I press the Doorbell Button it ouputs:

     Decimal: 1987151315 (32Bit) Binary: 01110110011100011000010111010011 Tri-State: not applicable PulseLength: 708 microseconds Protocol: 2
    Raw data: 7272,444,1612,1464,588,1464,588,1464,588,440,1612,1472,568,1476,580,456,1596,452,1600,1476,580,1472,580,1468,584,444,1608,444,1608,448,1608,1464,584,1468,584,448,1608,444,1608,440,1608,448,1604,1472,584,444,1608,1468,584,1464,588,1464,592,440,1612,1464,588,444,1608,440,1612,1464,588,1464,600,

    Decimal: 1987151104 (32Bit) Binary: 01110110011100011000010100000000 Tri-State: not applicable PulseLength: 727 microseconds Protocol: 2
    Raw data: 7268,448,1604,1472,584,1468,580,1472,584,444,1608,1472,584,1468,588,444,1604,444,1608,1468,584,1472,588,1460,592,436,1616,440,1608,444,1608,1464,592,1464,588,440,1612,440,1612,440,1608,444,1608,1472,584,444,1608,1468,584,1468,588,1464,588,440,1612,1464,592,436,1612,440,1612,1464,592,1460,600,

    Decimal: 1987151315 (32Bit) Binary: 01110110011100011000010111010011 Tri-State: not applicable PulseLength: 726 microseconds Protocol: 2
    Raw data: 7272,444,1604,1472,584,1468,580,1468,588,444,1608,1468,588,1460,592,440,1612,440,1612,1464,588,1464,592,1460,592,436,1612,440,1616,436,1612,1468,584,1468,584,444,1608,444,1608,444,1608,444,1612,1464,584,444,1608,1468,584,1468,588,1460,588,444,1612,1464,592,436,1608,444,1612,1464,592,1460,600,

Now I am trying to send the signal via the FS1000A Set to the "Doorbell Receiver" but nothing happens. I tried it via the Binary send and via the Decimal send method. But the "Doorbell Receiver" remains silent.

Please help me!

title: Trigger cheap wireless doorbell

Answers: 0


body:
So for one of my projects i want to power LED strips with power banks but once i try use the second power bank the LEDs half way through patterns jump to random different colors and then go back to the code im using to make sure they work, I dont think its a code issue as when i plug the power into my MEGA it works fine. I would use the MEGA to power the strips but i need 3 power sources to keep my strips at maximum brightness. would this be a voltage drop issue?

When I connected it to my 3 usb port power bank it works perfectly fine so it might be different currents causing it to jump im not to sure if im correct but its definitely something to do with using another power supply is causing my LEDs to randomly change multiple different colors randomly i just cant see if its a current or voltage issue. Any help would be greatly appreciated.

block diagram [link](https://drive.google.com/file/d/1-EDED7WAER_BU6tCumgxvPttGHeGSt7O/view)

title: Powering LED strips with two power banks and they randomly change different colors when i use the second power bank

Answers: 1

body:
These are USB power-banks? You need a way to tie the grounds together somehow. Try tying all the ground lines from your LED strips together and also connecting a wire from one of the LED strips to a ground line on your Arduino.

The USB connections should connect ground between the power bank and the device it's connected to, so by tying the grounds on the LED strips together, that should connect the grounds on the power banks as well.


body:
I've connected my NodeMCU to GSM module using GND, RX and TX.

I use At Comand Tester. When I try to get sim status or something I get error for example:

> Unable to get Sim status.

Only AT comand returns

> AT
>
OK

When I send any AT comand to GSM module I can see that the diode on the module blink.

How can I solve this problem?

Let me know if you need more informations to help me.

title: Nodemcu + GSM IOT-GA6

Answers: 0


body:
I was taking measures from the  outputs of an OpAmp when all the sudden measure 5 volts from all pins of the Arduino Mega for no reason. I disconnected the Arduino and loaded the Firmata and test. All the pins are reading high to 1023.. 5 volts are been output for no reason even when I have the Analog Ping to input.

Sketches code are loading and the lights look normal. I did noticed the processor chip getting hot and the voltage in the breadboard line to the Arduino Analog pins reading 7 volts.

Is this a sign of a serious damaged to my device?

title: Arduino Analog pins go all to high problem

Answers: 1

body:
A high voltage at a pin can damage the microcontroller partially.

The ATtiny microcontrollers can sometimes survive a voltage of 7 V.
The ATmega microcontrollers are damaged by that voltage.
The ATmega2560 is older and even more critical with voltages, it can not work at 16 MHz below 4.5 V and gets easily damaged with voltages above 6 V.

When the microcontroller runs at 5.0 V, a input pin can have -0.5 V to +5.5 V.

When the microcontroller gets damaged, it can be damaged partially. It is impossible to determine which parts of the chip are still okay. Therefor a partially damaged microcontroller should not be used anymore.

**Solution:**

A simple solution is a protection resistor in the signal path to the analog input.

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

<!-- End schematic -->

According to application note AVR182, it is allowed to push 1 mA into a pin or pull 1 mA from a pin for the ATmega microcontrollers. That current flows via the internal ESD diodes to VCC or from GND.

With a protection resistor of 4k7 before an input, the microcontroller is protected up to: 1mA * 4k7 + 5.5V = 10.2 V.

The internal ESD diodes can have more than 1 mA, but the maximum is unspecified. It is also dangerous when for example the ATmega is put into sleep mode. Then the 1 mA can lift the VCC voltage and still damage the ATmega microcontroller.

When a voltage divider is used (two resistors, R1 and R2) and the internal reference is used, then the voltage divider can be designed to be protected against very high voltages. For example with a ATmega2560, internal reference of 2.56V, R1=47k, R2=10k. This can measure up to 14.6 V and be protected up to 78 V.


body:
I know this problem has been reported multiple times but in my case I think there is a different light on it.
My desktop is a w7x64 box and I also have a notebook with w10.
Both system have the arduino IDE 1.8.5 with the latest updates.
The desktop though has more boards and drivers as it is my main development system.
I have at ATmega2560 clone with CH340 which used to work on my desktop about half a year ago when I tried to get an LCD touch shield to work.
Yesterday I tried to resume on it and I got the ubiquitous timeout error.

So I removed the shield and tried the basic blink sketch but no change.
I tried an arduino nano and there was no problem to upload the blink sketch.
Then I tried different USB cables and ports but the timeout problem with the ATmega persisted.

So I went to the notebook and the ATmega worked like a charm.
Now I know that the board is ok as well as the cable.
The port is also ok as the nano worked on it smoothly.
I also tried the upload from an elevated command prompt with the verbose option but it gave me no further clue.

The output is below:

    C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -vvvv -CC:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega2560 -cstk500v2 -PCOM34 -b57600 -D -Uflash:w:T:\TMP\arduino_build_330193/Blink.ino.hex:i

    avrdude: Version 6.3-20171130
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0 -arduino14/etc/avrdude.conf"

             Using Port                    : COM34
             Using Programmer              : stk500v2
             Overriding Baud Rate          : 57600
    STK500V2: stk500v2_open()
    STK500V2: stk500v2_getsync()
    STK500V2: stk500v2_send(0x1b 0x01 0x00 0x01 0x0e 0x01 0x14 , 7)
    avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
    STK500V2: stk500v2_recv(): avrdude: ser_recv(): programmer is not responding
    avrdude: stk500v2_ReceiveMessage(): timeout

Does anybody have an idea how to further tackle the problem?

title: SOLVED: Strange phenomenon with avrdude: stk500v2_ReceiveMessage(): timeout only with ATmega250 on windows 7x64

Answers: 1

body:
I found the problem coming from a mismatch of the port speed setting and the baudrate in the avrdude command.
It seems that the ATmega is very sensitive to timing issues.
After I did set everything to 115200 it works on my w7 box like on the notebook.


body: I am building a Model Rocket for which I need arduino nano to log data.But,I dont know how to power it up once it goes off the ground.Can anyone explain?

title: How can I power up my Arduino Nano for project of Rocket Data logging?

Answers: 0


body:
I buy a SIM800L EVB 2.0 modul for Arduino (https://www.aliexpress.com/item/SIM800L-V2-0-5V-Wireless-GSM-GPRS-MODULE-Quad-Band-W-Antenna-Cable-Cap/32465337183.html).

First I tested modul with all pins connect to Arduino. Modul successfully response on AT commands (but not register on network).

Next day is the same. So I connect modul +5V and GND to external power supply with 1000uF capacitor (as in comments on Aliexpress). Modul successfully connected to the network - my GSM number was accessible) (additional GND pin on modul I connect to Arduino GND on digital GND pin).

But modul is not longer respoding on AT command.

So I tested with USB - serial cable (pin 2 and 3 with GND 5) - modul register on network, but not response on AT command (tested via Putty with different baud speed) - no answer.

What else can I try? How to tested if Rx and Tx on modul works or how to know if I accident burned pins on modul or Arduino or USB-serial cable.

Thanks for every reply.

title: Arduino, RS232 and SIM800L EVB 2.0 (not responding on AT command)

Answers: 0


body:
I have a remote controller for a portable heater, and working on a small project to be able to control the fan on/off from an arduino with Bluetooh HM-10 module. I thought a solenoid might work by mounting on top of the remote but it doesnt have enough force, I want to remove/desolder the mechanical button and figure out a way to control it without the switch but kind dont really know what circuit
I should use, kind of just learning how to use arduino.

Images of remote and button traces below.

Any idea how I could wire this up to arduino via some switch/relay circuit? Any circuit design / schematic would be helpful

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

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

  [1]: https://i.stack.imgur.com/mwuYO.jpg
  [2]: https://i.stack.imgur.com/FbZBe.jpg

title: Replace mechanical switch with electrical switch or relay

Answers: 1

body:
I would unsolder the switch then solder in a FET in the configuration shown below. The FET will act as a switch and may be controlled with any digital output from your Arduino board. When selecting a FET makes sure you find something that will fit the foot print you have to work with on your board, and the gate-source threshold voltage is rated to handled 5V.

[![circuit][1]][1]

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


body:
I'm not very advanced in Arduino "core" functions, so I need your help.

I'm using a Solid State Relay in order to control a heating element, with a PID Library (PID_v1.h) to obtain the OUTPUT of the PWM.

The code itself is not a problem, so that I'll not post it here.

Summarizing, this is the code where I send the PWM to the Relay:
    analogWrite(RELAY_OUT, outputValue);

I've found in this [article][1] that:
"The analogWrite function is used to set the duty cycle of a PWM pulse train that operates at approximately 500 Hz. Thus, with a frequency = 500 Hz, the period is = 2 ms."

My concern is that the response time of the relay (FOTEK SSR-60 DA) is 10ms (to turn on or to turn off), but I DO NOT KNOW how to configure Arduino PWM to work accordingly to this Relay, in a period greater than 10ms.

I've found in some pages some people changing the clock frequency in order to have a "fast pwm", but I need to know what values I have to use to get a "slow pwm", for a period greater then 10ms.

Can you help me with that? I've been searching a lot for this answer, but I could not find any "definitive"answer.

Thank you in advance!

Everton

  [1]: http://web.cecs.pdx.edu/~gerry/class/EAS199A/topics/pdf/PWM_output_Arduino.pdf

title: Arduino Mega PWM - 100ms Period - SSR and Heater

Answers: 2

body:
Use ATmega PWM registers directly, in order to achieve about 100Hz PWM (10ms period).

This is an example of 10ms PWM period with 50% duty cycle on Arduino Mega (Pin D11):

    /* Setup PWM pin D11 as Output */
       pinMode(11, OUTPUT); //D11/PB5/OC1A

       /* Timer/Counter Control Registers: TCCRxx */
       TCCR1A = 0;            //Clear register
       TCCR1B = 0;            //Timer/Counter stopped (CS12=0,CS11=0,CS10=0)

       TCCR1A = (1<<WGM11)  | //Fast PWM mode 16-bit (WGM13=1,WGM12=1,WGM11=1,WGM10=0)
                (1<<COM1A1);  //Set output HIGH during Duty Cycle peiod of OC1A

       TCCR1B = 2                     |   //Prescaler: divide by 8
                (1<<WGM12)            |
                (1<<WGM13);

       /* Set PWM frequency */
       ICR1   = 20000; // Period expressed in tick (10ms)

       /* Clear PWM counter */
       TCNT1  = 0;

       /* Set duty cycle to 50% */
       OCR1A  = 10000;

I didn't test it, but I think that it's correct.

Read [this][1] and [this][2] for details.

  [1]: http://playground.arduino.cc/Main/TimerPWMCheatsheet
  [2]: https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM

body:
I'd suggest using the [TimerOne library](https://github.com/PaulStoffregen/TimerOne).

Call `Timer1.initialize(10000)` in `setup`.
Then call `Timer1.pwm(pin, duty);` in your loop. Where `pin` is 11, 12, or 13 for the MEGA, and `duty` is between 0 and 1023.


body:
In my project I have an issue. I have more than 2 mesh network with Arduino + nRF240L01 with a star topology (one Arduino is master another 6 Arduino + nRF240L01 are the slaves likewise I can be able to have more than 2 networks).

So I want to communicate only with one mesh network but not to another. Is the different addressing enough to separate the networks? And I would like to have sample code as well.

title: Mesh with star topology

Answers: 0


body:
After searching the internet and trying different examples, I always get the same wrong response in the serial monitor.

Picture 1 shows the wrong results. At first i thought it was decimal and I just had to convert it to ASCII. But that wasn't the problem.

Picture 2 shows the results that I expect. It's from the Logic Analyzer that sits on a breadbord to "sniff" the communication.
I expect N+0000.0\r

Picture 3 shows the settings or the logic analyzer. Please ignore the "SPI MISO" it's just an old description.

I have no other approach left in my mind.

I would appreciate any hint. :) Thank you in advance.

You will find the Arduino sketch below the pictures.

[![Serial Monitor][1]][1]

[![Logic Analyzer][2]][2]

[![Settings Logic Analyzer][3]][3]

  [1]: https://i.stack.imgur.com/OLwk7.jpg
  [2]: https://i.stack.imgur.com/qyYe4.jpg
  [3]: https://i.stack.imgur.com/RAua3.jpg

    #include <SPI.h>
    #include <Controllino.h>  /* Usage of CONTROLLINO library allows you to use CONTROLLINO_xx aliases in your sketch. */

    const int numBytes = 20;
    int incomingBytes[numBytes];   // for incoming serial data

    void setup() {

      /* Initialize serial port for debug messages. */
      Serial.begin(9600);

      /* Initialize CONTROLLINO RS485 direction control DE/RE pins and Serial3 */
    Serial3.begin(9600,SERIAL_8N2); //Initialisierung Serial Controllino(RS 485)
      //Beim Mega oder Maxi Zugang zum /OVL pin und RS458 /RE DE Pins
      //Zuweisung /RE (PJ5) DE (PJ6) pins als Ausgang (1). Für /OLV (PE7) als Eingang (0)
      DDRJ |= B01100000;
      DDRE &= B01111111;

      //Controllino_RS485Init(9600);
      //Controllino_RS485RxEnable();

      Serial.println("Recieving RS485...");
    }

    void loop() {

    DatenEmpfangen();
    delay(1000);
    DatenAnzeigen();
    }

    void DatenEmpfangen()
    {
      static byte ndx = 0;
      int rc;
      PORTJ &= B10011111;//Empfangen MODUS
      //Controllino_RS485RxEnable();
      delay(1000);
      do
      {
        if (Serial3.available() > 0)
        {
         // digitalWrite(CONTROLLINO_D1, HIGH);
         rc = Serial3.read();

         incomingBytes[ndx] = rc;
         ndx++;
        }
      } while (Serial3.available() > 0);
    }

    void DatenAnzeigen()
    {
      static byte count = 0;
      //int Xor = 0;
      //Xor = receivedIntegersA[0];
      Serial.println("Daten");
      for (count=0;count<9;count++)
      {
        Serial.println((incomingBytes[count]));
      }

    }

title: RS485 Wrong Results in Serial Monitor(Controllino) - Right Results with Logic Analyzer

Answers: 0


body:
I have node mcu with ESP8266 wifi module. When i am trying to upload an example code then its not working.

This is the Error:-

    inline PubSubClient* PubNub::subscribe(const char* channel, int timeout)

                          ^

    exit status 1
    invalid conversion from 'char' to 'const char*' [-fpermissive]

Code:-

    #include <ESP8266WiFi.h>
    #define PubNub_BASE_CLIENT WiFiClient
    #define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

    #include <PubNub.h>

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

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

    char pubchannel = 'demo_keyset';
    char subchannel = 'demo_keyset';

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

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

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

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

    void loop() {
        /* Maintain DHCP lease. For other HW, you may need to do
           something else here, or maybe nothing at all. */

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

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

        delay(1000);
    }

Code is taken from pubnub arduino github example - https://github.com/pubnub/arduino/blob/master/examples/AdafruitFeatherM0WINC1500/AdafruitFeatherM0WINC1500.ino

title: Error - invalid conversion from 'char' to 'const char*', Not able to connect on pubnub server using node mcu

Answers: 1

body:
problem was in the declaration of API keys and channel on the above code

Here is the right code:-

    const char * pubkey = "publisher key from your account";
    const char * subkey = "subscriber key from your account";

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


body:
The starter code.

    #include <Stepper.h>

    const int stepsPerRevolution = 120;  // change this to fit the number
    // for your motor of steps per revolution

    // initialize the stepper library on pins 8 through 11:
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

    int stepCount = 0;         // number of steps the motor has taken
    int LEDPin = 13;
    void setup() {
      // initialize the serial port:
      Serial.begin(9600);
      pinMode(LEDPin,OUTPUT);
    }

    void loop() {
      // step one step:
      myStepper.step(1);
      Serial.print("steps:");
      Serial.println(stepCount=456);
      stepCount++;
      delay(35);
    }

I want a light to flash in 15 sec increments while my stepper keeps moving. I basically want to combine that code with this one:

    int LEDPin = 13;
    void setup()
      pinMode(LEDPin,OUTPUT);
    void loop()
    {
      digitalWrite(LEDPin,HIGH);
      delay(6000);
      digitalWrite(LEDPin,LOW);
      delay(6000);
    }

title: I need help makeing a light flash while a stepper is constantly moving

Answers: 2

body:
In your loop() function, call two new functions. Let's call those maybeStep() and maybeBlink(). Each one of those reads the time, millis(), and subtracts the saved time when it last performed its action (stepping or toggling the LED). If that difference is >= the interval for that action, do the action and update the saved time to the current time.

Remember to make the saved times 'static' (or global) so they won't get over-written when these function return.

The BlinkWithoutDelay example program gives the general idea of how to read the clock instead of calling delay(), to decide when to perform each action.

Update:

>  new at Arduino and don't quite know what you mean?

Your loop function would something like this:

    void loop(){
       maybeStep();
       maybeBlink();
    }

Notice that loop now does nothing but call your action functions. Here's an outline of one of the action functions:

    void maybeStep(){
       if the time_now > than the time_we_last_stepped by 35 millisec, then
          step again and store the new time_we_last_stepped;

       return;
    }

Notice that this function may or may not take a step! It decides whether to step by reading the time and comparing it to the time of the previous step. But either way - step, or no step - it returns quickly. The maybeBlink() function will work exactly the same way: compare the time it last toggled the LED on or off to the amount of time it should wait between toggles. Then either toggle it (and save the time and on/off state) or not, and in any case, return to the loop.

Done this way, your loop() function will call those action function very frequently - way more often than the actions need to take place. Most of those times, nothing will happen. But every once in a while (a "tiny while" in human terms), one of those functions will take a step or switch the LED. If you write your code this way, loop() could call dozens or hundreds of such functions and all of those actions could still take place on time.

The key to this programming technique - called non-blocking programming - is that the action functions be *very brief* . They must decide quickly whether something needs to be done, and either do it or not, then return immediately.

body:
The `delay()` function causes the Arduino program to stop in it's tracks and "count to 100". While it's doing that, it's not doing **anything else**.

Therefore delay is not an option when you're trying to do more than one thing at a time.

you need to rewrite your code to use the `millis()` function to tell if your desired amount of time has passed. something like this:

    unsigned long nextLEDTime = 0;
    bool ledState = false;
    #define delay 6000

    int LEDPin = 13;
    void setup()
      pinMode(LEDPin,OUTPUT);
    void loop()
    {
      if (millis() >= nextLEDTime) //if it's time to toggle the LED
       {
         ledState = ! ledState;  //Invert the LED state
         digitalWrite(LEDPin, ledState);
         nextLEDTime = millis() + delay;  //Set nextLEDTime to the next time we need to do something
       }
    }

Then you need to do the same thing with your stepper motor code, creating a separate variable to track the next time you want to do something with the stepper motor.

Put all your code in a single loop function that checks bot the nextLEDTime and the nextStepperMotorTime and takes appropriate action at the correct time for each thing you want to handle.


body:
I have been working on an Arduino based call and message project which I am following from this link https://circuitdigest.com/microcontroller-projects/call-and-message-using-arduino-sim900-gsm.
This project uses a membrane keypad for inputting the phone number and etc., but I intend to use a TTP229 16 channel Touch sensor module.

I need help in taking input from the touchpad rather than the keypad. As I need to submit the project within a month it is my humble request if someone can help.
Thanks for replying!

title: Interfacing TTP229 touch sensor with arduino and gsm module

Answers: 0


body:
I have 8 8x8 WS2812 Matrix LED boards connected together to make 2 16x16 matrices. I have them connected with Dupont wires.

I also power the 2 16x16 with Dupont wires that are connected to a 5v 60Amp PSU (More Leds will be added later). The PSU power  should easily support the LED power requirements however, if I set the brightness anything over 30...the first matrices start to get reddish at the end. They start white but as the end they are orange/red.  If I set the brightness to 20-25 they are white. So there must be something with the power but I have 60amps...Can it be that the Dupont cables are the bottleneck? The cables don't get hot...so I guess they are ok?

Any help is highly appreciated.

Thanks
V.A

title: WS2812 Matrix colour problem. Power?

Answers: 1

body: Use at least AWG20 and power each possible spot on the matrices (in and out). All the energy not reaching the LEDs is fried in the DuPont wires. Use Ohms law.


body:
The Arduino MKR WIFI 1010 product page says "The microcontroller on the MKR WIFI 1010 runs at 3.3V, which means that you must never apply more than 3.3V to its Digital and Analog pins. Care must be taken when connecting sensors and actuators to assure that this limit of 3.3V is never exceeded. Connecting higher voltage signals, like the 5V commonly used with the other Arduino boards, will damage the MKR WIFI 1010."

and yet it only has a 5V pin. I have a sensor that requires a 3.3V pin so I'm guessing my only option is to use a Logic Level Converter.

My question is if the MKR Digital and Analog pins can only take 3.3V, why is there only a 5V pin instead of a 3.3V pin to connect to a breadboard?

title: MKR WIFI 1010 Providing 3.3V to breadboard

Answers: 1

body:
In short: VCC = 3.3V

The [Arduino MKR WiFi 1010][1] board documentation is not complete. Well, at least they have the warning that the processor is running at 3.3V and the voltage levels of the pins should never be above 3.3V.

The page of the [Arduino MKR ZERO][2] has more information in the "documentation" tab. The **VIN** pin is the 5V power input, the **5V** pin is unregulated 5V output (when the board is powered by USB or the VIN pin) and **VCC** is the regulated 3.3V output.

The term "VCC" means that it is the voltage at which the processor is running. Since it is a 3.3V Arduino board, it is the 3.3V voltage pin. That 3.3V should be used to power sensors. The "Tech Specs" tab at the MKR ZERO tells that it can supply up to 600 mA. That is the same for the MKR WiFi 1010, because the same AP2112K-3.3 voltage regulator is used.

  [1]: https://store.arduino.cc/arduino-mkr-wifi-1010
  [2]: https://store.arduino.cc/arduino-mkrzero


body:
I'm making a Data Acquisition System for force impact usign an AD7606 from Analog Devices, an Arduino DUE and a load cell. I already tested it following [this guide][1] an making the proper changes for Arduino DUE and some potentiometers for simulating the input signals. I can read variable 1-5 V signals pretty good but when I tried to read mV signals from my load cell I can't see any changes in the Visuino Scope. I've read some forums and using an amplifier is recommended. However, when I read the AD7606 datasheet it says that since it has a High Analog Input Impedance and Internal amplifiers, a previous  amplification phase isn't needed. Also, I want to avoid the noise from the external amplifiers.

I also tested my load cell using the HX711 ADC and it works fine, but I can't use it for my application because of its limited sampling frequency (80 Hz). AD7606 can give up to 200 kilo samples per second.

Does any one knows if I'm missing something for my input signal? if an amplifier is really nedded can you recommend me one?

Thanks

  [1]: https://www.hackster.io/mitov/connect-ad7606-8-channel-16-bit-adc-in-16-bit-parallel-mode-4a6cfc

title: AD7606 DAQ and datalogging

Answers: 0


body:
I am trying to call a function that will turn a stepper motor a number of steps depending on the value submitted through the serial console. For an example, if I submit 50, the motor should turn 50 steps clockwise (and counter clockwise for  a negative value).

    #include <Stepper.h>
    #define STEPS 200
    Stepper stepper(STEPS, 8, 9, 10, 11);

    int serial_input = Serial.read();

    void setup() {
    Serial.begin(9600) ;
    stepper.setSpeed(30);
    }

    void loop() {
    }

    void turnMotor(serial_input){
      stepper.step ( serial_input ) ;
    }

And here are the errors I get:

    Motor4.ino:12:28: error: variable or field ‘turnMotor’ declared void
    Motor4.ino:12:16: error: ‘serial_input’ was not declared in this scope
    Motor4.ino:117:28: error: variable or field ‘turnMotor’ declared void

Thank you

title: Help with placing a function please

Answers: 1

body:
As Juraj already explained, you cannot use Serial.read() outside a function.

What you probably want is to call it within the loop, or a function called from loop (via other functions).
Than you can call also turnMotor from Loop or a function called from loop. The value (int serial_input) probably doesn't have to be global anymore, but that depends on the time where you assign the value and where you call turnMotor.


body:
Well I am working on old textile machines, it is taking motor RPM with ISR. I want to read this RPM and publish on web. but the output voltage of this old system is 0 and 22 Volt. (0 Volt when the infrared light comes into the gap in the disk, 22 volt  when the infrared light see the photocell). if I try to read this data I see 17.000 - 18.000 RPM while actual RPM was 1600. I cant read true RPM. I suspect input signal voltages which is 0 and 22 Volts. I don't think Arduino UNO works in this voltage range but I cant see any info at [docs][1]. voltage divider with 0 - 2.2 volts I have dropped but still did not work. what is the ideal voltage level for attachInterrupt() command. I am using [klon arduino uno][2] (Arduino Uno R3 SMD CH340 Chip - Klon Arduino Uno )

Also are there ane filter  to prevent interference I am using long wire (100 meter)?

this is my [code][3]

    int encoder_pin = 2; // pulse output from the module
    unsigned int rpm; // rpm reading
    volatile byte pulses; // number of pulses
    unsigned long timeold;
    // number of pulses per revolution
    // based on your encoder disc
    unsigned int pulsesperturn = 12;
    void counter()
    {
       //Update count
       pulses++;
    }
    void setup()
    {
       Serial.begin(9600);
       pinMode(encoder_pin, INPUT);
       //Interrupt 0 is digital pin 2
       //Triggers on Falling Edge (change from HIGH to LOW)
       attachInterrupt(0, counter, FALLING);
       // Initialize
       pulses = 0;
       rpm = 0;
       timeold = 0;
    }
    void loop()
    {
       if (millis() - timeold >= 1000) {
          //Don't process interrupts during calculations
          detachInterrupt(0);
          rpm = (60 * 1000 / pulsesperturn )/ (millis() - timeold)* pulses;
          timeold = millis();
          pulses = 0;
          Serial.print("RPM = ");
          Serial.println(rpm,DEC);
          //Restart the interrupt processing
          attachInterrupt(0, counter, FALLING);
       }
    }

  [1]: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
  [2]: https://www.direnc.net/arduino-uno-r3-smd
  [3]: https://www.electroschematics.com/12275/motor-speed-sensor-module-circuit/

title: Ideal voltage level for attachInterrupt()

Answers: 0


body:
I'm developing a program that uses the HTML server in the WiFi101 library.

My hardware does not have SD card storage so all source html needs to be stored as strings in the sketch at compile time.  To aid in development I want to keep my html files separate from the sketch and include them at compile time.

Is there a way to use #include in the Arduino IDE and assign the included file to a string/char array constant?  If so can the path to the included file be relative to the sketch's path?

Notes:
Similar question on Stack overflow:
https://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char

Edit:
There are lots of great answers here to solve this in a more robust fashion. The correct thing to do is setup a proper build system.  If I were to set this up I'd be temped to try something like [Gulp][1] since you could easily minify/lint your web content.
As this is a small project I ended up just running the HTML through a minifier service and copy/pasted into strings.

  [1]: https://gulpjs.com/

title: How to assign text stored in a local file to a string at compile time

Answers: 4

body:
C++ has 'raw string literals'. You can put a constant string, without escaping special characters, into the source code between an opening and closing 'tag'. You can choose the tag to be something that is not in the raw string. In following example the tag is `=====`.

    const char* s1 = R"=====(Hello
    "World")=====";

is same as

    const char* s2 = "Hello\n\"World\"";

This way you can put your large strings into separate .h files and include them. On AVR use PROGMEM to save RAM.

body:
This will probably not work with the Arduino IDE. If you are willing to
go through a Makefile-based workflow, you can install this [generic
Arduino Makefile][makefile], which should make things easier.

With that Makefile installed in `/usr/share/arduino/Arduino.mk`, the
following test worked on an Arduino Uno. It is based on the objcopy
trick from the article [Embedding of binary data into
programs][objcopy].

Project's **Makefile**:

    BOARD_TAG    = uno
    MONITOR_PORT = /dev/ttyACM0
    OTHER_OBJS   = text.o

    include /usr/share/arduino/Arduino.mk

    text.o: text.txt
     avr-objcopy -I binary -O elf32-avr -B avr:5 $< $@

**text.txt**:

<!-- language: lang-none -->

    Hello, World!

**include-blob.ino**

    extern "C" const uint8_t _binary_text_txt_start[];
    extern "C" const uint8_t _binary_text_txt_size;

    void setup() {
        Serial.begin(9600);
        Serial.write(_binary_text_txt_start, (size_t) &_binary_text_txt_size);
    }

    void loop(){}

The program just prints “Hello, World!”, but if you modify text.txt and
retype `make`, it will print whatever you had in this file. Please note
that the text is not NUL-terminated, so you have to use the
`_binary_*_size` symbol to know its size.

[makefile]: https://github.com/sudar/Arduino-Makefile
[objcopy]: https://www.devever.net/~hl/incbin

body:
An easy way to do this is to write a C program to convert your files that you want included into your source into a form that looks like:

    byte file_001[] = { 0x00, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0A,
                        0x01, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0C,

                        ...

                        0x03, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0C };

The converted file can contain binary data without issue instead of just ASCII.

You can then access the file directly using:   file_001[index]

body:
I found another way to include a literal file (html, css, or other) and assign it to a constant string without resorting to make files:

Add one line of code on top of your html (css, js, etc) file, and another at the bottom, and save it with an extra .h extension. Then include that file in de Arduino IDE.
This could easily be done by a (manually executed) script, every time those files are changed.

    const char *indexHtml = R"====( // added by script
    <html> <!-- original .html file -->
    .
    .
    .
    </html> <!-- end .html -->
    )===="; // added by script

The variable name can be derived from the original filename. The result is saved with an extra .h extension. In the .ino (or .cpp) you can then include this file:

    #include index.html.h

This will compile in the Arduino IDE.


body:
I've been trying to send a put request from my esp8266 for a while not but I can't figure out why it doesn't work and there are barely any posts about put requests online
I keep getting errors around ``int httpCode = http.sendRequest("PUT", String(data));``

Error log: https://gist.github.com/dkbay/ab3fedf5e89d841d25b24fb829df74ef

```#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define LED_BUILTIN 2

const char* ssid     = "Some SSDI";
const char* password = "Some wifi password";

int wifiStatus;

void setup() {

  Serial.begin(115200);\
  pinMode(LED_BUILTIN, OUTPUT);
  delay(200);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Your are connecting to;");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.print(".");
  }

}

void loop() {
  wifiStatus = WiFi.status();

  if(wifiStatus == WL_CONNECTED){

    HTTPClient http;

    http.begin("http://google.com/");
    http.addHeader("Content-Type", "application/json");
    String data = "{\"on\":false}";
    int httpCode = http.sendRequest("PUT", String(data));
    String payload = http.getString();

    Serial.println(httpCode);
    Serial.println(payload);

    http.end();
     Serial.println("");
     Serial.println("Your ESP is connected!");
     Serial.println("Your IP address is: ");
     Serial.println(WiFi.localIP());
  }
  else{
    Serial.println("");
    Serial.println("WiFi not connected");
  }
  delay(1000); // check for connection every once a second

}

title: HTTP PUT method on NodeMCU/ESP8266

Answers: 1

body:
    HTTPClient http;
    http.begin("http://google.com?on=false");
    http.addHeader("Content-Type", "application/json");
    int httpCode = http.sendRequest("PUT", "");
    String payload = http.getString();

try with this code, if server .php,
get data by $_REQUEST


body:
I've been chipping away at a project for a long time now and I've found a serious bug.

Basically the user has an 8x8 grid, and each cell in this grid has a number of properties.
I want to be able to save all of these properties as a 'profile' within the EEPROM, and previously this worked OK but now seems to have a few bugs.

The most prominent of which is that when I save a grid to a profile (Say profile 3), and then load the next profile (profile 4, in this case) the far right column of profile 3 appears in the far left column of profile 4.
LikeWise, saving a filled in grid to profile 1, and then saving an empty grid to profile 2 causes the RIGHT hand column of profile 1 to be cleared.

It used to work great in a previous version but there was completely different hardware in place supporting the GUI making it impossible to load older versions of the code and test how it was working then.

Here is the code where I save / load profiles
```

#include <EEPROM.h>
#include"EEPROMAnything.h"
const int profileSize = 224; // Actually everything is only half the size you thought (WTF but ok)

void saveProfile(int profileNum)                               // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Saving...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8); // Original
  tft.print(" Bytes");
  setLine2();
  tft.print("please wait");
//  tft.sendBuffer();

  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      saveConfiguration.ROMcellType[ROMRow][ROMCol]      = cellType[ROMRow][ROMCol];
      saveConfiguration.ROMindexVal[ROMRow][ROMCol]      = indexVal[ROMRow][ROMCol];
      saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol]  = MIDIVariable[ROMRow][ROMCol];
      saveConfiguration.ROMcellChannel[ROMRow][ROMCol]   = cellChannel[ROMRow][ROMCol];
      saveConfiguration.ROMorientation[ROMRow][ROMCol]   = orientation[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol]  = faderGroundX[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol]  = faderGroundY[ROMRow][ROMCol];
    }
  }

  EEPROM_writeAnything((profileNum*profileSize), saveConfiguration);

  delay(500);
  menuState = 1; // Go back to main menu
  menuLocatorY = 0; // Otherwise text will not show on next screen;
  updateScreen();
}
//{EEPROM_writeAnything(profileNum*profileSize, configuration);}

void loadProfile(int profileNum)                              // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Loading...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8);
  tft.print(" Bytes.");
  setLine2();
  tft.print("please wait");

  initGrid(); // Clear any information regarding the current grid. Shouldn't really be neccesary but makes code safer.

  EEPROM_readAnything(profileNum*profileSize,saveConfiguration);
  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      cellType[ROMRow][ROMCol]      = saveConfiguration.ROMcellType[ROMRow][ROMCol];
      indexVal[ROMRow][ROMCol]      = saveConfiguration.ROMindexVal[ROMRow][ROMCol];
      MIDIVariable[ROMRow][ROMCol]  = saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol];
      cellChannel[ROMRow][ROMCol]   = saveConfiguration.ROMcellChannel[ROMRow][ROMCol];
      orientation[ROMRow][ROMCol]   = saveConfiguration.ROMorientation[ROMRow][ROMCol];
      faderGroundX[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol];
      faderGroundY[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol];

      /*
      if (cellType[ROMRow][ROMCol] == 3)
      {
        customValue = orientation[ROMRow][ROMCol];
        customMessage =   indexVal[ROMRow][ROMCol];
        MIDIVariable[ROMRow][ROMCol] = 0;   // Sets read fader value to 0 initially,   the customvalue variable is used to control physical orientation in this function
        customChannel = cellChannel[ROMRow][ROMCol];    // The MIDI channel the given cell is assigned to
        initType3(ROMRow,ROMCol);
      }
      */

    }
  }

    // Here we go back to the grid view
    delay(500); // Just so user can see message
    menuState = 2; // Go back to Grid View
    menuLocatorX = 0;
    menuLocatorY = 0; // Otherwise text will not show on next screen;
    updateScreen();
}
//{EEPROM_readAnything((profileNum*profileSize), configuration);}

```

Here is the declaration of the struct I am using
```
//-------------------------------EEPROM STRUCTURE -------------------------------------------
struct config_t   // I think this will allow EEPROM saving made easy
{
  int ROMcellType[8][8];  // [Row][Column] States the type of input assigned to the cell.  Top left = 0,0 Row, Column    // Celltype 9 will be a reservation cell for the faders.
  int ROMindexVal[8][8];       // States the note value / Command  assigned to the cell
  int ROMMIDIVariable[8][8];   // Used to retain desired velocity / Current value of continuous input.
  int ROMcellChannel[8][8];    // The MIDI channel the given cell is assigned to
  int ROMorientation[8][8]; // Keeps track of the direction of orientation of large modules
  int ROMfaderGroundX[8][8]; // Keeps track of where the 'root' of the fader is
  int ROMfaderGroundY[8][8]; // Keeps track of where the 'root' of the fader is
} saveConfiguration;
//--------------------------------------------------------------------------------------------
```

IndexVal, cellType, etc are all global variables (I know, I know, global variable bad)

And last of all, the header file with my base level EEPROM functions
```
#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

```

It's been a while since I wrote this code so I'm a little lost in it myself.
I should probably add that if I save to profile 1, mess around testing the other profiles, then load profile 1 again it's always correct.

Also, the part where it prints sizeof(saveConfiguration) does return 224, and I've also removed the "/8" just to check that there was no rounding error.
If I double the value of profileSize it simple halves the number of profiles I have available by spacing them out by the size of the struct in memory.

Please ignore the (if cellType == 3) section, this is used for a type of object that uses 3 consecutive cells and is a whole can of worms in itself.
For the sake of this test I'm just using celltypes that are modules that use a single cell.

I feel like I really need to make some progress with this soon for the sake of my own mental wellbeing.

Anyone able to help?

Further info for the commenters:
The board I am using is a PJRC teensy 3.5.

The /8 was to display the number of Integers being saved. I think when I originally wrote this code I mistakenly thought that the device was 8 bit, and estimated the profile size to be 448.
I believe the EEPROM is 16 bits wide?

title: What's going wrong with my EEPROM?

Answers: 1

body:
Depending if you are on an 8 bit or 32 bit Arduino your profile is either 896 or 1792 bytes in size. *Not* 224. (Why do you think /8 is an option?)

I am guessing that you are on a 32-bit Arduino since 1792/8 = 224.

1792 is more EEPROM than any normal Arduino has, anyway.  Even if you were on an 8-bit Arduino and the profile size was 896 there would only be room for one in the EEPROM.

I think you need to re-think your strategy somewhat to either massively reduce the amount of data you are saving, or change where you are storing the data to.


body:
I am working on a project where I have 4 DC motors that is controlled by 2 L293D motor drivers.  2 of the motors act as the wheels of the robot, and the other 2 act as a mop.

The Arduino board is powered through the USB port.  The DC motors are powered by the L293D motor driver through the 5V pin on the Arduino.  Alongside the motors, an ultrasonic sensor and a water sensor is also using the 5V pin.

This is what the robot should be doing:
The robot will move forward.  If it senses an obstacle through the ultrasonic sensor, it will turn right.  If it senses water through the water sensor, the robot will stop moving and the mop will start spinning.  After cleaning the water spillage, it will move forward again, just like what it did before.

It seems like the motors are not getting enough power, because whenever I place it on the floor, it doesn't move.

The base / platform of the robot is a plywood, which is heavy for the robot, and also which I think is a factor that affects the spinning of the wheels.

I also have a 9V battery, which I think could power the motors, but I don't know how to connect it.  How am I supposed to connect it to the L293D motor driver? I think, I should connect the positive side of the 9V battery to the VCC 2 pin of the L293D motor driver. But, where should I connect the negative side of the 9V battery?

title: How to properly run 4 DC motors with an Arduino?

Answers: 1

body:
With out knowing the demands of the motors (how much current they need under a given load) it is difficult to answer your question.  But, in most Arduino designs:

 1. Motors are powered independently of the Arduino.  And when Arduino Uno is powered through its USB port it should be realized that most [common USB power sources are only obliged to offer up to 500mA of current][1].
 2. The motor's power source likely needs to be capable of providing several Amps. A [common 9 Volt battery][2] only contains about 500mAh and will likely drain in 10s of minutes if it works at all.

Consider the power pack used in common portable electric power tools.  This should give you a perspective of the type of power you will need in order to create a robot with multiple motors.

  [1]: https://en.wikipedia.org/wiki/USB
  [2]: https://en.wikipedia.org/wiki/Nine-volt_battery#Technical_specifications