body:
The first one reads from sensors and displays it, the second code receives an incoming byte to control LEDs. I tried to combine it but i don't know why it doesn't work. Please help me out. I need it for my project to run both of them.

In my java netbeans i have two GUIs. For monitoring(first code) and controlling(second). I want it both to run with only one combined code in arduino.

I tried to use if else statement for the arduino to know what to do. Not working also. I think i just missed something

    const int model = 0;

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

    }

    float sensitivity[] ={
          0.185,// for ACS712ELCTR-05B-T
          0.100,// for ACS712ELCTR-20A-T
          0.066// for ACS712ELCTR-30A-T

         } ;

    void loop() {
    static unsigned long count=0;
    static float Vsum=0;
    float Vave=0;
    int volt = analogRead(A1);

    float voltage= map(volt,0,1023, 0, 2500)/100.0;
    Vsum=Vsum+voltage;

    static float Csum=0;
    float Cave=0;
     float milli = pow(10, -3);
     float current = (voltage / sensitivity[model]);
     float current1 = current*milli;

    Csum=Csum+current1;
    count++;
    Vave=Vsum/count;
    Cave=Csum/count;
    float watts = Vave*Cave;

    long milisec = millis();
    long time=milisec/1000;

     float energy = (watts*time)/3600;
    Serial.print(energy,6);
    Serial.println("Wh");
    delay(1000);

    }

And this is the second code. This receives byte from java to control LEDs

    int incomingByte;

    void setup() {
      Serial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
      pinMode(13, OUTPUT);
      pinMode(12, OUTPUT);
      pinMode(11, OUTPUT);
      pinMode(10, OUTPUT);
      pinMode(9, OUTPUT);
      pinMode(8, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(3, OUTPUT);
      pinMode(2, OUTPUT);
      pinMode(1, OUTPUT);
      pinMode(0, OUTPUT);

    }

    void loop() {
     // if (Serial.available()>0) {
        incomingByte = Serial.read();

        if(incomingByte == 0x01){
          digitalWrite(13, HIGH);
         Serial.println("ON");

        }else if(incomingByte == 0x00){
          digitalWrite(13, LOW);
           Serial.println("OFF");
        }

        if(incomingByte == 0x02){
          digitalWrite(12, HIGH);
        }else if(incomingByte == 0x03){
          digitalWrite(12, LOW);
        }

        if(incomingByte == 0x04){
          digitalWrite(11, HIGH);
        }else if(incomingByte == 0x05){
          digitalWrite(11, LOW);
        }

        if(incomingByte == 0x06){
          digitalWrite(10, HIGH);
        }else if(incomingByte == 0x07){
          digitalWrite(10, LOW);
        }

        if(incomingByte == 0x08){
          digitalWrite(9, HIGH);
        }else if(incomingByte == 0x09){
          digitalWrite(9, LOW);
        }

        if(incomingByte == 0x10){
          digitalWrite(8, HIGH);
        }else if(incomingByte == 0x11){
          digitalWrite(8, LOW);
        }

        if(incomingByte == 0x12){
          digitalWrite(7, HIGH);
        }else if(incomingByte == 0x13){
          digitalWrite(7, LOW);
        }

        if(incomingByte == 0x14){
          digitalWrite(6, HIGH);
        }else if(incomingByte == 0x15){
          digitalWrite(6, LOW);
        }

        if(incomingByte == 0x16){
          digitalWrite(5, HIGH);
       }else if(incomingByte == 0x17){
          digitalWrite(5, LOW);
        }

        if(incomingByte == 0x18){
          digitalWrite(4, HIGH);
        }else if(incomingByte == 0x19){
          digitalWrite(4, LOW);
        }

        if(incomingByte == 0x20){
          digitalWrite(3, HIGH);
        }else if(incomingByte == 0x21){
          digitalWrite(3, LOW);
        }

        if(incomingByte == 0x22){
          digitalWrite(2, HIGH);
        }else if(incomingByte == 0x23){
          digitalWrite(2, LOW);
        }

        if(incomingByte == 0x24){
          digitalWrite(1, HIGH);
        }else if(incomingByte == 0x25){
          digitalWrite(1, LOW);
        }

        if(incomingByte == 0x026){
          digitalWrite(0, HIGH);
        }else if(incomingByte == 0x027){
          digitalWrite(0, LOW);
        }

      delay(100);
    }

This is my sample code from javafx application

        try {
            if (tbLED12.isSelected()) {
                if (arduinoPort != null) {
                    arduinoPort.writeByte((byte) 0x02);
                    System.out.println("LED 12 ON");
                } else {
                    System.out.println("arduinoPort not connected!");
                }
            } else {
                if (arduinoPort != null) {
                    arduinoPort.writeByte((byte) 0x03);
                    System.out.println("LED 12 OFF");
                } else {
                    System.out.println("arduinoPort not connected!");
                }
            }
        } catch (SerialPortException ex) {
            Logger.getLogger(JavaFXApplication11.class.getName())
                    .log(Level.SEVERE, null, ex);
        }

title: How can I combine this two codes in one program? And use it in javafx application

Answers: 2

body:
Combining this code is all about synchronizing the reading of the sensors with the control sequences that are sent from the Java program.

The second program reads the Serial port continuously in the loop method. A better way would be to use a serial interrupt for this. Let me give you an example.

My code is written without an IDE so it is just an untested example. But hopefully I did not include errors ;-).

I use the first program as a base:

    const int model = 0;
    float sensitivity[] = {
      0.185,// for ACS712ELCTR-05B-T
      0.100,// for ACS712ELCTR-20A-T
      0.066// for ACS712ELCTR-30A-T
    } ;

    unsigned long count = 0;
    float         Vsum  = 0;
    float         Csum  = 0;

    long startTime = 0;

    void setup()
    {
      Serial.begin(9600);
      // setting the LED pins to output
      // I use a loop
      for ( int i = 2; i < 14; i++ )
      {
        pinMode( i, OUTPUT );
      }
    }

    void loop()
    {
      float Vave = 0;
      float Cave = 0;
      // pow is to expensive for the loop
      // I use a constant
      float milli = 0.001;

      if ( startTime = 0 ) startTime = millis();

      float voltage = map( analogRead( A1 ), 0, 1023, 0, 2500 ) / 100.0;
      Vsum = Vsum + voltage;

      float current  = ( voltage / sensitivity[ model ] );
      float current1 = current * milli;

      Csum = Csum + current1;

      count++;

      Vave = Vsum / count;
      Cave = Csum / count;
      float watts = Vave * Cave;

      // you did not use a time delta here,
      // but energiy it work over a time period
      long timeDelta = ( millis() - startTime ) / 1000;

      float energy = ( watts * timeDelta ) / 3600;
      Serial.print( energy, 6 );
      Serial.println( "Wh" );

      serialHandler();

      delay( 1000 );
    }

    void serialHandler()
    {
       delay( 200 );
       while ( Serial.available() )
       {
         // get the new byte:
         int inByte = Serial.read();

         if(inByte == 0x01)
         {
           digitalWrite(13, HIGH);
           //Serial.println("ON");
         }
         else if(inByte == 0x00)
         {
           digitalWrite(13, LOW);
           //Serial.println("OFF");
         }
         else if(inByte == 0x02) digitalWrite(12, HIGH);
         else if(inByte == 0x03) digitalWrite(12, LOW);
         else if(inByte == 0x04) digitalWrite(11, HIGH);
         else if(inByte == 0x05) digitalWrite(11, LOW);
         else if(inByte == 0x06) digitalWrite(10, HIGH);
         else if(inByte == 0x07) digitalWrite(10, LOW);
         else if(inByte == 0x08) digitalWrite(9,  HIGH);
         else if(inByte == 0x09) digitalWrite(9,  LOW);
         else if(inByte == 0x10) digitalWrite(8,  HIGH);
         else if(inByte == 0x11) digitalWrite(8,  LOW);
         else if(inByte == 0x12) digitalWrite(7,  HIGH);
         else if(inByte == 0x13) digitalWrite(7,  LOW);
         else if(inByte == 0x14) digitalWrite(6,  HIGH);
         else if(inByte == 0x15) digitalWrite(6,  LOW);
         else if(inByte == 0x16) digitalWrite(5,  HIGH);
         else if(inByte == 0x17) digitalWrite(5,  LOW);
         else if(inByte == 0x18) digitalWrite(4,  HIGH);
         else if(inByte == 0x19) digitalWrite(4,  LOW);
         else if(inByte == 0x20) digitalWrite(3,  HIGH);
         else if(inByte == 0x21) digitalWrite(3,  LOW);
         else if(inByte == 0x22) digitalWrite(2,  HIGH);
         else if(inByte == 0x23) digitalWrite(2,  LOW);
         //else if(inByte == 0x24) digitalWrite(1,  HIGH);
         //else if(inByte == 0x25) digitalWrite(1,  LOW);
         //else if(inByte == 0x26) digitalWrite(0,  HIGH);
         //else if(inByte == 0x27) digitalWrite(0,  LOW);
       }
    }

**EDIT:**

 I changed the code a little bit according to Juraj comments. I also
commented the `Serial.println' s that had reported the LED 13 state.

body:
    void serialEvent();
    const int model = 0;
    float sensitivity[] = {
      0.185,// for ACS712ELCTR-05B-T
      0.100,// for ACS712ELCTR-20A-T
      0.066// for ACS712ELCTR-30A-T
    } ;

    unsigned long count = 0;
    float         Vsum  = 0;
    float         Csum  = 0;
    float         DecPowerRate = 9.8623 ;//kWh
    long          startTime = 0;
    float         no_voltage = 0.00;
    //float           address = 0;
    float         no_CURRENT = 0.000;
    float energy;
    long timeDelta;float consumption;float Kwatts;
    void setup()
    {
      Serial.begin(9600);
      // setting the LED pins to output
      // I use a loop
      for ( int i = 2; i < 14; i++ )
      {
        pinMode( i, OUTPUT );
      }
    }

    void loop()
    {
      float Vave = 0;
      float Cave = 0;
      float milli = 0.001;// pow is to expensive for the loop

      if ( startTime = 0 ) startTime = millis();

      float voltage = map( analogRead( A1 ), 0, 1023, 0, 2500 ) / 100.0;

      if( voltage >no_voltage){
      Vsum = Vsum + voltage;

      float current  = ( voltage / sensitivity[ model ] );
      float current1 = current * milli;

      Csum = Csum + current1;

      count++;

      Vave = Vsum / count;
      Cave = Csum / count;
      Kwatts = (Vave * Cave)/1000;
      }
        if (Cave >no_CURRENT){
      // you did not use a time delta here,
      // but energiy it work over a time period
      timeDelta = ( millis() - startTime ) / 1000;
      energy = ( Kwatts * timeDelta ) / 3600;
      consumption = energy * DecPowerRate;
    }

      //Serial.print( energy, 6 );
     // Serial.println( "kWh" );

      Serial.print( "P " );
      Serial.print( consumption, 6 );
      Serial.println( "/kWh" );
      delay( 1000 );

    }
    // naming convention for a serial interrupt
    void serialEvent()
    {
       while (Serial.available())
       {
     // get the new byte:
     int inByte = Serial.read();

     if(inByte == 0x01)
     {
       digitalWrite(13, HIGH);
       //Serial.println("ON");
     }
     else if(inByte == 0x00)
     {
       digitalWrite(13, LOW);
       //Serial.println("OFF");
     }
     else if(inByte == 0x02) digitalWrite(12, HIGH);
     else if(inByte == 0x03) digitalWrite(12, LOW);
     else if(inByte == 0x04) digitalWrite(11, HIGH);
     else if(inByte == 0x05) digitalWrite(11, LOW);
     else if(inByte == 0x06) digitalWrite(10, HIGH);
     else if(inByte == 0x07) digitalWrite(10, LOW);
     else if(inByte == 0x08) digitalWrite(9,  HIGH);
     else if(inByte == 0x09) digitalWrite(9,  LOW);
     else if(inByte == 0x10) digitalWrite(8,  HIGH);
     else if(inByte == 0x11) digitalWrite(8,  LOW);
     else if(inByte == 0x12) digitalWrite(7,  HIGH);
     else if(inByte == 0x13) digitalWrite(7,  LOW);
     else if(inByte == 0x14) digitalWrite(6,  HIGH);
     else if(inByte == 0x15) digitalWrite(6,  LOW);
     else if(inByte == 0x16) digitalWrite(5,  HIGH);
     else if(inByte == 0x17) digitalWrite(5,  LOW);
     else if(inByte == 0x18) digitalWrite(4,  HIGH);
     else if(inByte == 0x19) digitalWrite(4,  LOW);
     else if(inByte == 0x20) digitalWrite(3,  HIGH);
     else if(inByte == 0x21) digitalWrite(3,  LOW);
     else if(inByte == 0x22) digitalWrite(2,  HIGH);
     else if(inByte == 0x23) digitalWrite(2,  LOW);

       }
    }

This worked! Thanks for the help! <3


body:
It is very simple device, 2 continuous servos [FS5113R][1], rotates continuously in one direction. Here is device original content, which is this [servo shield][2] it looks like russian, and here is [library][3], I have added to Arduino IDE, also I have original code, which runs this device, given below.

I'm trying to figure out, what can I do with speed, to run it slower, I've tried change  delay(15); number to 1000, but it moves with same speed.  I've tried  increment variable  in  `while (z < 2) loop` and pass it with interval, but speed is same:

    #include <Wire.h>
    #include <Multiservo.h>

    #define SERVO_COUNT 2

    Multiservo servo[SERVO_COUNT];

    int pos1 = 0;
    int pos2 = 0;

    int z = 1;

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

      for (int i = 0; i < SERVO_COUNT; ++i)
      {
        servo[i].attach(i);
        servo[i].write(0);
      }
    }

    void loop(void)
    {
        while (z < 2){
            pos1 + 1;
            pos2 + 1;
            servo[1].write(pos1);
            servo[2].write(pos2);
            delay(15);
        }
    }

 Any advice, guide or example would be useful

  [1]: https://www.rhydolabz.com/robotics-servo-motors-c-155_157/fs5113r-std-13kgcm-continuous-rotation-metal-geared-servo-p-1463.html
  [2]: http://wiki.amperka.ru/продукты:multiservo-shield
  [3]: https://github.com/amperka/Multiservo

title: Continuous servo speed control with Arduino Uno controller and servo shield

Answers: 1

body:
The speed of your servo is controlled by the pulswidth of a square wave signal. According to the datascheet of the servo the motor stops on a pulsewith of about 1500 µSec (+- 5 µSec).

From 1500 to 900 μSec the motor turns clock wise. And it getting faster with decreasing pulsewidth.

From 1500 to 2100 μSec the motor turns counter clock wise. And it getting faster with increasing pulsewidth.

Next we have to check whether your shield and the library can handle that values and which value you have to give to the `servo[i].write(?)` function. I can read cyrillic but I do not understand russian good enough to read the f. manual. So I have to look into the code on GitHub (https://github.com/amperka/Multiservo/blob/master/library/Multiservo ).

Et voila:

    Multiservo::attach(int pin, int minPulse, int maxPulse)

You can define the min and max pulseWidth, that's great. Let's do it:

    #include <Multiservo.h>
    #define SERVO_COUNT 2

    Multiservo servo[SERVO_COUNT];
    // speed is 0 ( full speed CW )
    int speed = 0;

    void setup(void)
    {
      for (int i = 0; i < SERVO_COUNT; ++i)
      {
        servo[i].attach( i, 900, 2100);
        // 900 - 2100 is mapped from 0 to 180
        // so 90 is the middle where the motor stopps
        // 180 the motor runs as fast as possible CCW
        // 0 the motor runs as fast as possible CW
        servo[i].write( speed );
      }
    }

    void loop(void)
    {
       // Here I halt the program if the motor stops.
       // If you use a lower value than 89 you can halt the program
       // at the corresponding speed. If you use a higher value instead of 89
       // the motor starts rotating counter clockwise.
       // Do not use a value greater then 179 or less than 1.
       if ( ++speed > 89 ) speed = 90;

       servo[1].write( speed );
       servo[2].write( speed );

       delay(25);
    }

Ah, of cause I have not hte hardware, so I can not test the program. Use it as an example.


body:
I have a question.

I made a system which includes a servo, a stepper and a wiper motor :)
All these parts has one job to do and I can code it. But, I want to make 2 modes in this system Single Operation, Loop operation.

for example position 1-single operation, 2-loop operation.
I can code the loop operation thanks to arduino syntax :)

But I cannot code single one. I can read switch state detection.  I want to do exactly same things, but only one time when slide switch on the position.

The code is really long and it includes Turkish defines. If you need to see the code, let me know.

title: Running in loop or once according to a slide switch position

Answers: 1

body:
Let's assume the switch is on pin 9, that the pinMode() has already been set, and that the switch reads HIGH for loop operation.

    #define MODE_SWITCH  9
    #define DO_LOOP  HIGH

    // This loop will execute once if the mode-switch is off, or
    // will execute continously if the mode-switch is on:
    do {
      servo_things();
      stepper_things();
      motor_things();
    } while( digitalRead(MODE_SWITCH) == DO_LOOP );

in C/C++, 'do-while' loops always execute at least once, since the condition isn't tested until after the first pass through the loop. If the 'while' condition is satisfied (or TRUE), the loop will execute again, otherwise the loop will exit.


body:
I'm currently trying to program an STM32 with arduino, but along the way, i encountered some issues with pin modes. To be more specific, programming certain pins to certain modes. Some pins have consistent digital outputs like PC13, while others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.
[![PA12 digital output][1]][1]
here is what i get from PA12
[![PA11 digital output][2]][2]
here is what i get from PA11

i've read the pinout diagrams, and im not too sure if both mentioned pins can be used digitally according to this pinout diagram :
[![stm32 pinout diagram][3]][3]

can anyone help me explain what is going on, how do i program an STM32 with Arduino IDE exactly (stm32duino programming procedures, rule of thumb, etc), and can an stm32duino be used to do complex programs like an arduino like for example driving a motor with PWM in a balancing robot or do we have to use C or C++ using atollic TrueSTUDIO and all of those software?

  [1]: https://i.stack.imgur.com/eaGVP.png
  [2]: https://i.stack.imgur.com/s4gna.png
  [3]: https://i.stack.imgur.com/rMEGS.jpg

title: programming STM32 with arduino IDE issues

Answers: 1

body:
>others have wonky outputs like PA11 and PA12, despite being able to be used as digital outputs.

As the pinout diagram you included in the question yourself shows, PA11 and PA12 provide the USB interface.

You can't use those pins for both USB and other GPIO roles at the same time.

Your Arduino core and add-on bootloader are presumably using the USB port for programming and communication with the host PC.  Custom projects which did not use the pins for USB would be possible, but you'd likely be largely on your own and unable to use those particular Arduino components (or at least not without heavily modifying them).

There are other pins which have key purposes, too, for example those which support external clock crystals, those which provide the SWD debug interface, those which could provide serial UART output, etc - some designs can use these as generic I/O's but only by forgoing the unique functionality which many designs need them to provide.


body:
The following code intends to read from serial port and write the data byte by byte to a [24LC01B](http://ww1.microchip.com/downloads/en/devicedoc/21711c.pdf) EEPROM.

```
// 24LC01B PINS
// Pin 1, A0: float
// Pin 2, A1: float
// Pin 3, A2: float
// Pin 4, VSS: GND
// Pin 5, SDA: Arduino A4
// Pin 6, SCL: Arduino A5
// Pin 7, WP: Write/Protect = GND
// Pin 8, VCC: +5

#include <Arduino.h>
#include <Wire.h>

// I2C Bus address of 24LC256 EEPROM;
// if more than one eeprom, they will have different addresses (h/w configured);
#define EEPROM_ADDR 0x50
byte m_addr = 0;

#define MAX_ADDRESS 128

byte eeprom_write(byte address, byte *data, byte len)
{
    byte r = 0;
    for(byte i=0; i<len; )
    {
        Wire.beginTransmission(EEPROM_ADDR | m_addr);
        Wire.write(address + i);
        byte l = len > 8 ? 8 : l;
        Wire.write(data+i, l);
        r |= Wire.endTransmission();
        delay(3);
        i += l;
    }
    return r;
}

byte eeprom_read(byte address, byte *data, byte len)
{
    Wire.beginTransmission(EEPROM_ADDR | m_addr);
    Wire.write(address);
    byte tr = Wire.endTransmission();
    if(tr)
        return tr;

    Wire.requestFrom((uint8_t)(EEPROM_ADDR | m_addr), len);
    byte avail = Wire.available();
    if(avail < len)
        return 0xFF;

    for(int i=0; i < len; i++)
    {
        // store data in raw bcd format
        data[i] = Wire.read();
    }
    return 0;
}

void setup()
{
    Wire.begin();
    Serial.begin(9600);
    delay(500);
    Serial.println("Type something to store in EEPROM");
}

byte i = 0;

void loop()
{
    if(Serial.available())
    {
        byte data = Serial.read();
        int rc = eeprom_write(i, &data, 1);
        if(rc==0)
        {
            Serial.print("EEPROM[0x");
            Serial.print(i, HEX);
            Serial.print("] = 0x");
            Serial.print(data, HEX);
            Serial.print(" (");
            Serial.print((char)data);
            Serial.print(")");
            Serial.println();

            Serial.println("Reading from EEPROM:");
            for(byte j=0;j<MAX_ADDRESS;j++)
            {
                if(byte rc=eeprom_read(j, &data, 1))
                {
                    Serial.print("Error in reading from EEPROM (rc=0x");
                    Serial.print(rc, HEX);
                    Serial.println(")");
                }
                else
                {
                    Serial.print(data, HEX);
                    Serial.print(' ');
                    if((j + 1) % 8 == 0 && j != MAX_ADDRESS - 1)
                        Serial.print("| ");
                }
            }
            Serial.println("");
        }
        else
        {
            Serial.println("Write error.");
        }
        i++;
    }
}

```

Every time I write one byte to the EEPROM, I read back the data on it.
The result is a bit disappointing for me. I understand that `24LC01B` has a page size of 8 bytes. But, it does not make sense to me why the bytes withing the page rotate right every time I write into it

```
Type something to store in EEPROM
EEPROM[0x0] = 0x61 (a)
Reading from EEPROM:
61 4 4F 0 80 0 80 4 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x1] = 0x62 (b)
Reading from EEPROM:
4 62 4 4F 0 80 0 80 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x2] = 0x63 (c)
Reading from EEPROM:
80 4 63 4 4F 0 80 0 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x3] = 0x64 (d)
Reading from EEPROM:
0 80 4 64 4 4F 0 80 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x4] = 0x65 (e)
Reading from EEPROM:
80 0 80 4 65 4 4F 0 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x5] = 0x66 (f)
Reading from EEPROM:
0 80 0 80 4 66 4 4F | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x6] = 0x67 (g)
Reading from EEPROM:
4F 0 80 0 80 4 67 4 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x7] = 0x68 (h)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 45 0 80 4 3 0 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x8] = 0x69 (i)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 69 4 4F 0 80 0 80 4 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x9] = 0x6A (j)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 6A 4 4F 0 80 0 80 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xA] = 0x6B (k)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 80 4 6B 4 4F 0 80 0 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xB] = 0x6C (l)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 0 80 4 6C 4 4F 0 80 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xC] = 0x6D (m)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 80 0 80 4 6D 4 4F 0 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xD] = 0x6E (n)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 0 80 0 80 4 6E 4 4F | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xE] = 0x6F (o)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4F 0 80 0 80 4 6F 4 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0xF] = 0x70 (p)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 3 F6 0 5B 4 38 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x10] = 0x71 (q)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 71 4 4F 0 80 0 80 4 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
EEPROM[0x11] = 0x72 (r)
Reading from EEPROM:
4 4F 0 80 0 80 4 68 | 4 4F 0 80 0 80 4 70 | 4 72 4 4F 0 80 0 80 | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF | FF FF FF FF FF FF FF FF
```

title: EEPROM page rotates while writing to it

Answers: 2

body:
The global variable `data` is a byte variable. But in the read and write function you use it as an byte array (`data[i]` or 'data +i').
That's not OK, but also not an error in the case you use length 1 ;-).

In your read function you performed a so called random read action that must be terminated by a STOP signal on the I2C bus. This can be forced by:

    // ...

    for(int i=0; i < len; i++)
    {
        // store data in raw bcd format
        data[i] = Wire.read();
    }

    Wire.endTransmission(true);

    return 0;

    // ...

It's just a guess.

Writing single bytes must also be ended by a STOP condition but you used

    r |= Wire.endTransmission();

that does not send a STOP signal.

Again you can force it with:

    r |= Wire.endTransmission( true );

I'm not a Wire lib wizard, so I had read the Arduino documentation. Hopefully I understood it correctly.

body:
Your problem is

`byte l = len > 8 ? 8 : l;`

in the `eeprom_write()` function.

You wrote `byte NumberOfBytes = len > 8 ? 8 : NumberOfBytes;` and that will leads to an undefined behavior.

And for the future, if you want to write more than 1 Byte it is not important how many byte you write in a block but that the addresses are all located on the same eeprom page.

`((address / pagesize) == ((address + length) / pagesize)` must be true


body:
I found a link on how to connect MQ-2 Gas Sensor to Arduino Uno.

http://electronicsprojectshub.com/how-to-connect-mq2-gas-sensor-to-arduino/

After I bought all the parts and tried it out, the sensor gave me this in the serial monitor

> Ro: 10.81 kohm
>
>LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm
>
>LPG:0.00ppm    CO:0.00ppm    SMOKE:0.00ppm

and so on.

Here is the code I used

    #include <MQ2.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27, 16,2);
    int Analog_Input = A0;
    int lpg, co, smoke;
    MQ2 mq2(Analog_Input);

    void setup(){
      pinMode(A0, INPUT);
      Serial.begin(9600);
      lcd.begin();
      lcd.backlight();
      mq2.begin();
    }

    void loop(){
      float* values= mq2.read(true);
      //lpg = values[0];
      lpg = mq2.readLPG();
      //co = values[1];
      co = mq2.readCO();
      //smoke = values[2];
      smoke = mq2.readSmoke();

      lcd.setCursor(0,0);
      lcd.print("LPG:");
      lcd.print(lpg);
      lcd.print(" CO:");
      lcd.print(co);
      lcd.setCursor(0,1);
      lcd.print("SMOKE:");
      lcd.print(smoke);
      lcd.print(" PPM");
      delay(1000);
    }

Please help me fix it so that it can perform just the same as the video. Thanks.

title: Trying to read different gas levels with MQ2 Gas Sensor

Answers: 1

body:
First this should be like this:

    float* values= mq2.read(false); //false

and then write this to be printed in the serial monitor

    Serial.print('\n');
      Serial.print("LPG:");
      Serial.print(lpg);
      Serial.print(" CO:");
      Serial.print(co);

      Serial.print('\n');
      Serial.print("SMOKE:");
      Serial.print(smoke);
      Serial.print(" PPM");
      Serial.print('\n');


body:
I'm new in Arduino stuck in String to a dynamic byte array.

My String:

    String Finalval="6D616320747820636E662031352033300D0A";

Dynamic Byte array:

    byte ft[]={0x6D,0x61,0x63,0x20,0x74,0x78,0x20,0x63,0x6E,0x66,0x20,0x31,0x35,0x20,0x33,0x30,0x0D,0x0A};

title: String to Dynamic Byte array

Answers: 1

body:
Common C-string to byte array functions as shown in https://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c work perfectly fine.

```
Source hex string: 6D616320747820636E662031352033300D0A
Conversion OK buff 0x289 len 18
output byte array:
  00 6d 61 63 20 74 78 20 63 6e 66 20 31 35 20 33 30  mac tx cnf 15 30
  10 0d 0a                                            ..
```

```cpp
#include <Arduino.h>

void hexDump (const char *desc, const void *addr, const int len);

bool convert_hexstr_to_bytearray(const char* source, uint8_t* &output,
  size_t& output_len) {
 size_t len = strlen(source);
 //cannot convert non-even string length
 if ((len % 2) != 0) {
  return false;
 }
 //dynamically allocate output buffer
 output_len = len / 2;
 output = (uint8_t*) malloc(output_len);
 const char* curPos = source;
 for (size_t count = 0; count < len; count++) {
  sscanf(curPos, "%2hhx", output + count);
  curPos += 2;
 }
 return true;
}

String Finalval="6D616320747820636E662031352033300D0A";

void setup() {
 Serial.begin(115200);
 Serial.print("Source hex string: ");
 Serial.println(Finalval);
 Serial.flush();

 uint8_t* buffer = nullptr;
 size_t buffer_len = 0;
 if(convert_hexstr_to_bytearray(Finalval.c_str(), buffer, buffer_len)) {
  Serial.println("Conversion OK buff 0x" + String((long)buffer,HEX) + " len " + String(buffer_len));
  hexDump("output byte array", buffer, buffer_len);
 } else {
  Serial.println("Conversion failed\n");
 }

 //free memory
 if(buffer)
  free(buffer);
}

void loop() {
}

void PrintHex8(const uint8_t *data, uint8_t length) // prints 8-bit data in hex
{
     char tmp[length*2+1];
     byte first;
     byte second;
     for (int i=0; i<length; i++) {
           first = (data[i] >> 4) & 0x0f;
           second = data[i] & 0x0f;
           // base for converting single digit numbers to ASCII is 48
           // base for 10-16 to become lower-case characters a-f is 87
           // note: difference is 39
           tmp[i*2] = first+48;
           tmp[i*2+1] = second+48;
           if (first > 9) tmp[i*2] += 39;
           if (second > 9) tmp[i*2+1] += 39;
     }
     tmp[length*2] = 0;
     Serial.print(tmp);
}

void hexDump (const char *desc, const void *addr, const int len) {
    int i;
    unsigned char buff[17];
    const unsigned char *pc = (const unsigned char*)addr;

    // Output description if given.
    if (desc != NULL) {
        Serial.print (desc);
        Serial.println(":");
    }

    if (len == 0) {
        Serial.print("  ZERO LENGTH\n");
        return;
    }
    if (len < 0) {
        Serial.println("  NEGATIVE LENGTH: " + String(len));
        return;
    }

    // Process every byte in the data.
    for (i = 0; i < len; i++) {
        // Multiple of 16 means new line (with line offset).

        if ((i % 16) == 0) {
            // Just don't print ASCII for the zeroth line.
            if (i != 0) {
                Serial.print ("  ");
    Serial.println((char*)buff);
            }

            // Output the offset.
            Serial.print ("  ");
            PrintHex8((uint8_t*)&i, 1);
        }

        // Now the hex code for the specific character.
        Serial.print(" ");
        PrintHex8(pc + i,1);

        // And store a printable ASCII character for later.
        if ((pc[i] < 0x20) || (pc[i] > 0x7e))
            buff[i % 16] = '.';
        else
            buff[i % 16] = pc[i];
        buff[(i % 16) + 1] = '\0';
    }

    // Pad out last line if not exactly 16 characters.
    while ((i % 16) != 0) {
        Serial.print ("   ");
        i++;
    }

    // And print the final ASCII bit.
    Serial.print ("  ");
 Serial.println((char*)buff);
}

```


body:
I found a bunch of Arduinos (seemingly), but I can't identify the type.

I first thought of a **Micro**, but the chip is a MEGA328PAU and the Micro should have a MEGA32U4 instead:

[![Chip of the unknown Arduino][1]][1]

I know it's also not a **Nano**, because the Nano is a bit longer:

[![Comparison of unknown Arduino with Nano][2]][2]

Next, I looked up the [List of Board Specs](https://www.arduino.cc/en/Products/Compare). Based on the chip, the following models remain:

* Lilypad, can easily be excluded due to its shape
* Lilypad SimpleSnap, can easily be excluded due to its shape
* Uno, can easily be excluded due to its size
* Ethernet, can easily be excluded, because of the Ethernet port
* Mini
* Pro
* Pro Mini

So I am left with **Mini**, **Pro Mini** and **Pro**. The back of the board is not very helpful, since it IMHO misses the markers in the silk sceen:

[![Back of the board][3]][3]

It definitely looks like the [**Pro Mini** from Arduino Store](https://store.arduino.cc/arduino-pro-mini), but the Arduino store seems not to offer the Mini and Pro, so I don't have a comparison.

What type of Arduino is this? And, if possible, do you have a visual comparison of the three remaining types?

  [1]: https://i.stack.imgur.com/Bde7D.jpg
  [2]: https://i.stack.imgur.com/0gYyg.jpg
  [3]: https://i.stack.imgur.com/NogdP.jpg

title: What type of Arduino is this?

Answers: 1

body:
It is a version of Pro Mini.
[here in DIY MORE shop][1]

The Mini has regulator. Power it over RAW pin with 7 to 12 V and measure the Vcc pin if it shows 5v or 3.3 V.

To determine the frequency, look at the resonator (the component next to pin 2).

EDIT: the resonator markings are hard to read and very cryptic. to determine the frequency you could install Sparkfun boards package. There you can select the different variants of Pro Mini. Upload Blink. If the upload is successful and it Blinks in 1 second intervals, you have the right setting.

  [1]: https://www.diymore.cc/products/pro-mini-atmega328-3-3v-5v-16m-replace-atmega128-for-arduino-nano?_pos=6&_sid=8931d4b6d&_ss=r


body:
How can I save my output continuously to EEPROM? Or is this even possible? Please help me out.

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

    void loop() {
      static unsigned long count = 0;
      static float sum = 0;
      float ave = 0;
      int volt = analogRead(A1);
      float voltage = map(volt, 0, 1023, 0, 2500) / 100.0;
      Serial.print("Voltage: ");
      Serial.println(voltage, 2);
      sum = sum + voltage;
      count++;
      ave = sum / count;
      Serial.print("Average: ");
      Serial.println(ave, 2);
      Serial.println("-----");
      delay(3000);
    }

title: How can I save my float 'ave' on the EEPROM continuously?

Answers: 2

body:
It's possible, but it's certainly not advised.

EEPROM has a limited number of writes before it's dead. By writing continuously to the EEPROM you will kill it in no time at all.

body:
The answer is: Read the Arduino Reference and find [EEPROM.put][1]

But your actual problem is that

1) if you write to eeprom every 3 seconds, the Arduino eventually
    won't survive you

2) you eventually rather want to write the sum and the count, in
    your case ?

You should also think about how to initialize from EEPROM after Restart.

Perhaps it's sufficient to save restart values only once after 1 minute / 1 hour / daily if it still changes?

BTW the "Update only if it changed" is already built into the put() method.

  [1]: https://www.arduino.cc/en/Reference/EEPROMPut


body:
I want to connect my adafruit motor shield v2.3 to a touch board from bare conductive so that the motor turns when one of the electrodes is touched.

I've tested the touch part and that isn't a problem so i tested the motor shield on my arduino uno. I am using the DCMotorTest example and when uploading it doesn't give any errors. The shield is getting powered, but the motor isn't turning.

The motor does turn when connected to a 9v battery.
The motor doesn't turn when connected to motor shield without external power and VIN jumper connected.enter image description here
The motor doesn't turn when connected to motor shield with external power with and without VIN jumper connected.

```
/*
This is a test sketch for the Adafruit assembled Motor Shield for Arduino v2
It won't work with v1.x motor shields! Only for the v2's with built in PWM
control

For use with the Adafruit Motor Shield v2
----> http://www.adafruit.com/products/1438
*/

#include <Wire.h>
#include <Adafruit_MotorShield.h>

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Or, create it with a different I2C address (say for stacking)
// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(1);
// You can also make another motor on port M2
//Adafruit_DCMotor *myOtherMotor = AFMS.getMotor(2);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Adafruit Motorshield v2 - DC Motor test!");

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  myMotor->run(FORWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tock");

  myMotor->run(BACKWARD);
  for (i=0; i<255; i++) {
    myMotor->setSpeed(i);
    delay(10);
  }
  for (i=255; i!=0; i--) {
    myMotor->setSpeed(i);
    delay(10);
  }

  Serial.print("tech");
  myMotor->run(RELEASE);
  delay(1000);
}
```

https://i.stack.imgur.com/uzsEb.jpg

title: Adafruit motorshield v2.3 not working

Answers: 2

body:
You have two possibilities of powering the shield according to the adafruit documentation.

A: power the Arduino over the power plug (not the USB plug) of the Arduino and set the VIN jumper.

B: Leave the VIN jumper off and power over the power connector of the shield.

Don't try other possibilities. They may kill the shield or the Arduino.

The reason your motor doesn't turn is because you switched it off
`myMotor->run(RELEASE);`  immediately after you switched it on `myMotor->run(FORWARD);`.

body: I just used a different motor-shield and it works now, thank you all for your replies and research in this!


body:
I've assembled the TI RSLK Robot Maze Edition for a final project for my embedded systems class. Instead of using the MSP432P401R LaunchPad that came with the kit to control the power board, I've used an Arduino MEGA 2560 instead. I'm also using a KY-023 Analog Joystick to control the two dc motors.

    int xPin = A0; // analog input for x-axis joystick
    int yPin = A1; // analog input for y-axis joystick

    int yPosition = 0;
    int xPosition = 0;

    //Right motor pins
    #define MRSpeed 11
    #define MRDir 10
    #define MRSleep 9

    //Left motor pins
    #define MLSpeed 8
    #define MLDir 7
    #define MLSleep 6

    void setup() {
     Serial.begin(9600);
     pinMode(xPin, INPUT); // setup x input
     pinMode(yPin, INPUT); // setup y input

     pinMode(MRSpeed, OUTPUT);
     pinMode(MRDir, OUTPUT);
     pinMode(MRSleep, OUTPUT);
     digitalWrite(MRSleep, 1);

     pinMode(MLSpeed, OUTPUT);
     pinMode(MLDir, OUTPUT);
     pinMode(MLSleep, OUTPUT);
     digitalWrite(MLSleep, 1);

     }

     void loop() {

      yPosition = analogRead(yPin);
      xPosition = analogRead(xPin);

      //Steer Forward
      if (yPosition > 1020)
      {
        analogWrite(MRSpeed, 255); //To move right wheel forward
        analogWrite(MLSpeed, 255); //To move left wheel forward
      }

       //To stop both wheels
        else if (yPosition = 506 || 505)
        {
          analogWrite(MRSpeed, 0);
          analogWrite(MLSpeed,0);
        }

         //Turn Right
          if(xPosition < 512)
          {
           analogWrite(MRSpeed, 0);
           analogWrite(MLSpeed, 255);
          }

         //Turn Left
           if(xPosition > 1020)
           {
             analogWrite(MRSpeed, 255);
             analogWrite(MLSpeed, 0);
           }

           }

title: How do I write my code to reverse the motors in the opposite direction so the RSLK can move backwards?

Answers: 0


body:
It is possible to split the project into server files. However, it looks like they all must be in the same folder with the.ino file.

Is it possible to split project into several folders? I’ve got several git repositories which I want to use in the same project and I can’t use them as libraries. Each repository must have its own folder…

Answers: 1

body:
I will try to give an answer as it is not easy to understand what you mean.

Probably it is also better if you know how the Arduino IDE works, before try to make complex projects.

Short answer:
**Yes, it is possible**

Normally, you have an ino-file, some other files and many libraries. If you want create something for your project, you can just create a folder inside the library folder.

But this is not what you want right?

You can create many folders inside your project and include any header inside your folders just with
`#include "subfolder/yourfile.h"`

The files will not be opened with your Arduino IDE.

You can also create your "mini library", so the compiler will compile it with your project. This library need to be in a subfolder called `src`. At this point it will be converted and compiled for your project.

Simple working example:
**testsub.ino**
```cpp
#include "src/test.h"
Test *test = new Test();
void setup(){
  Serial.print(test->number());
}
void loop(){
}

```

Create a subfolder `src` and place your files:
**test.h**
```cpp
class Test
{
public:
  Test();
  int number();
};
```
and
**test.cpp**
```cpp
#include "test.h"
Test::Test() {
}
int Test::number() {
  return 95;
}
```

If you want another "library", you can create another subfolder called `src`.


body:
hi i am getting this error, im guessing i have a bracket missing or one in the wrong place.  any help is appreciate, still new at this. thank you

(code bellow)

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>
    #include <XBOXRECV.h>

    Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

    USB Usb;
    XBOXRECV Xbox(&Usb);

    // our servo # counter
    // You can change the value from 0 to 15 (servo 1 through 16)
    uint8_t util1servo = 0;
    uint8_t util2servo = 1;
    uint8_t ldoorservo = 2;
    uint8_t rdoorservo = 7;
    uint8_t sdoorservo = 3;
    uint8_t mdoorservo = 8;

    //Servo limits definition.
    //You will have to figure out which numbers match your servo be carefull with these,
    //it can break your servo if you go beyond the limits. The ones listed here are for my own setup
    #define UTIL1MIN  150 // Close position of the Top Utility arm
    #define UTIL1MAX  310 // Open position of the Top Utility arm
    #define UTIL2MIN  140 // Close position of the Bottom Utility arm
    #define UTIL2MAX  300 // Open position of the Bottom Utility arm
    #define LDOORMIN  390 // Close position of the Left door
    #define LDOORMAX  550 // Open position of the Left door
    #define RDOORMIN  555 // Close position of the Right door
    #define RDOORMAX  360 // Open position of the Right door
    #define SDOORMIN  492 // Close position of the Small door
    #define SDOORMAX  200 // Open position of the Small door
    #define MDOORMIN  550 // Close position of the Mid door
    #define MDOORMAX  380 // Open position of the Mid door

    //Status for each door open/close
    int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
    int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
    int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
    int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

    void setup() {

       pwm1.begin();

      pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

      Wire.begin();

    }

    void loop() {

    //Left door
    if (Xbox.getButtonClick(LEFT, 0)){
      if (Xbox.getButtonPress(R1, 0)) {
        if(LDOORSTATUS == 0){
              for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++){
              pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
              delay(1);
              }
              LDOORSTATUS = 1;
              }
            else if (LDOORSTATUS == 1){
                 for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--){
                 pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
                 delay(1);
                 }
                 LDOORSTATUS = 0;
         }

title: expected '}' at end of input

Answers: 1

body:
Auto-formatting produced the following - look at your `loop()` function and you'll see the problem:

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>
    #include <XBOXRECV.h>

    Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x40);

    USB Usb;
    XBOXRECV Xbox(&Usb);

    // our servo # counter
    // You can change the value from 0 to 15 (servo 1 through 16)
    uint8_t util1servo = 0;
    uint8_t util2servo = 1;
    uint8_t ldoorservo = 2;
    uint8_t rdoorservo = 7;
    uint8_t sdoorservo = 3;
    uint8_t mdoorservo = 8;

    //Servo limits definition.
    //You will have to figure out which numbers match your servo be carefull with these,
    //it can break your servo if you go beyond the limits. The ones listed here are for my own setup
    #define UTIL1MIN  150 // Close position of the Top Utility arm
    #define UTIL1MAX  310 // Open position of the Top Utility arm
    #define UTIL2MIN  140 // Close position of the Bottom Utility arm
    #define UTIL2MAX  300 // Open position of the Bottom Utility arm
    #define LDOORMIN  390 // Close position of the Left door
    #define LDOORMAX  550 // Open position of the Left door
    #define RDOORMIN  555 // Close position of the Right door
    #define RDOORMAX  360 // Open position of the Right door
    #define SDOORMIN  492 // Close position of the Small door
    #define SDOORMAX  200 // Open position of the Small door
    #define MDOORMIN  550 // Close position of the Mid door
    #define MDOORMAX  380 // Open position of the Mid door

    //Status for each door open/close
    int LDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
    int RDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
    int SDOORSTATUS = 0; // Status 0 = Closed, 1 = Open
    int MDOORSTATUS = 0; // Status 0 = Closed, 1 = Open

    void setup() {

      pwm1.begin();

      pwm1.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

      Wire.begin();

    }

    void loop() {

      //Left door
      if (Xbox.getButtonClick(LEFT, 0)) {
        if (Xbox.getButtonPress(R1, 0)) {
          if (LDOORSTATUS == 0) {
            for (uint16_t lpulselen = LDOORMIN; lpulselen < LDOORMAX; lpulselen++) {
              pwm1.setPWM(ldoorservo, 0, lpulselen); //Open the door
              delay(1);
            }
            LDOORSTATUS = 1;
          }
          else if (LDOORSTATUS == 1) {
            for (uint16_t lpulselen = LDOORMAX; lpulselen > LDOORMIN; lpulselen--) {
              pwm1.setPWM(ldoorservo, 0, lpulselen); //Close the door
              delay(1);
            }
            LDOORSTATUS = 0;
          }


body:
There are nine registers inside and the contents of the registers can be changed to perform several operations. The link of the data-sheet is given here(Page 26). The write cycle sampling must be performed on the rising edge.
The 16 bits of the serial write data are shifted in, MSB to lower
sideband.
The link: https://www.analog.com/media/en/technical-documentation/data-sheets/ADMV1013.pdf

title: how to wrire into the contents of the registers in ADMV1013 up converter using arduino Due?

Answers: 0


body:
I would like to create a custom Arduino board based on the Arduino Due. Upon looking at the Due's [schematics][1] under the documentation tab there are some stuff that i do not need and removed them. the last thing that i want removed is the ATMEGA16U2. This part just takes so many components that i want it removed.

I would like to build my code using the arduino IDE and with the 16u2 gone i do not know a way how to upload my codes.

This seems to be possible since under the documentations there is a native usb port of the due that is directly connected to the SAM3X8E,

from here on out im lost what how do i upload my code to the same sam3x8E

Special tools that i have that might be usefull:

 - J-link EDU Mini

 - USB to UART

My Current draft schematics:

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

  [1]: https://store.arduino.cc/usa/due
  [2]: https://i.stack.imgur.com/Wbrep.png

title: Circuit requirement for Arduino Due custom circuit without the ATMEGA16U2

Answers: 1

body:
Since you have USB you just connect it to your computer. As long as the flash is blank (use the erase button) it will enter the BOSSA bootloader at powerup and you can use the Arduino IDE to upload the code as normal (or the bossac command line tool).

There are two ways of entering the bootloader:

1. Wipe the flash with the ERASE button (or trigger from 16U2).
2. Open the native port at 1200 baud.

The latter is only possible if you have first programmed the board with a sketch with that ability in it. The most sure-fire way is to include the erase button.

You can either provide a physical button (as shown in the existing schematics) or a simple jumper that can be shorted when erasing is needed.


body:
I am new to Arduino Programming and I have bought an Arduino UNO , Ultrasonic Sensor (HC-SR04), A Piezo Buzzer, IR Receiver (VS1838B) and a RGB LED....

I wrote a program to Calculate Distance form the Ultrasonic Sensor to an object and a Processing Sketch to Display the results.

Now I want to use the IR Receiver to increase the Distance Threshold which makes the buzzer beep...I mean I want to press 1 in my remote to keep the distance about 5 cm after which the buzzer beeps, and when I press 2 the distance becomes 10 cm and so on...I want to stop everything when I press 0 in my remote...

I have already found out the hex codes of my remote buttons but the program makes the task harder...
Please help me with the program that I have already written :-

```
#include <NewTone.h>
#include <IRremote.h>

const int rec = 9;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  irrecv.enableIRIn();
  Serial.begin(9600);
}

void loop()
{
  if (irrecv.decode(&results))
  {
    if (results.value != BUTTON_0)
    {

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);
      distanceCm = duration * 0.034 / 2;
      distanceInch = duration * 0.0133 / 2;
      dur = duration / 10000;

      Serial.print(distanceCm);
      Serial.print("  cm ");
      Serial.print("                         ");
      Serial.print(distanceInch);
      Serial.print(" Inch ");
      Serial.print("                         ");
      Serial.print(dur);
      Serial.print(" Seconds");
      Serial.print("\n");
    }

    if (results.value == BUTTON_0)
    {

      noNewTone(buzPin);
      analogWrite(redPin, 0);
      analogWrite(greenPin, 0);
      analogWrite(bluePin, 0);
    }

    if (results.value == BUTTON_1)
    {

      if (distanceCm <= 5)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 10 && distanceCm > 5)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_2)
    {

      if (distanceCm <= 10)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 20 && distanceCm > 10)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_3)
    {

      if (distanceCm <= 30)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 50 && distanceCm > 30)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }

    if (results.value == BUTTON_4)
    {

      if (distanceCm <= 100)
      {
        NewTone(buzPin, 2000);
        analogWrite(redPin, 255);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }
      else if (distanceCm <= 200 && distanceCm > 100)
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 255);
      }
      else
      {
        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 255);
        analogWrite(bluePin, 0);
      }

    }
    irrecv.resume();
  }
}
```

I am using the "IRremote.h" and "NewTone.h" Libraries....

The main problem is that the "irrecv.resume();" pauses the program and waits for the IR input but I want the program to run continuously till I give an IR Input...

I request you to help me with the program.

---

I edited my program to this and this worked:-

```
#include <NewTone.h>
#include <IRremote.h>

const int rec = 2;
IRrecv irrecv(rec);
decode_results results;

#define BUTTON_0 0xFF6897
#define BUTTON_1 0xFF30CF
#define BUTTON_2 0xFF18E7
#define BUTTON_3 0xFF7A85
#define BUTTON_EQ 0xFF906F
#define BUTTON_4 0xFF10EF

const int redPin = 5;
const int greenPin = 6;
const int bluePin = 10;
const int trigPin = 12;
const int echoPin = 11;
const int buzPin = 3;
double duration;
double distanceCm, distanceInch;
double dur;

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(buzPin, OUTPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop()
{
  if (irrecv.decode(&results))
  {

    do
    {
      if (results.value == BUTTON_0)

      {

        noNewTone(buzPin);
        analogWrite(redPin, 0);
        analogWrite(greenPin, 0);
        analogWrite(bluePin, 0);
      }

      if (results.value == BUTTON_1)
      {
        sonic();

        if (distanceCm <= 5)
        {
          red();
        }
        else if (distanceCm <= 10 && distanceCm > 5)
        {
          blue();
        }
        else
        {
          green();
        }

      }

      if (results.value == BUTTON_2)
      {
        sonic();
        if (distanceCm <= 10)
        {
          red();
        }
        else if (distanceCm <= 20 && distanceCm > 10)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_3)
      {
        sonic();
        if (distanceCm <= 30)
        {
          red();
        }
        else if (distanceCm <= 50 && distanceCm > 30)
        {
          blue();
        }
        else
        {
          green();
        }
      }

      if (results.value == BUTTON_4)
      {
        sonic();
        if (distanceCm <= 100)
        {
          red();
        }
        else if (distanceCm <= 200 && distanceCm > 100)
        {
          blue();
        }
        else
        {
          green();
        }

      }
    }
    while (digitalRead(rec) == 1);

    irrecv.resume();
  }
}

void sonic()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distanceCm = duration * 0.034 / 2;
  distanceInch = duration * 0.0133 / 2;
  dur = duration / 10000;

  Serial.print(distanceCm);
  Serial.print("  cm ");
  Serial.print("                         ");
  Serial.print(distanceInch);
  Serial.print(" Inch ");
  Serial.print("                         ");
  Serial.print(dur);
  Serial.print(" Seconds");
  Serial.print("\n");
}

void green()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 255);
  analogWrite(bluePin, 0);
}

void blue()
{
  noNewTone(buzPin);
  analogWrite(redPin, 0);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 255);
}

void red()
{
  NewTone(buzPin, 2000);
  analogWrite(redPin, 255);
  analogWrite(greenPin, 0);
  analogWrite(bluePin, 0);
}

```

But now the problem is I need to press the IR Remote button two times because when I press once the program moves to the `irrecv.resume();` command and waits for another IR Input and I need to press the button again.

Can this be solved (with only one press)?

title: Stuck in a loop using IR Receiver

Answers: 2

body:
 1. You really should use switch-case.
 2. irrecv.resume() does not halt the code.

Your program is running fine. It seems like you want to make sensor readings continuously and act only when you press the button. Am I right?

body:
Your code becomes more readable, if you use functions with return values.

For example, something like this structure

    unsigned int limit; // 0 = off, else limit in cm  ...
    void loop() {
      if (irrecv.decode(&results)) {
          byte key = getIRKey(results.value); // 0 , 1, 2, etc.,  0xFF for unknown
          irrecv.resume();
          switch (key) {
             case 0: limit = 0; break;
             case 1: limit = 5; break;
             ...
             default: break; // wrong key does not change limit
          }
      }
      if (limit) {
         unsigned int dist = sonic(); // returns the measured distance or 0
         if (dist && dist < limit) NewTone(buzPin, 2000);
         else noNewTone(buzPin); // off: too far
      } else noNewTone(buzPin); // off: no check
    }

This code should not block. Have fun modifying sonic() and creating the other helper function.


body:
I am trying to implement a bot which can sense obstacle in front, left or right and post detection send interrupts. Which in turn will perform the appropriate motor function to avoid these obsticles. Any help would be highly appreciated.
It would be great if you could make changes in this code and post it so that I can actually run, simulate and find out where actually I have gone wrong.

My code

    #define trigPin 14
    #define echoPin 12
    #define echoPin1 13
    #define echoPin2 15

    //Initialize Digital Pins
    const int leftForward = 2;
    const int leftBackward = 16;
    const int rightForward = 5;
    const int rightBackward = 4;

    // Define variables:
    long duration;
    long duration1;
    long duration2;
    int distance;
    int distance1;
    int distance2;
    boolean goesForward = false;
    bool flag = false;
    bool flag1 = false;
    bool flag2 = false;

    void f5(void){
      flag = true;
    }

    void f2(void){
      flag1 = true;
    }

    void f3(void){
      flag2 = true;
    }

    void inter1(){
        Serial.print("Distance1 = ");
        Serial.print(distance2);
        Serial.println(" cm");
        moveStop();
        delay(3000);
        moveBackward();
        delay(4000);
        moveStop();
        delay(3000);
        turnRight();
        moveStop();
        delay(3000);
    }

    void inter2(){
        Serial.print("Distance2 = ");
        Serial.print(distance2);
        Serial.println(" cm");
        moveStop();
        delay(3000);
        moveBackward();
        delay(4000);
        moveStop();
        delay(3000);
        turnRight();
        moveStop();
        delay(3000);
    }

    void inter3(){
        Serial.print("Distance2 = ");
        Serial.print(distance2);
        Serial.println(" cm");
        moveStop();
        delay(3000);
        moveBackward();
        delay(4000);
        moveStop();
        delay(3000);
        turnRight();
        moveStop();
        delay(3000);
    }

    void setup() {
      // Define inputs and outputs:
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(echoPin1, INPUT);
      pinMode(echoPin2, INPUT);

      // set control pins as Output
      pinMode(leftForward,OUTPUT);
      pinMode(leftBackward,OUTPUT);
      pinMode(rightForward,OUTPUT);
      pinMode(rightBackward,OUTPUT);

      attachInterrupt(digitalPinToInterrupt(echoPin), f5, RISING);
      attachInterrupt(digitalPinToInterrupt(echoPin1), f2, RISING);
      attachInterrupt(digitalPinToInterrupt(echoPin2), f3, RISING);
      //Begin Serial communication at a baudrate of 9600:
      Serial.begin(9600);
    }

    void loop() {
      // Clear the trigPin by setting it LOW:
      digitalWrite(trigPin, LOW);
      delayMicroseconds(5);

      // Trigger the sensor by setting the trigPin high for 10 microseconds:
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      // Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
      duration = pulseIn(echoPin, HIGH);
      // Calculate the distance:
      distance= duration*0.034/2;

      duration1 = pulseIn(echoPin1, HIGH);
      // Calculate the distance:
      distance1= duration1*0.034/2;

      duration2 = pulseIn(echoPin2, HIGH);
      // Calculate the distance:
      distance2= duration2*0.034/2;

      // Print the distance on the Serial Monitor (Ctrl+Shift+M):

      if (distance <= 20){
          attachInterrupt(digitalPinToInterrupt(12), f5, RISING);
        }
      else{
        moveForward();
      }

      if (distance1 <= 20){
        attachInterrupt(digitalPinToInterrupt(13), f2, RISING);
      }
      else{
        moveForward();
      }

      if (distance2 <= 20){
        attachInterrupt(digitalPinToInterrupt(15), f3, RISING);
      }
      else{
        moveForward();
      }

      if(flag)
     {
      inter1();
      flag = false;
     }

      if(flag1)
     {
      inter2();
      flag1 = false;
     }

     if(flag2)
     {
      inter3();
      flag2 = false;
     }

     delay(1000);
     /* // run forward

      digitalWrite(leftForward,HIGH);
      digitalWrite(leftBackward,LOW);
      digitalWrite(rightForward,HIGH);
      digitalWrite(rightBackward,LOW);

      delay(1000);

      // run left
      digitalWrite(leftForward,LOW);
      digitalWrite(leftBackward,LOW);
      digitalWrite(rightForward,HIGH);
      digitalWrite(rightBackward,LOW);

      delay(1000);

      // run forward
      digitalWrite(leftForward,HIGH);
      digitalWrite(leftBackward,LOW);
      digitalWrite(rightForward,LOW);
      digitalWrite(rightBackward,LOW);

      delay(1000);

      // run backward
      digitalWrite(leftForward,LOW);
      digitalWrite(leftBackward,HIGH);
      digitalWrite(rightForward,LOW);
      digitalWrite(rightBackward,HIGH);

      delay(1000);
      delay(50);
      */
    }
    void moveStop(){

      digitalWrite(rightForward, LOW);
      digitalWrite(leftForward, LOW);
      digitalWrite(rightBackward, LOW);
      digitalWrite(leftBackward, LOW);
    }

    void moveForward(){

      if(!goesForward){

        goesForward=true;

        digitalWrite(leftForward, HIGH);
        digitalWrite(rightForward, HIGH);

        digitalWrite(leftBackward, LOW);
        digitalWrite(rightBackward, LOW);
      }
    }

    void moveBackward(){

      goesForward=false;

      digitalWrite(leftBackward, HIGH);
      digitalWrite(rightBackward, HIGH);

      digitalWrite(leftForward, LOW);
      digitalWrite(rightForward, LOW);

    }

    void turnRight(){

      digitalWrite(leftForward, HIGH);
      digitalWrite(rightBackward, HIGH);

      digitalWrite(leftBackward, LOW);
      digitalWrite(rightForward, LOW);

      delay(500);

      digitalWrite(leftForward, HIGH);
      digitalWrite(rightForward, HIGH);

      digitalWrite(leftBackward, LOW);
      digitalWrite(rightBackward, LOW);

    }

    void turnLeft(){

      digitalWrite(leftBackward, HIGH);
      digitalWrite(rightForward, HIGH);

      digitalWrite(leftForward, LOW);
      digitalWrite(rightBackward, LOW);

      delay(500);

      digitalWrite(leftForward, HIGH);
      digitalWrite(rightForward, HIGH);

      digitalWrite(leftBackward, LOW);
      digitalWrite(rightBackward, LOW);
    }

title: Getting weird output for following object detection code using interrupts on HUZZAH ESP8266 and motor controller L293D along with 3 HCSR04 sensors

Answers: 0


body:
I have some issues with my Digispark ATtiny85 board.
If I upload the blink sketch for example the LED starts blinking and everything looks fine. But as soon as I unplug the Digispark from the USB port and plug it back in nothing happens. I know that the programm starts with a delay of 5 seconds so programming via USB becomes possible, but still nothing. Its seems like the flash-memory (where the programm is stored) of the ATtiny 85 is empty.

Here is the example blink sketch:
```
// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(0, OUTPUT); //LED on Model B
  pinMode(1, OUTPUT); //LED on Model A
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(0, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(1, HIGH);
  delay(1000);               // wait for a second
  digitalWrite(0, LOW);    // turn the LED off by making the voltage LOW
  digitalWrite(1, LOW);
  delay(1000);               // wait for a second
}
```

I also tried uploading the sketch from a Laptop running on Windows but without success.

I am using Linux Mint and Arduino IDE 1.8.10.

Since I am new to Microcontrollers, I would be grateful for explainations, tipps or useful links.
Thank you!

title: Digispark ATtiny 85 erases flash after power loss

Answers: 1

body:
I got the same issue, on two boards. Will probably try to burn the bootloader using usbasp, maybe they burned the wrong one back in china.

EDIT:

As expected flashing the micronucleus bootloader using USBasp solved the problem on both of the boards. I've used burn-o-mat as the arduino was not seeing my programmer.

Just download the firmware from github (I've used this: https://github.com/f4goh/micronucleus/archive/master.zip )

and connect like so (here the guy is using arduino uno, doesn't matter): https://hamprojects.wordpress.com/2018/12/27/digispark-microcontrollers-implementation/


body:
I'm trying to get a Bluefruit Feather M0, which has a SAMD21G on it, to do high-frequency  PWM by accessing timer registers directly, rather than using the Arduino API to do PWM at ~1 kHz or ~500 Hz. Actual frequency isn't important at this stage, I just want a lot more than 1 kHz.

I found an [example][1] for an MKR1000, based on a similar processor. I've adapted it as shown below. Comparing the [Adafruit pinout][2] with the original code and with the [datasheet][3], it's apparent that the pin numberings are different and that pin 11, which is the only one of the two example pins that is accessible, is on TCC0 here and not TCC1.

The only change I see that I needed to make is to duplicate all the TCC1 setup in `setupTimers()` and the TCC1 duty cycle control in `loop()` for TCC0. Yet on the scope, I see no PWM output. I then tried setting pin 13 to PWM as well, so I'd see it on the on board LED. Still nothing. I'm somewhat stuck now.

Does anyone have any ideas?

    void setup() {
     // put your setup code here, to run once:
     setupTimers();
     Serial.begin(9600);
    }

    void loop() {
     // put your main code here, to run repeatedly:
     int t = 0;
     Serial.println("\nRunning PWM 0 to 100%");
     for (t = 0; t < 1000; t = t + 1) {
      REG_TCC1_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
      while (TCC1->SYNCBUSY.bit.CC1);                // Wait for synchronization
      REG_TCC0_CC1 = t;                              // TCC1 CC1 - on D3  - PWM signalling
      while (TCC0->SYNCBUSY.bit.CC1);                // Wait for synchronization
      delay(1);
      Serial.print(".");
     }

     delay(2000);
    }

    // Output PWM 24Khz on digital pin D3  and D11 using timer TCC1 (10-bit resolution)
    void setupTimers() {
     REG_GCLK_GENDIV = GCLK_GENDIV_DIV(1) |          // Divide the 48MHz clock source by divisor N=1: 48MHz/1=48MHz
      GCLK_GENDIV_ID(4);            // Select Generic Clock (GCLK) 4
     while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

     REG_GCLK_GENCTRL = GCLK_GENCTRL_IDC |           // Set the duty cycle to 50/50 HIGH/LOW
      GCLK_GENCTRL_GENEN |         // Enable GCLK4
      GCLK_GENCTRL_SRC_DFLL48M |   // Set the 48MHz clock source
      GCLK_GENCTRL_ID(4);          // Select GCLK4
     while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

     // Enable the port multiplexer for the digital pin D3 and D11  **** g_APinDescription() converts Arduino Pin to SAMD21 pin
     PORT->Group[g_APinDescription[3].ulPort].PINCFG[g_APinDescription[3].ulPin].bit.PMUXEN = 1;
     PORT->Group[g_APinDescription[11].ulPort].PINCFG[g_APinDescription[11].ulPin].bit.PMUXEN = 1;
     PORT->Group[g_APinDescription[13].ulPort].PINCFG[g_APinDescription[13].ulPin].bit.PMUXEN = 1;

     // Connect the TCC1 timer to digital output D3 and D11 - port pins are paired odd PMUO and even PMUXE
     // F & E specify the timers: TCC0, TCC1 and TCC2
     PORT->Group[g_APinDescription[2].ulPort].PMUX[g_APinDescription[2].ulPin >> 1].reg = PORT_PMUX_PMUXO_E;  // D3 is on PA11 = odd, use Device E on TCC1/WO[1]
     PORT->Group[g_APinDescription[11].ulPort].PMUX[g_APinDescription[11].ulPin >> 1].reg = PORT_PMUX_PMUXE_F; // D11 is on PA08 = even, use device F on TCC1/WO[0]
     PORT->Group[g_APinDescription[13].ulPort].PMUX[g_APinDescription[13].ulPin >> 1].reg = PORT_PMUX_PMUXE_E; // Try the LED.. doesn't work with E or F

     //Actually, pin 11 on the Feather is on PA16. Still even, not sure of the significance, but it's now TCC0/WO[6] and still port F.
     //All the stuff further down is about TCC1!

     // Feed GCLK4 to TCC0 and TCC1
     REG_GCLK_CLKCTRL = GCLK_CLKCTRL_CLKEN |         // Enable GCLK4 to TCC0 and TCC1
      GCLK_CLKCTRL_GEN_GCLK4 |     // Select GCLK4
      GCLK_CLKCTRL_ID_TCC0_TCC1;   // Feed GCLK4 to TCC0 and TCC1
     while (GCLK->STATUS.bit.SYNCBUSY);              // Wait for synchronization

     // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
     REG_TCC1_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
      TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
     while (TCC1->SYNCBUSY.bit.WAVE);               // Wait for synchronization

     // Each timer counts up to a maximum or TOP value set by the PER register,
     // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
     REG_TCC1_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
     while (TCC1->SYNCBUSY.bit.PER);                // Wait for synchronization

     // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
     REG_TCC1_CC1 = 500;                             // TCC1 CC1 - on D3  50%
     while (TCC1->SYNCBUSY.bit.CC1);                   // Wait for synchronization
     REG_TCC1_CC0 = 500;                             // TCC1 CC0 - on D11 50%
     while (TCC1->SYNCBUSY.bit.CC0);                   // Wait for synchronization

     // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
     REG_TCC1_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
      TCC_CTRLA_ENABLE;             // Enable the TCC0 output
     while (TCC1->SYNCBUSY.bit.ENABLE);              // Wait for synchronization

     //Do everything again for TCC0

     // Dual slope PWM operation: timers countinuously count up to PER register value then down 0
     REG_TCC0_WAVE |= TCC_WAVE_POL(0xF) |           // Reverse the output polarity on all TCC0 outputs
      TCC_WAVE_WAVEGEN_DSBOTH;     // Setup dual slope PWM on TCC0
     while (TCC0->SYNCBUSY.bit.WAVE);               // Wait for synchronization

     // Each timer counts up to a maximum or TOP value set by the PER register,
     // this determines the frequency of the PWM operation: Freq = 48Mhz/(2*N*PER)
     REG_TCC0_PER = 1000;                           // Set the FreqTcc of the PWM on TCC1 to 24Khz
     while (TCC0->SYNCBUSY.bit.PER);                // Wait for synchronization

     // Set the PWM signal to output , PWM ds = 2*N(TOP-CCx)/Freqtcc => PWM=0 => CCx=PER, PWM=50% => CCx = PER/2
     REG_TCC0_CC1 = 500;                             // TCC1 CC1 - on D3  50%
     while (TCC0->SYNCBUSY.bit.CC1);                   // Wait for synchronization
     REG_TCC0_CC0 = 500;                             // TCC1 CC0 - on D11 50%
     while (TCC0->SYNCBUSY.bit.CC0);                   // Wait for synchronization

     // Divide the GCLOCK signal by 1 giving  in this case 48MHz (20.83ns) TCC1 timer tick and enable the outputs
     REG_TCC0_CTRLA |= TCC_CTRLA_PRESCALER_DIV1 |    // Divide GCLK4 by 1
      TCC_CTRLA_ENABLE;             // Enable the TCC0 output
     while (TCC0->SYNCBUSY.bit.ENABLE);              // Wait for synchronization
    }

  [1]: https://www.hackster.io/voske65/high-speed-pwm-on-arduino-atsamd21-859b06
  [2]: https://cdn-learn.adafruit.com/assets/assets/000/046/245/original/adafruit_products_Feather_M0_Bluefruit_v2.2-1.png?1504885440
  [3]: http://ww1.microchip.com/downloads/en/DeviceDoc/SAMD21-Family-DataSheet-DS40001882D.pdf

title: High-frequency PWM on an Adafruit Feather M0

Answers: 1

body:
For your specific problem: the Feather's `D11` is the SAMD's `PA16` and on `TCC0/WO[6]` (use `REG_TCC0_CCB2` and `PORT_PMUX_PMUXE_F`), and also on `TCC2/WO[0]` (use `REG_TCC2_CCB0` and `PORT_PMUX_PMUXE_E`).

An easier way: I have made a high-frequency-PWM library for this (called [Arduino_SAMD21_turbo_PWM][1]), and I have implemented the pin table for the Adafruit Feather M0.

I haven't tested it though, mainly because I don't have an Adafruit Feather M0. Still, feel free to have a try.

The pin mapping table itself for the Adafruit Feather M0, which AFAIK has the same pin mappings as the Arduino Zero, is [here][2] on Github; maybe it can help as well.

  [1]: https://github.com/ocrdu/Arduino_SAMD21_turbo_PWM
  [2]: https://github.com/ocrdu/Arduino_SAMD21_turbo_PWM/blob/master/extras/pintables.txt


body:
I am working on a device which will have to periodically switch positions and keep the position for very long time, as accurate as possible, under tension.

Never worked with servo motors before, but I found MG996R interesting. It has a stall torque of approx 12kg*cm (@6V).

**My question is:**

To what maximum safe continuous load I could subject the motor if I need to keep it in position for 24h+ (it may switch position occasionally, but worst scenario would be like 24h-48h continuous locking in same position) ?

title: Servo MG996R - what is the maximum load for very long time?

Answers: 0


body:
On Arduino Uno Wifi rev2 I want to create an SSL socket to my own SSL socket server implementation.

The board can download a webpage with encryption (after I've installed the certificate into it of course).

For my own SSL socket server implementation I'm using OpenSSL.

The board can connect to my own SSL socket server without any issues.

I want to enable [SSL_VERIFY_PEER][1] in my socket server.

With this option I can verify if peer is valid and true.

However after enabling this option, the Arduino is not able to connect to my socket anymore.

My question: **is peer certificate sending can be achieved on Ublox NINA W10x**?

  [1]: https://www.openssl.org/docs/man1.0.2/man3/SSL_CTX_set_verify.html

title: Uno Wifi rev2 - SSL socket connection

Answers: 0


body:
I have issues with electrical noise on my board (>300mV switching noise on top of 3.3V rail, its quite a lot), which is generated by my I2C SSD1306 OLED display. After some research I [found][1] that the noise may be reduced by changing the pre-charge duration in the SSD1306 controller. I am using an Arduino IDE with Adafruit_SSD1306.h library to program my chip. As I understand the initialization bits should be passed via I2C to the controller.
I found the following command in the Adafrui_SSD1306.cpp:

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

And the relevant bit of datasheet:

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

The D9 register is defined as SSD1306_SETPRECHARGE in Adafruit_SSD1306.h:

[![enter image description here][4]][4]

I am using the following code:

    void setup(){
    ...
    display.ssd1306_command(SSD1306_SETPRECHARGE); //0xD9
    display.ssd1306_command(0x11);
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    }
    ...

I am trying to set to 0x11, so to give the pre-charge byte lowest value possible. I've also tried putting the same command into the loop. Nothing has any effect on the display brightness though, which from my understanding should decrease with decreasing the pre-charge value. The noise also stays exactly the same. It seems I fail to pass the values to the SSD1306 correctly. I also tried changing the value in the Adafruit_SSD1306.cpp file:

[![enter image description here][5]][5]

Still no change. The noise stays exactly the same as well as the brightness. It's clear to me I'm doing something wrong, or I misunderstand the effect of changing the pre-charge value completely. I couldn't find anything in adafruit documentation on this matter. What am I doing wrong?

UPDATE:

I used other commands, such as setcontrast, which did have an effect on the display, so I did pass the values to the controller. It seems that changing the pre-charge value do not have much of an effect. On the other hand I discovered that I2C bus might be introducing the unwanted noise. When bypassing the data of clock line to ground via a capacitor the noise decreases. It seems I was looking for an issue in the wrong place.

  [1]: https://www.eevblog.com/forum/projects/oled-audible-noise/msg2752588/#msg2752588
  [2]: https://i.stack.imgur.com/UWcEY.png
  [3]: https://i.stack.imgur.com/pQ7Pg.png
  [4]: https://i.stack.imgur.com/Xzi23.png
  [5]: https://i.stack.imgur.com/rGwEo.png

title: Reducing the noise of an SSD1306 display by reducing pre-charge in Adafruit SSD1306 library

Answers: 0


body:
I have an Arduino and a [microswitch][1] that I want to use to know when the switch is initially being pressed (get "OnsetTime" on Serial) and when the switch is not being pressed anymore (get "OffsetTime" on Serial).

Imagine a bird sitting on the switch. I want to get an output "OnsetTime" when the bird first sits on the switch and an output "OffsetTime" when the bird flies away from the switch.

Right now, I have an output that constantly prints out "OnsetTime" when the switch is pressed.
I would appreciate it if anybody can help me figure out how can I implement the below code to get the outputs only when the switch is initially pressed and not being pressed anymore.

    void setup() {
      pinMode(7, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      if (digitalRead(7) == HIGH) {
        Serial.println("OnsetTime");
        }
    }
        //Serial.println("GetOffsetTime");

  [1]: https://uk.rs-online.com/web/p/microswitches/1594590/

title: Only print when the button is pressed and not being pressed anymore

Answers: 2

body:
If you want to be simple, you can use [this library][1]. The code will be

    #include <ezButton.h>

    ezButton button(7);  // create Button object that attach to pin 7;

    void setup() {
      Serial.begin(9600);
      button.setDebounceTime(100); // set debounce time to 100 milliseconds
    }

    void loop() {
      button.loop(); // MUST call the loop() function first

      if(button.isPressed())
        Serial.println("OnsetTime");

      if(button.isReleased())
        Serial.println("GetOffsetTime");
    }
If you want to understand in depth, You can see the code and instruction in [this tutorial][2]

  [1]: https://www.arduinolibraries.info/libraries/ez-button
  [2]: https://arduinogetstarted.com/tutorials/arduino-button#content_modifying_arduino_code

body:
You can save the value of the switch read to compare it on the next loop. This way you're able to detect changes.

    int lastValue;

    void setup() {
      pinMode(7, INPUT);
      lastValue= digitalRead(7);

      Serial.begin(9600);
    }

    void loop() {
      int currentValue = digitalRead(7);
      if (lastValue != currentValue) {
        lastValue = currentValue;

        if (currentValue == HIGH) {
          Serial.println("OnsetTime");
        } else {
          Serial.println("OffsetTime");
        }
      }
    }

Please be aware that switches bounce. If you see multiple messages at each mechanical change, insert a `delay(...)`.


body:
I am doing project on Single-lead ECG & Heart rate Variability using MAX30003 using Arduino.  I have added the code for this project also. Can anyone please tell me how to include Timer.h library. I am getting following error:

> F:\TRACKER WAVE\MAX INT\max
> ard\Protocentral-protocentral_max30003-v0.1-12-ge141d22
> (1)\Protocentral-protocentral_max30003-e141d22\software\protocentral_max30003_arduino\protocentral_max30003\protocentral_max30003.ino:34:22:
> fatal error: TimerOne.h: No such file or directory
>
>  #include <TimerOne.h>
>
> compilation terminated.
>
> exit status 1 Error compiling for board Arduino/Genuino Uno.

The code is here:

    #include<SPI.h>
    #include <TimerOne.h>
    #include "MAX30003.h"

    #define MAX30003_CS_PIN   7
    #define CLK_PIN          6

    volatile char SPI_RX_Buff[5] ;
    volatile char *SPI_RX_Buff_Ptr;
    int i=0;
    unsigned long uintECGraw = 0;
    signed long intECGraw=0;
    uint8_t DataPacketHeader[20];
    uint8_t data_len = 8;
    signed long ecgdata;
    unsigned long data;

    char SPI_temp_32b[4];
    char SPI_temp_Burst[100];

    // 32KHz clock using timer1
    void timerIsr()
    {
        digitalWrite( CLK_PIN, digitalRead(CLK_PIN ) ^ 1 ); // toggle Digital6 attached to FCLK  of MAX30003
    }

    void setup()
    {
        Serial.begin(115200); //Serial begin

        pinMode(MAX30003_CS_PIN,OUTPUT);
        digitalWrite(MAX30003_CS_PIN,HIGH); //disable device

        SPI.begin();
        SPI.setBitOrder(MSBFIRST);
        SPI.setDataMode(SPI_MODE0);

      //please enable the below lines if you are using older version of Protocentral_max30003 board without 32k f-clock generator
        /*SPI.setClockDivider(SPI_CLOCK_DIV4);
        pinMode(CLK_PIN,OUTPUT);

         //Start CLK timer
        Timer1.initialize(16);              // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
        Timer1.attachInterrupt( timerIsr ); // attach the service routine here
    */
        MAX30003_begin();   // initialize MAX30003
    }

    void loop()
    {
        MAX30003_Reg_Read(ECG_FIFO);

        unsigned long data0 = (unsigned long) (SPI_temp_32b[0]);
        data0 = data0 <<24;
        unsigned long data1 = (unsigned long) (SPI_temp_32b[1]);
        data1 = data1 <<16;
        unsigned long data2 = (unsigned long) (SPI_temp_32b[2]);
        data2 = data2 >>6;
        data2 = data2 & 0x03;

        data = (unsigned long) (data0 | data1 | data2);
        ecgdata = (signed long) (data);

        MAX30003_Reg_Read(RTOR);
        unsigned long RTOR_msb = (unsigned long) (SPI_temp_32b[0]);
       // RTOR_msb = RTOR_msb <<8;
        unsigned char RTOR_lsb = (unsigned char) (SPI_temp_32b[1]);

        unsigned long rtor = (RTOR_msb<<8 | RTOR_lsb);
        rtor = ((rtor >>2) & 0x3fff) ;

        float hr =  60 /((float)rtor*0.008);
        unsigned int HR = (unsigned int)hr;  // type cast to int

        unsigned int RR = (unsigned int)rtor*8 ;  //8ms

         /*Serial.print(RTOR_msb);
         Serial.print(",");
         Serial.print(RTOR_lsb);
         Serial.print(",");
         Serial.print(rtor);
         Serial.print(",");
         Serial.print(rr);
         Serial.print(",");
         Serial.println(hr);      */

          DataPacketHeader[0] = 0x0A;
          DataPacketHeader[1] = 0xFA;
          DataPacketHeader[2] = 0x0C;
          DataPacketHeader[3] = 0;
          DataPacketHeader[4] = 0x02;

          DataPacketHeader[5] = ecgdata;
          DataPacketHeader[6] = ecgdata>>8;
          DataPacketHeader[7] = ecgdata>>16;
          DataPacketHeader[8] = ecgdata>>24;

          DataPacketHeader[9] =  RR ;
          DataPacketHeader[10] = RR >>8;
          DataPacketHeader[11] = 0x00;
          DataPacketHeader[12] = 0x00;

          DataPacketHeader[13] = HR ;
          DataPacketHeader[14] = HR >>8;
          DataPacketHeader[15] = 0x00;
          DataPacketHeader[16] = 0x00;

          DataPacketHeader[17] = 0x00;
          DataPacketHeader[18] = 0x0b;

          for(i=0; i<19; i++) // transmit the data
          {
            Serial.write(DataPacketHeader[i]);

           }

        delay(8);
    }

    void MAX30003_Reg_Write (unsigned char WRITE_ADDRESS, unsigned long data)
    {

        // now combine the register address and the command into one byte:
         byte dataToSend = (WRITE_ADDRESS<<1) | WREG;

         // take the chip select low to select the device:
         digitalWrite(MAX30003_CS_PIN, LOW);

         delay(2);
         SPI.transfer(dataToSend);   //Send register location
         SPI.transfer(data>>16);     //number of register to wr
         SPI.transfer(data>>8);      //number of register to wr
         SPI.transfer(data);      //Send value to record into register
         delay(2);

         // take the chip select high to de-select:
         digitalWrite(MAX30003_CS_PIN, HIGH);
    }

    void max30003_sw_reset(void)
    {
        MAX30003_Reg_Write(SW_RST,0x000000);
        delay(100);
    }

    void max30003_synch(void)
    {
        MAX30003_Reg_Write(SYNCH,0x000000);
    }

    void MAX30003_Reg_Read(uint8_t Reg_address)
    {
        uint8_t SPI_TX_Buff;

        digitalWrite(MAX30003_CS_PIN, LOW);

        SPI_TX_Buff = (Reg_address<<1 ) | RREG;
        SPI.transfer(SPI_TX_Buff); //Send register location

        for ( i = 0; i < 3; i++)
        {
           SPI_temp_32b[i] = SPI.transfer(0xff);
        }

        digitalWrite(MAX30003_CS_PIN, HIGH);
    }

    void MAX30003_Read_Data(int num_samples)
    {
        uint8_t SPI_TX_Buff;

        digitalWrite(MAX30003_CS_PIN, LOW);

        SPI_TX_Buff = (ECG_FIFO_BURST<<1 ) | RREG;
        SPI.transfer(SPI_TX_Buff); //Send register location

        for ( i = 0; i < num_samples*3; ++i)
        {
          SPI_temp_Burst[i] = SPI.transfer(0x00);
        }

        digitalWrite(MAX30003_CS_PIN, HIGH);
    }

    void MAX30003_begin()
    {
        max30003_sw_reset();
        delay(100);
        MAX30003_Reg_Write(CNFG_GEN, 0x081007);
        delay(100);
        MAX30003_Reg_Write(CNFG_CAL, 0x720000);  // 0x700000
        delay(100);
        MAX30003_Reg_Write(CNFG_EMUX,0x0B0000);
        delay(100);
        MAX30003_Reg_Write(CNFG_ECG, 0x805000);  // d23 - d22 : 10 for 250sps , 00:500 sps
        delay(100);

        MAX30003_Reg_Write(CNFG_RTOR1,0x3fc600);
        max30003_synch();
        delay(100);
    }

title: MAX30003 using Arduino

Answers: 0


body:
I'm trying to make my own firmware uploader for the Arduino DUE by using an ESP32.

While reading through the datasheet I saw that once there's data transmitted over the UART port, the sam3x8e will go into the SAM-BA monitor mode. The flowchart that the datasheet provides is as follow:
[![enter image description here][1]][1]

How does this make sense, since you can obviously communciate with the DUE over UART?
Do you have to avoid certain hex combinations, or does it get out of this loop automatically?

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

title: Understanding SAM3x8e boot program. Misunderstanding the datasheet

Answers: 0


body:
[Arduino Uno Wifi rev2][1] includes an ECC608 crypto accelerator chip.

Even their documentation states "As for the WiFi connection, that's made secure with the new ECC608 crypto chip accelerator."

My question is: **how exactly the ECC608 is used?** I'd like to see the sources the Arduino makes the "WiFi secure" with it.

  [1]: https://store.arduino.cc/arduino-uno-wifi-rev2

title: What is ECC608 crypto chip accelerator used for in Arduino Uno Wifi rev2?

Answers: 1

body:
The library for the chip is [ArduinoECCX08][1]. It is used by the [ArduinoBearSSL][2] library. The ArduinoBearSSL is used by the [ArduinoIoTCloud
][3] library and [Arduino_OAuth][4] library.
.

  [1]: https://github.com/arduino-libraries/ArduinoECCX08
  [2]: https://github.com/arduino-libraries/ArduinoBearSSL
  [3]: https://github.com/arduino-libraries/ArduinoIoTCloud
  [4]: https://github.com/arduino-libraries/Arduino_OAuth


body:
I've recently bought an Arduo Due to create some sort of a Midi controller together with the MIDIUSB library.

I have create a simple a test program with 1 potentiometer (without the use of a class) to test the MIDIUSB library and everything works fine, so I decided to expanded my program to make it work with more than 1 potentiometer (with the use of a class).

However my pc stopped recognizing my Arduino as a MIDI device with my updated code. When I upload my previous example code it all works fine. I get no compile errors or whatsoever.
I don't understand what I'm doing wrong.
If anybody could explain me what I'm doing wrong or could give me a solution you would be a hero since I can't really work further if this issue doesn't get resolved.
Thanks!

Here is my code for Custom_MIDI_controller_V2.ino:

    #include "MIDIUSB.h"
    #include "Class.h"
    #define TOLERANCE 8

    byte NUMBER_POTS = 5;

    Pot PO0(A0, 1, 14);
    Pot PO1(A1, 1, 15);
    Pot PO2(A2, 1, 16);
    Pot PO3(A3, 1, 17);
    Pot PO4(A4, 1, 18);

    Pot *POTS[] = {&PO0, &PO1, &PO2, &PO3, &PO4};

    void setup() {

    }

    void loop() {
      for (int i = 0; i < NUMBER_POTS; i++) {
        int potValue = POTS[i]->getValue();
          if(potValue != 255) {
            controlChange(POTS[i]->_channel, POTS[i]->_control, potValue);
            MidiUSB.flush();
          }
       }
    }

    void controlChange(byte channel, byte control, byte value) {
      midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
      MidiUSB.sendMIDI(event);
    }

Here is my Class.cpp code:

    #include "Arduino.h"
    #include "Class.h"

    #define TOLERANCE 8

    Pot::Pot(int pin, int channel, int control) {
      _pin = pin;
      _channel = channel;
      _control = control;
      _value = analogRead(_pin);
      _oldValue = _value - 10;
    }

    int Pot::getValue() {
      int diff = abs(_value - _oldValue);
      if(diff > TOLERANCE)
      {
        _oldValue = _value;
        return map(_value, 0, 1023, 127, 0);
      } else {
        return 255;
      }
    }

And this is my header Class.h code:

    #ifndef Class_h
    #define Class_h
    #include "Arduino.h"

    class Pot
    {
      public:
        Pot(int pin, int channel, int control);
        int getValue();
        int _pin;
        int _channel;
        int _control;
        int _value;
        int _oldValue;
    };

    #endif

title: PC not recognizing Arduino when working with a class and MIDIUSB library

Answers: 1

body:
You need to take care with constructors in C++.  They get called during the global variable initialisation phase of the execution, which happens before `main()` gets called.

`main()` calls the routines that initialise and configure the peripherals and such in the chip, and by having `analogRead()` in your constructor (which is itself another error I will mention below) there is a good chance (I don't know the full initialisation sequence of that chip though) that it will never complete, and thus your program hangs at that point.

Your `analogRead()` doesn't want to be in the constructor, anyway, since that will only execute once when the object is constructed.  Instead you want to have `analogRead()` called at the point you need to get the analog value. In your code that would be at the start of `int Pot::getValue()`.