I2C connection freezes Master if Slave disconnects I am using I2C to successfully request critical data from a Slave device (I have to use requestFrom() in the Master) but if, for some reason, the power disconnects from the Slave device then the Master freezes altogether. I didn't realise I2C was so problematic in this regard and I have been a number of weeks trying all types of alternative setups to try and avoid this situation. I can't seem to find a way for example, to simply check if a Wire() connection exists before requesting data and freezing everything. Both devices are Arduino Uno r3.
Any ideas I may not have tried yet? Any way to send a single value to the Master and update it every 30 secs would do. Actually the data comes from a capacitive sensor, so would it be possible to just have both arduinos read from the same sensor?

In response to Nick Gammons suggestions (below):
I have edited the examples you gave to try and fit in with what I am trying to achieve. I would like to do the following. Catch a situation where the Master (Arduino Yun Shield) cannot communicate with the Slave ( Arduino r3 - with sensor) due to its power supply and/or sensor reading failing. In other words, an Arduino monitoring another Arduino. Here is my edited versions, however I am still not able to catch the "else" condition of the Slave being unreachable:

SLAVE

#include <Wire.h>

const byte MY_ADDRESS = 42;

// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2
    };

char command;

void setup()
  {
  command = 0;
  pinMode (A0, INPUT);

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming  messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

void loop()
  {
  // all done by interrupts
  }  // end of loop

void receiveEvent (int howMany)
  {
  command = Wire.read ();  // remember command for when we get request
  } // end of receiveEvent

void sendSensor (const byte which)
  {
  //int val = analogRead (which);
  int val = 125;//test only
  byte buf [2];
    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
  }

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:      Wire.write (0x55); break;   // send our ID
     case CMD_READ_A0: sendSensor (A0); break;  // send A0 value
     }
  }

MASTER

#include <Process.h>
#include <I2C.h>
#include <Bridge.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C  lcd(0x27, 16, 2);

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
  CMD_ID = 1,
  CMD_READ_A0  = 2,
};

void setup ()
{
  Bridge.begin();
  Console.begin();
  //while (!Console);
  I2c.begin ();
  I2c.timeOut(100);  // milliseconds

  lcd.init();
  lcd.backlight();
}

void loop()
{
  int value = getA0();
  Console.print("A0 value:");
  Console.println(value);
  lcd.setCursor(0, 0);
  lcd.print("A0 value:");
  lcd.print(value);//displays first '0' reading then freezes code
  delay (5000);
}

int getA0() {
  if (I2c.write (SLAVE_ADDRESS, CMD_READ_A0) == 0) {
    byte buf [2];
    int val;
    if (I2c.read (SLAVE_ADDRESS, sizeof buf, buf) == 0)
   {
      val = buf [0] << 8 | buf [1];
      return val;
    }
    else {
      return 0;
    }
  }
  else {
    return 0;
  }
  delay(500);
}

There is code inside the standard library that loops waiting for certain interrupts to complete transmission. If the transmission fails in the middle it can hang.
See my page about I2C. On that page I mention that there is an alternative library. That is written a bit differently so it times out if the transmission doesn't complete in time. An alternative download to the library is here - I2C_Rev5.zip - 6.6 KB.

As hinted by KIIV in a comment, maybe you don't have pull-up resistors. Make sure that you have pull-up resistors from both SDA and SCL to the +5V line. A reasonable value would be 4.7k (each).

Example code

would like a few more examples to show a similar setup to replace my current requestFrom

Borrowed from my page about I2C I am using the same slave code as on that page.
Slave
#include <Wire.h>

const byte MY_ADDRESS = 42;

// various commands we might get

enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

char command;

void setup()
  {
  command = 0;

  pinMode (8, INPUT_PULLUP);
  pinMode (A0, INPUT);

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveEvent);  // interrupt handler for incoming messages
  Wire.onRequest (requestEvent);  // interrupt handler for when data is wanted

  }  // end of setup

void loop()
  {
  // all done by interrupts
  }  // end of loop

void receiveEvent (int howMany)
  {
  command = Wire.read ();  // remember command for when we get request
  } // end of receiveEvent

void sendSensor (const byte which)
  {
  int val = analogRead (which);
  byte buf [2];

    buf [0] = val >> 8;
    buf [1] = val & 0xFF;
    Wire.write (buf, 2);
  }  // end of sendSensor

void requestEvent ()
  {
  switch (command)
     {
     case CMD_ID:      Wire.write (0x55); break;   // send our ID
     case CMD_READ_A0: sendSensor (A0); break;  // send A0 value
     case CMD_READ_D8: Wire.write (digitalRead (8)); break;   // send D8 value

     }  // end of switch

  }  // end of requestEvent

The above code responds to requests to send one of:

Its ID (0x55)
An analog reading (A0)
A digital reading (D8)

Master using Wire library
The master from my page was this:
#include <Wire.h>

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

void sendCommand (const byte cmd, const int responseSize)
  {
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (cmd);
  Wire.endTransmission ();

  Wire.requestFrom (SLAVE_ADDRESS, responseSize);
  }  // end of sendCommand

void setup ()
  {
  Wire.begin ();
  Serial.begin (115200);  // start serial for output

  sendCommand (CMD_ID, 1);

  if (Wire.available ())
    {
    Serial.print ("Slave is ID: ");
    Serial.println (Wire.read (), DEC);
    }
  else
    Serial.println ("No response to ID request");

  }  // end of setup

void loop()
  {
  int val;

  sendCommand (CMD_READ_A0, 2);
  val = Wire.read ();
  val <<= 8;
  val |= Wire.read ();
  Serial.print ("Value of A0: ");
  Serial.println (val, DEC);

  sendCommand (CMD_READ_D8, 1);
  val = Wire.read ();
  Serial.print ("Value of D8: ");
  Serial.println (val, DEC);

  delay (500);
  }  // end of loop

Master using I2C library
The beginTransmission() ... write() ... endTransmission() have been replaced by simply write() and the requestFrom() by read() like this:
#include <I2C.h>

const int SLAVE_ADDRESS = 42;

// various commands we might send
enum {
    CMD_ID = 1,
    CMD_READ_A0  = 2,
    CMD_READ_D8 = 3
    };

void setup ()
  {
  I2c.begin ();
  I2c.timeOut(100);  // milliseconds
  Serial.begin (115200);  // start serial for output

  I2c.write (SLAVE_ADDRESS, CMD_ID);
  byte id;

  if (I2c.read (SLAVE_ADDRESS, sizeof id, &id) == 0)
    {
    Serial.print ("Slave is ID: ");
    Serial.println (id, DEC);
    }
  else
    Serial.println ("No response to ID request");

  }  // end of setup

void loop()
  {

  I2c.write (SLAVE_ADDRESS, CMD_READ_A0);

  byte buf [2];
  int val;
  if (I2c.read (SLAVE_ADDRESS, sizeof buf, buf) == 0)
    {
    val = buf [0] << 8 | buf [1];
    Serial.print ("Value of A0: ");
    Serial.println (val, DEC);
    }
  else
    Serial.println ("No response to CMD_READ_A0 request");

  I2c.write (SLAVE_ADDRESS, CMD_READ_D8);
  uint8_t digitalVal;
  if (I2c.read (SLAVE_ADDRESS, sizeof digitalVal, &digitalVal) == 0)
    {
    Serial.print ("Value of D8: ");
    Serial.println (digitalVal, DEC);
    }
  else
    Serial.println ("No response to CMD_READ_D8 request");

  delay (500);
  }  // end of loop


Sending SMS once with arduino GPRS SIM900 if an input is HIGH I faced a problem to send 1 SMS if an input is HIGH and if it is LOW no SMS will be sent. The code not working, just sends SMS when I turn the GPRS on and after that nothing happens.

Please check this link to see the code : the code

Thank you for helping in advance.

You need to attach an interrupt to the pin which is getting HIGH and then the function connected to the interrupt will have the code to send the SMS.

Just init the GPRS with connecting to the network then just wait for the interrupt to send anything.


Issues with connecting to an Adafruit FLORA board I just bought a new Adafruit Flora board, and I haven't been able to get it working successfully. When I plug it into a USB port, the board seems to be getting power (the green PWR LED is illuminated), but there is no other output from the board. The Arduino IDE also does not recognize the board (the "port" menu under "Tools" is grayed out), and I have tried to connect to it on both Windows and Linux (Ubuntu) systems with the appropriate drivers/packages installed (including the Windows drivers and the board manager add-on in both installations of the Arduino IDE). I've also verified that the USB cable I'm using can handle data.

Previously, I was able to at least get the board to be recognized in the IDE on my Linux machine, and the red LED did light up, but after disconnecting it doesn't light up anymore (unless I try to reset the board, which makes the red LED pulse a few times).

Anything that I can try to get it recognized in the IDE?

Edit: I'm able to see the board pop up under "ports" in the IDE immediately after I hit the reset button on the board. However, as soon as the red LED stops pulsing (I think this means that the board is finished rebooting), it disappears from the list of available ports. It's also mounting under /dev/ttyACM0, not the usual /dev/ttyUSB0.

Seems like whatever code was running on the Flora was corrupted. As soon as I hit the reset button, the board would momentarily pop up in the Arduino IDE, and after doing this a few times, I managed to upload the "Blink" sketch while the board was visible to my system. After that the board started working normally. It reports its name as "Adafruit FLORA" under "get board info", and the serial monitor/onboard LED work just fine.


Why is my class losing a field in the middle of a method I have a class with a byte (stripLength) that seems to just disappear in the middle of the frameStep() method. I'm not especially skilled with C++ (or non-VM languages in general), but I believe it's only written or modified at the initialization of the class. What am I doing wrong?

BugFinding.ino

#define PIN 11
#define NUM_LEDS 100
#define WAIT 5
#define TAIL_LENGTH 40

#include "Libraries/Adafruit_NeoPixel.h"
#include "LightingStrip.h"

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_RGB + NEO_KHZ800);
LightingStrip lightStrip = LightingStrip(strip, NUM_LEDS, 20);

void setup() {
    Serial.begin(9600);
    strip.begin();
    strip.show();
    Serial.println("BugFinding");
    lightStrip.setColors();
}

void loop() {
    Serial.println("loop");
    lightStrip.frameStep();
    lightStrip.write();
    delay(WAIT);
}

LightingStrip.h

#ifndef LIGHTINGSTRIP_H_
#define LIGHTINGSTRIP_H_

#include "Libraries/Adafruit_NeoPixel.h"

class LightingStrip {
    public:
        LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t stripLength, uint8_t lengthOfTail);
        void frameStep();
        void write();
        void setColors();
    protected:
        Adafruit_NeoPixel strip;
        uint8_t mode;
        uint8_t frame;
        uint8_t colorFrame;
        uint8_t stripLength;
        uint8_t tailLength;
        uint32_t buf[];
        uint32_t colors[7];
        uint8_t currentColor[3];

        void cycleStep();
};

#endif /* LIGHTINGSTRIP_H_ */

LightingStrip.cpp

#include "LightingStrip.h"
#include "Libraries/Adafruit_NeoPixel.h"

LightingStrip::LightingStrip(Adafruit_NeoPixel ledStrip, uint8_t length, uint8_t lengthOfTail) {
    strip = ledStrip;
    stripLength = length;
    tailLength = lengthOfTail;

    buf[stripLength] = {0};
    colorFrame = 0;

    cycleStep();
}

void LightingStrip::setColors(){
    //colors = uint8_t[8][3];
    colors[0] = strip.Color(255, 120,   0); // Orange
    Serial.println("Color 0: " + String(colors[0]));
    Serial.println("Color 0: " + String(strip.Color(255, 120,   0)));
    Serial.println("stripLength: " + String(this->stripLength));
    colors[1] = strip.Color(  0, 255,   0); // Green
    Serial.println("setColors");
    Serial.println("stripLength: " + String(stripLength));
}

void LightingStrip::cycleStep(){
    frame = 0;
    colorFrame++;
}

void LightingStrip::frameStep(){
    Serial.println("frameStep");
    Serial.println("Color 0: " + String(colors[0]));
    int16_t j;
    Serial.println("frame: " + String(frame));
    Serial.println("colorFrame: " + String(colorFrame));
    Serial.println("stripLength 1: " + String(stripLength));
    if(frame > stripLength + tailLength)
        cycleStep();
    Serial.println("stripLength 1.2: " + String(stripLength));

    for(j=0; j<stripLength; j++){
        buf[j] = strip.Color(255,255,255);
    }
    Serial.println("stripLength 2: " + String(stripLength));
    for(j=frame; j>0 && frame-j<=stripLength; j--){
        if(j>stripLength) continue;
        buf[j] = colors[colorFrame];
        Serial.print("j: " + String(j));
        Serial.print(" color: " + String(colors[colorFrame]));
        Serial.println();
    }
    Serial.println("stripLength 3: " + String(stripLength));
    Serial.println("stripLength 4: " + String(stripLength + tailLength));
    Serial.println("stripLength 5: " + String(stripLength));

    frame++;
}
void LightingStrip::write(){
    Serial.println("write");
    Serial.println("stripLength: " + String(stripLength));

    int16_t j;

    for(j=0; j<stripLength; j++){
        Serial.print(" j: " + String(j));
        strip.setPixelColor(j, buf[j]);
    }
    Serial.println();
    Serial.println(String(buf[0]));
    Serial.println(String(strip.getPixelColor(0)));
    strip.show();
}

Serial Output:

BugFinding
Color 0: 16742400
Color 0: 16742400
stripLength: 100
setColors
stripLength: 100
loop
frameStep
Color 0: 16742400
frame: 0
colorFrame: 1
stripLength 1: 100
stripLength 1.2: 100

I think what you mean by stripLength "disappearing" is that your stripLength 2 trace does not appear. This is going to be because you never reach this point in the code.

Look at buf: it's defined as an array in the .h file, but you don't ever allocate any memory for it. buf[stripLength] = {0} doesn't do what you think it does. It puts a 0 into element 100, which at that point is going to trash over some memory you don't mean to write to. When you write to every element in the loop, you're going to trash over lots of memory you didn't mean to.  You want something like

buf = (uint32_t*) malloc(stripLength*sizeof(uint32_t));

Remember to free it again in the destructor.

(Full disclosure: I'm writing this on my phone and I can't remember or test whether it's legal syntax to do this with your array defined (in the .h) as uint32_t buf[]. It's more common, and certainly legal, to use uint32_t* buf.)


Concatenate two non constant char arrays in Arduino I have two non constant char arrays. One is "buff" and other is "buffa". I get values in buffa via rf transmitter of other Arduino and I want to append those data to the data inside of buff. Then I will send all data to other Arduino. So I don't want to send two different char arrays. I want to send them all at once as just one array.

I TRIED SPRINTF BUT IT DOESNT WORK.

char buffa[144];
    char buff[1000];

void loop() {

  uint8_t buf[VW_MAX_MESSAGE_LEN];
  uint8_t buflen = VW_MAX_MESSAGE_LEN;

  sprintf(buff,"<status>\n");

    if (vw_get_message(buf, &buflen)) { // check to see if anything has been received
      int i;
      for (i = 0; i < buflen; i++) {
        buffa[i] = (char) buf[i];  // the received data is stored in buffer

      }
    }

  distance1 = getDistance(initPin1, echoPin1);
  sendData(3, distance1);

  sprintf(buff, "%s", buffa);

delay(5000);
 const char *msg0 = buff;

 vw_send((uint8_t *)msg0, strlen(msg0)); // Send control character
 vw_wait_tx();

 Serial.print(msg0);

}

Assuming the data in buffa is a c-style string (i.e. null-terminated), replace

sprintf(buff, "%s", buffa);

with

strcat( buff, buffa );


PCA9685 servo shield not working Im working on a project where I want to connect 32 servos together.
 I got:
-Arduino uno
-2 PCA9685 16-Channel 12-bit PWM/Servo Shield
-power supply 5v 10 A
-All wiring is to the right pins (I have checked that several times)

So I got the 2 PCA9685 16-Channel 12-bit PWM/Servo Shield from Adafruit I connected all the wires as its supposed to be and I connected the shield to an external power supply which is 5V 10A that should be sufficient for it to work but unfortunately servos are not moving at all although the serial monitor is giving numbers I don't know where is the problem coming from.
ps. Im using the Adafruit library
its not even moving one servo (although the servo moves when connected directly to the Arduino.
thank you in advance.

the code I'm using its one of the examples from the library:

/***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 8 servos, one after the other on the
  first 8 pins of the PCA9685

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These drivers use I2C to communicate, 2 pins are required to
  interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

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

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
// you can also call it with a different address you want
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);
// you can also call it with a different address and I2C interface
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(&Wire, 0x40);

// Depending on your servo make, the pulse width min and max may vary, you
// want these to be as small/large as possible without hitting the hard stop
// for max range. You'll have to tweak them as necessary to match the servos you
// have!
#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

// our servo # counter
uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("8 channel Servo test!");

  pwm.begin();

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

  delay(10);
}

// you can use this function if you'd like to set the pulse length in seconds
// e.g. setServoPulse(0, 0.001) is a ~1 millisecond pulse width. its not precise!
void setServoPulse(uint8_t n, double pulse) {
  double pulselength;

  pulselength = 1000000;   // 1,000,000 us per second
  pulselength /= 60;   // 60 Hz
  Serial.print(pulselength); Serial.println(" us per period");
  pulselength /= 4096;  // 12 bits of resolution
  Serial.print(pulselength); Serial.println(" us per bit");
  pulse *= 1000000;  // convert to us
  pulse /= pulselength;
  Serial.println(pulse);
  pwm.setPWM(n, 0, pulse);
}

void loop() {
  // Drive each servo one at a time
  Serial.println(servonum);
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
    pwm.setPWM(servonum, 0, pulselen);
  }

  delay(500);
  for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
    pwm.setPWM(servonum, 0, pulselen);
  }

  delay(500);

  servonum ++;
  if (servonum > 7) servonum = 0;
}

You have your SDA and SCL pins connected backwards.

SDA is A4
SCL is A5

You have it the other way around.


At what level does low dynamic memory effect performance? I have a few Arduino sketches that take 70-90% of dynamic memory. It seems that over 70%, the compiler gives the warning:

Low memory available, stability problems may occur.

but otherwise I wasn't noticing any problems.

Then I uploaded a sketch that took 89%, which logged String data to the serial port, and found that only newlines were being written out. When I commented out some global variables so that dynamic memory usage got to 88%, then it started printing out the data.

Is there any hard/fast rule on when this problem occurs? I was surprised by this problem, because the global variables I removed weren't even being used in the sketch, so I had thought the compiler would have removed or optimized them so they didn't waste any space. Are there any ways to automatically improve compilation efficiency and detect wasteful variables?

The typical build memory statistics is:

Global variables use XXX bytes (X%) of dynamic memory,
leaving YYY bytes for local variables.
Maximum is ZZZ bytes.

What is all this about? First, the maximum number of bytes SRAM depends on the MCU. Arduino Uno is ATmega328 based and has 2K byte SRAM. Arduino Mega2560 has 8K byte. "Dynamic memory" in the print out is SRAM. It is not the heap (malloc/free). To avoid confusion I will use "data memory" below.

The compiler allocates memory for all global variable (objects, struct, etc). It also allocates memory for literal strings (character vectors). These are copied from program memory to data memory at startup. All static variables in functions are also allocated. The sum of all these allocations are the "Global variables".

To execute the sketch data memory is used for the stack. It contains the function parameters, local variables in called functions (that are not allocated to registers), saved registers such as return address to the caller, etc. The size of the frame is known by the compiler and may be found in the assembly listing of a sketch. The maximum stack size required is tricky to calculate as it is the call chain with the largest frame size sum. This is not necessarily the deepest call chain. Also the compiler does to a fair amount of inlining.

The heap (malloc/free) is used by classes such as String. The heap starts directly after the global variables in data memory and grows towards the stack. The heap is blocks of memory allocated and deallocated during the execution of the sketch. This behavior may give heap fragmentation.

Interrupt Service Routines (ISR) need to be able to execute "on top of" any function call. The ISRs are typically called on hardware events such as USART data received. The compiler has to generate code that stores the machine state on stack to execute the ISR. Depending on how many registers the ISR needs more or less of the machine state (registers) need to be stored. The worst case is all 32 registers.

The warning at 30% of SRAM is at approx. 600 bytes left (Arduino Uno, 2K byte). That has to cover the stack and possible heap usage together with ISRs. With a stack heap limit of 32-128 byte, ISR frame of 32-64 byte, that actually leaves worst case approx. 400 bytes for local variables in functions and possible usage of the heap (such as String).

Cheers!


How does Arduino distinguish between SPI programming data and regular data? The Arduino can be programmed using SPI without a boot loader. Without a boot loader, the Arduino starts running its sketch right away. So, how does the Arduino know that it is being programmed via SPI vs regular SPI traffic already present on the SPI bus? Was is the pin-level, electrical signal that let's the Arduino know the difference?

In-system programmer is activated with RESET line. During normal operation reset line is not active and ISP module is disabled.

You can find detailed description of AVR ISP in this document:

http://www.atmel.com/images/doc0943.pdf


Port Not Being Found Hey everyone I know this is a pretty common question, and I have read/tried almost everything on all the other posts here and on the arduino.cc forums, but I have been unable to fix my problem. Basically I have been using my Arduino Leonardo for a little over a month now for all sorts of things and have never had this issue with the Arduino not showing up under the port tab on the menu. I have no idea why this just started happening to me, I am using the same cable, etc, and was hoping someone could help me out. I am on a MacBook Pro by the way.

Thanks in advance.

Try this...
Go to your Arduino IDE.
Under the Tools tab, go to "Board" and select Arduino Leonardo.
Then in the Tools tab, go to Port and check to see if a port is selected.
Use this link to try and find which Serial Port you should have: https://www.arduino.cc/en/Guide/MacOSX
Try plugging in the cable in different USB ports on your computer and see if the port number changes automatically.

Also, could you please say what peripherals or other things are connected to the arduino? Because for example, I know what using a Bluetooth slave with the Arduino while connected with the cable to your computer, doesn't let you upload your program. There could be similar problems to this.


Uno - PCA9685 Servos are too shaky before stabilizing - when using two channels I'm trying to control a Tilt pan with an Arduino Uno. And the Sunrounder servo driver is used to do this, which comes with it's own capacitor out of the box.

The pan has two Servo motors, that help it face any direction.

I have set this up and even calibrated, so that I can input numbers between -90 degrees to +90 degrees horizontally, and 0 to 90 vertically. And it is working...

But the problem is that, when it is idle for too long, or when I connect it in the beginning, The tilt pan shakes intensely for about 20 to 30 seconds and turns every other direction before stabilizing to the correct point. As if it had a seizure!

When I disconnect one of the Servos, this problem solves. Two servos are connected to the first and second channel of the servo driver. So it seems that these two channels have an effect on each other.

Besides, there is not much weight on the tilt pane. And removing the weight does not seem to help.

init code:

pwm = Adafruit_PWMServoDriver();
pwm.begin();
pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
yield();

turning horizontally:

void Platform::setHorizontal(int d){
  if(d > 90)
    d = 90;
  if(d < -90)
    d = -90;
  point->setHorizontal(d);
  d = (d * 2.555) + 70.0; // calibrating.
  pwm.setPWM(0, 0, 325 + d); // 325 = (150 + 600) / 2
}

How can I solve this?

Start by verifying the power supply is adequate, then go from there. If nothing else try a much bigger capacitor.


Calculate statistic in EEPROM I've search on how to do statistic calculation in EEPROM, but non related.
The data that I stored in EEPROM is body temperature.
Currently I stored the data using float.

Below is my code for data store in eeprom.
I'm stuck at the void function named "printTemp". I know how to calculate average in array using for loop statement, but not EEPROM. From average/mean, I can find standard deviation.

Does anyone have an idea on how can we do calculation using data from EEPROM?

#define LM35 A1
#define READSAMPLES 100

float bt;
int buttonPin1 = D5;     // the number of the pushbutton pin 1 MEASURE
int buttonPin2 = D6;     // the number of the pushbutton pin 2 RESET CYCLE
int buttonState = 0;         // variable for reading the pushbutton status
int ButtonState = 0;         // variable for reading the pushbutton status
int address = 0;      //EEPROM address counter
int count, counT;
int sample[READSAMPLES];

void setup() {

    int contCount = EEPROM.get(5, count) / 10;

}

void loop() {

  buttonState = digitalRead(buttonPin1);
  ButtonState = digitalRead(buttonPin2);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
        Serial.println("Measuring your Body Temperature:");

        count = counting();
        counT = count / 10;
        Serial.print("Data count entering: ");
        Serial.println(counT);

        writeTemp();
  }

  if (ButtonState == LOW) {

        Serial.println("Update New Cycle of body temp...");
        printTemp();
        clearEEPROM();
        Particle.publish("DONE new Cycle");

  }

}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    float cel = EEPROM.read(i);                //read EEPROM data at address i
    //How to find MEAN of all data?
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  //getting the voltage reading from the temperature sensor
  int j;
  float average;
  for (j = 0; j < READSAMPLES; j++)
  {
    sample[j] = analogRead(LM35);        //read sensor value
    delay(50);
  }

  average = 0;
  for (j = 0; j < READSAMPLES; j++)
  {
    average += sample[j];
  }
  average /= READSAMPLES;

  //float mv = ( average / 4096.0) * 3300;
  //float cel = ( mv / 10 ) - 55.01;
  float mv = ( average / 1024.0) * 5000;
  float cel = ( mv / 10 );

  EEPROM.write(address, cel);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

float counting()
{
  count = count + 10;   // plus 10 is because to give a space for data entering the eeprom for LATER CODE. Just live it here.
    Particle.publish("Start Count =", String(count));
  return count;
}

What I can share from my problem findings are, to do the calculation of statistic from EEPROM data;

we need to know how to read back all the data in EEPROM. As in my code I know how to read the data, but the data cannot be hold because in FOR loop the the process will running until the end of 'i'.
we need to know how many data are there in EEPROM that have entered. To solve this, I'm using count; in order to count the entering data.

I need suggestion links or maybe any idea on how to do statistics in EEPROM.

Thanks.

Doing that calculation from EEPROM is exactly the same as doing it from any other source.  You have a count so you know where the EEPROM data ends.  You know where the EEPROM data starts.  You know how to read a number out of EEPROM.  What is stopping you from creating a for loop to read the i'th address from EEPROM and add all those numbers together just like you would for an array?

for (int i = EEPROM_START; i < EEPROM_END; i++){
   sum = sum + EEPROM.read(i);
}
average = sum / count;

where EEPROM_START and EEPROM_END are supplied by you by knowing what address you started and ended writing at.


How to Measure many voltages (Uno) - Analog extenders a good option? I am trying to make a battery capacity tester (3.7v li-ion 18650 battery) using arduino uno. If possible i'd like to test 20 or more batteries at the same time. I need to measure the voltage of each battery every 1 second.

The uno has 6 anolog inputs iirc so too little for this application.
I think using analog multiple extenders (connected using I2C) chained together to create enough analog inputs.
For example this one: https://nl.aliexpress.com/item/32858973834.html?spm=a2g0o.productlist.0.0.57206143DNgWKp&algo_pvid=526d42f2-f7ee-4781-932b-947744ac631e&algo_expid=526d42f2-f7ee-4781-932b-947744ac631e-0&btsid=89c452fa-1d7c-4ae9-9dd5-ed8fc9bff128&ws_ab_test=searchweb0_0,searchweb201602_8,searchweb201603_52
Do you think I'll be able to get relatively accurate voltage measurements using this approach?

The purpose of the circuit is to measure the amount of mah (battery capacity) of the 18650 battery which is being discharged via the 10Ohm resistor. The battery will be discharged from 4.2volt (fully charged) to approx 2.5V using the 10ohm resistor, each second the voltage drop over the resistor will be measured and using it and the time passed the integral of time*current will be calculated to determine the capacity.

This is the basic circuit used to connect each 18650 battery, the ANALOG1 pin will be connected to the input of the analog extenders:

(I based it off of the circuit from this video: https://www.youtube.com/watch?v=WScPyfQz_f8)
The idea is to measure the voltage drop over the 10Ohm10W power resistor and calculate the current using the known resistance value, calculate the integral of current*time to get a capacity value for the battery.

Is this a good approach? Would you recommend using analog extenders for this? If not what would be a better solution? Thank you very much!

Actually it is two separate questions and I answer your first question of reading multiple analog values using one ADC and the answer is Yes you can use this approach but  you should give enough time for each channel to charge internal ADC capacitor when you change channel .so if you use more independent ADC you get more time for each channel and result is better


Can I replace Atmega8 with Atmega328 in my freeduino board? Can I replace Atmega8 with Atmega328 in my freeduino board?
If so, let me know the steps needed.

Shouldn't be a problem. Some later versions already have a ATMega168 instead of the ATMega8. All three are pin-compatible.

In the arduino IDE you should however select a different board (one with a 328, like the UNO). That way the compiler knows the target MCU is the 328, and not the 8.


Use command line to upload hex code to teensy.ex I need a command line implementation for uploading code to Teensy-LC through Windows 8.1 operating system
I know Paul has not released support for command line for Teensy-LC yet but i would like to know if any work has been done by anybody else in this regard.
I asked this and this. But all these solutions include

sending the hex file to the user.
Asking him to open Teensy.exe
Asking him to upload the hex file into Teensy.ex
Asking him to run teensy_reboot.exe

So is it possible to create an installer of a sort for this purpose which eliminates the user performing all these operations separately and a guided installer simply with Next->Next which does the entire job.
But I suppose that since Command Line installer is not available for windows I don't know if this is possible for impossible.
So if there is any way I can achieve an installer UI for Teensy-LC bootloader that would be perfect
Other viable option
If not that is it possible to make the entire process happen with the person not having direct access to the hex file.
Like sending a packaged installer or something
I am not sure how this would happen but if there is any possible way please help me out

This is starting to drift off topic for this site, but the best solution for making an automated programming utility for the Teensy on Windows, short of writing one yourself, would be to use some kind of UI automation framework to automate the process described in my earlier answer. My favorite one that I have used in the past is AutoIt. It has tools to inspect applications so that you can programmatically click buttons and fill out fields. There are even ways of having it run programs without them being visible to the user. There are plenty of tutorials on the web on how to use AutoIt so I would suggest googling for that. If you have further questions on how to do that, they would be more appropriate on a site other than Arduino.SE.


Simple multiplication bug Executing the following code always gives -511 as a result, I performed many tests, and it seems that results are correct from 0 * 0 to 181 * 181, beyond that, results are abnormal, I tried many types for the z variable (int, long, float) without success, any idea? I'm using the Arduino Uno.

long z = 0;

void setup() {

Serial.begin(9600);

}

void loop() {

  z = 255 * 255;
  Serial.println(z);
  delay(200);

}

No, this is not a bug. You are using a compile time constant expression which is signed int unless told otherwise. Therefore you can only represent numbers between -32768 and 32767. Your computation of 255 * 255 = 65025 exceeds the range. Thus you see an overflow. In the C/C++ standard the overflow of signed types is actually undefined behavior. That means that the compiler is allowed to do anything from showing the correct answer to halt and catch fire. Only unsigned types with a known size like uint16_t have a well-defined overflow behaviour. You should promote your right hand side computation to unsigned type like this:

z = 255U * 255U;

This way you tell the compiler your intention and don't land in "Undefined-Behaviour-Land".


Voltage divider for 6 non intrusive current sensors I have an Arduino project where I intend to use 6 non intrusive current sensor model SCT013 (100A/50mA) manufactured by yhdc.com

As reference voltage on examples I find at the internet it is suggested the use of 2 10K resistor connected in series from 5V to ground, the reference voltage is extracted from the middle connection between the resistors (2.5v).

Question:

In the case of six sensors will I have to use 6 independent voltage dividers or can I use a single divider as reference for all sensors?

I am concerned the interference between sensors may cause reading imprecision.

Thanks in advance
Paulo

I assume you refer to a circuit like this:

simulate this circuit – Schematic created using CircuitLab

The "reference" you speak of is not a reference - it is a virtual ground. A ground reference that is at a different potential to the Arduino - in this case 2.5V higher.

Since it is just the ground for the circuit you can use the same one for all the current transformers without problems.

If the offset voltage were applied to the output (as is often done for active devices that create an AC waveform, such as audio signals) then you would require a separate offset voltage for each one, since otherwise you would be connecting all the outputs together, which would be bad.

You can also "reverse" your thinking. The "offset" voltage you apply is ground, and the Arduino's "ground" is 2.5V below that. It's all relative.


(ESP8266) Check if a SSID is in range I need to check if a given SSID is in range. Would be good if it didn't disconnect from the current wifi network that it's connected to, but it doesnt matter, i just need to see if a SSID is in range, whether it does disconnect or not.
It should be something like this:

if(WiFi.SSID(checkforthisSSID)) {
  //do something
}

Thanks.

Not so tough it is possible just try the bellow code :)

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  CheckPossibility();
  }

 CheckPossibility(){
 int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      if(WiFi.SSID(i) == "REPLACE THIS WITH YOUR SSID"){ //enter the ssid which you want to search
      Serial.println("The network you are looking for is available");
      }
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
 // delay(5000);
}


Connecting to Nano via USB3 I have a Uno (third party) that I connect to my Dell laptop with no problems at all. But I've just received a Nano (also third party) that I just can't get to upload. After lots of interneting, I hit Windows normally-useless troubleshooting tool. That tells me that the USB device (the Nano) doesn't understand USB3 and I should plug it into a USB2 port. Unfortunately, being a new machine there IS no USB2 port.

Is Windows Troubleshooting lying? Is there a problem interfacing with a Nano via USB3?

Edit: Error message is:

stk500_recv(): programmer is not responding

Windows troubleshooter is just trying to tell you that you've plugged a USB2 device into a USB3 port, thus wasting its USB3 capabilities which could be useful for another device. Of course, if you only have USB3, you can't do otherwise.

USB3 is fully backward-compatible with USB2, so whatever your problem is, it is not related to the fact that you plug the Nano into a USB3 port. Perhaps your problem comes from the fact that your Nano is "third party" - I suppose that means it's not the original device and thus it may not be fully compatible. If my guess is right, try to find out what programmer your Nano clone supports: chances are you just need to select a different programmer type in Arduino settings, or buy a separate programmer supported by your device.


What is GND on board? I've looked in several places, and so far can not understand to want to be the GND who is on the board.

There is this documented anywhere?

It is the 0V reference for everything else, as well as the power supply return.

"Ground (electricity)" on Wikipedia


Stable temperature sensor under voltage fluctuations I'm looking for an inexpensive temperature sensor which is non reliant on the input voltage to return an analog reading back or some sort of digital signal. Accuracy is not very important, for instance +/- 4 C is fine. The lm35 I have been using jumps from 25 to 70 degrees regularly with changes in circuit load.

My other option is to add a separate voltage regulator, but I am trying to avoid that if possible! Thanks!

The DS18B20 is a temperature sensor with a digital interface (1-Wire). It works at 3.3 to 5V and the cable length can be a number of meters. It is accurate to 0.5°C.

The DS18B20 is probably the most used temperature sensor for Arduino projects. Its price starts at less than a dollar/euro. You only need the DS18B20, a pullup resistor of 10k and a digital pin.

In the Arduino IDE, go to the Library Manager and search for 'onewire'. Install the "OneWire by Jim Studt, Tom Pollard, ... Paul Stoffregen, ...".
Then search for 'dallas' and install "DallasTemperature by Miles Burton, ...".
The OneWire library on its own can read the temperature of the DS18B20, but the DallasTemperature makes it easier to use.
Look for the examples of the DallasTemperature in the Arduino IDE to start with the DS18B20.

The 1-Wire is a bus, you can add more DS18B20 sensors to the same wire. The DallasTemperature library has two options. Select either a sensor by index, or by its ID. Every DS18B20 has a unique ID inside the sensor.

Sometimes an analog temperature sensor has specific advantages, for example a ntc temperature sensor or a thermocouple sensor. For normal indoor or outdoor usage, the digital temperature sensors are far more easier to use.

Why measure only the temperature ? If you want the baromic pressure and humidity as well, the BME280 has it all. Its temperature accuracy is not very accurate, it is only ±1°C.


How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)? I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules.
For transmitting I use the library VirtualWire and It works very well for this code:

#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[7] = {'h','e','l','l','o',' ','!'};
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  delay(1000);
}

I was wondering if I want to send some string or int data how I can do that.
I tried to use it for string data but I couldn't because the Input of function vw_send(...) is char and I couldn't use int or string.
finally I run this code:

#include <VirtualWire.h>
void setup()
{
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
}
void loop()
{
  char msg[11]="Hello there";
  vw_send((uint8_t *)msg, 11);
  vw_wait_tx(); // Wait until the whole message is gone
delay(1000);
}

and I could send Hello there !, but I'm looking for the correct way for sending string and int.

Have a look at the Easy Transfer library.  I haven't used the particular modules you have, however I did successfully use the EasyTransfer library with Ciseco wireless modules.  In essence the EasyTransfer library transmits the data as a structure with the same format on each module.  The structure can contain any data type.


Arduino IR not returning data THIS QUESTION ISN'T IN USE ANYMORE

  Solved by using an other remote that is supported by the libary

====NEW CODE====

    #include <IRremote.h>

    int RECV_PIN = 11;
    int relay1 = 2;
    int relay2 = 3;
    int relay3 = 4;

    int on = 1;
    int on1 = 1;
    int on2 = 1;

    IRrecv irrecv(RECV_PIN);
    decode_results results;

    void setup()
    {
      digitalWrite(relay3, HIGH);
      pinMode(relay3, OUTPUT);
      digitalWrite(relay2, HIGH);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, HIGH);
      pinMode(relay1, OUTPUT);
      pinMode(13, OUTPUT);
      irrecv.blink13(true);
      irrecv.enableIRIn();
    }

    unsigned long last = millis();

    void loop() {
      if (irrecv.decode(&results)){
        if (results.value == 0x36167A85) {
          if (millis() - last > 250) {
            on = !on;
            digitalWrite(relay1, on ? HIGH : LOW);
          }
          last = millis();
        } else if (results.value == 0x36161AE5) {
          if (millis() - last > 250) {
            on1 = !on1;
            digitalWrite(relay2, on1 ? HIGH : LOW);
          }
             last = millis();
        } else if (results.value == 0x3616FA05) {
         if (millis() - last > 250) {
            on2 = !on2;
            digitalWrite(relay3, on2 ? HIGH : LOW);
          }
            last = millis();
        }
        irrecv.resume();
      }
    }

================

I'm working on this bit of arduino code for a while now but i can't get it to work. My circuit is wired up correctly, but it isn't returning any data in the serial prompt. Here is my code:

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

int main = 0;
int left = 0;
int right = 0;

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

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    switch (results.value) {
      case 0x2E3A06C0:
        main = 1;
        Serial.println("MAIN: on");
        break;
      case 0x8C2921D6:
        left = 1;
        Serial.println("LEFT: on");
        break;
      case 0x226270DA:
        right = 1;
        Serial.println("RIGHT: on");
        break;
      case 0x4AC6E6A:
        main = 0;
        Serial.println("MAIN: off");
        break;
      case 0xDD5E26EF:
        left = 0;
        Serial.println("LEFT: off");
        break;
      case 0x3E5BEF99:
        right = 0;
        Serial.println("RIGHT: off");
        break;
    }
    irrecv.resume();
  }

  delay(100);
}

I'm using the libary Arduino-IRremote. When I try the demo "IRrecvDemo", it works fine. I have the hex codes from this demo. So can someone help me get this code working? It would be nice!

Did you try removing the 0x indicator? If I remember correctly the incoming signals are raw, e.g. 2E3A06C0, even though the script requires the 0x indicator on the send routines.

Alternatively, you'd need to rewrite, but you could try this IR Library and code, which I found has much better documentation and data analysis options on the receiving side: https://github.com/cyborg5/IRLib/


Accelerometer MPU-6050 marks timeout in Unity I've been having this problem, that I am trying to use an accelerometer MPU-6050 to get the rotation and pass that information to Unity.

I also have some buttons in the same Arduino. I'm using an Arduino Uno. With those buttons, everything works well, but the moment I put something related to the accelerometer in the Arduino code, Unity marks a time out. When I run it on Arduino it sends me all the info I'm asking, so I don't really know what's the problem. I really appreciate if someone could help me.

Here is code on Arduino:

#include<Wire.h>
#define A_R 16384.0
#define G_R 131.0
 #define RAD_A_DEG = 57.295779
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int AcX,AcY,AcZ,GyX,GyY;

float Acc[2];
float Gy[2];
float Angle[2];
int button = 0;
int button2 = 0;
int button3 = 0;

float arriba=0, abajo=0,mouse=0;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
  pinMode(7, INPUT); // declare pushbutton as input
pinMode(6, INPUT);
pinMode(5,INPUT);
  Serial.begin(9600);
}

void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  //Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers

  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
 AcZ=Wire.read()<<8|Wire.read();

  Acc[1] = atan(-1*(AcX/A_R)/sqrt(pow((AcY/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;
   Acc[0] = atan((AcY/A_R)/sqrt(pow((AcX/A_R),2) + pow((AcZ/A_R),2)))*RAD_TO_DEG;

  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)

  Angle[0] = 0.98 *(Angle[0]+Gy[0]*0.010) + 0.02*Acc[0];
   Angle[1] = 0.98 *(Angle[1]+Gy[1]*0.010) + 0.02*Acc[1];

        button = digitalRead(7);
  button2 = digitalRead(6);
  button3 = digitalRead (5);

   //Mostrar los valores por consola
   if(button == HIGH){
 arriba=1;
  }else if(button==LOW){
  arriba=0;
  }

  if(button2 == HIGH){
    abajo=1;
  }else if(button2==LOW){
    abajo=0;
  }

  if(button3 == HIGH){  //boton 3
    mouse=1;
  }else if(button3==LOW){
    mouse=0;
  }
  Serial.print(arriba);
  Serial.print(",");
  Serial.print(abajo);
  Serial.print(",");
  Serial.print(mouse);
   Serial.print(",");

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

  delay(200);
}

I know this isn't an Unity forum, but here is the code in Unity. The only thing it does, is read it and put the results in an array.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Globalization;
using System;

using UnityEngine;

public class ConectarArduino: MonoBehaviour
{
    string Recibidos;
    public string Linea, Linea1,Linea2;
    public int Arrib, Abajo,Boton;
    SerialPort stream;
    // Use this for initialization

    void Start()
    {
        stream = new SerialPort("COM3", 9600);
        //  stream.
        stream.Open();
        stream.ReadTimeout = 300;

    }

    // Update is called once per frame
    void Update()
    {
        try
        {
            Recibidos = stream.ReadLine();
            Debug.Log(Recibidos);
        }
        catch (System.Exception e)
        {
            Debug.Log(e.Message);
            throw;
        }

        string[] Values = Recibidos.Split(',').Select(str => str.Trim()).ToArray();
        Linea = Values[0];
        Linea1 = Values[1];
        Linea2 = Values[2];

Running MPU-6050 at 57600bps seemed to be the good rate for me:

  pinMode(5,INPUT);
  Serial.begin(57600);
}

It worked for me and I found these guys for whom it was the good rate :

From MPU-6050-simple-library, specifically MPU6050_test.ino:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

From Another Arduino as external i2c device for MPU6050:

void setup() {
  Wire.begin(0x1E);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(57600);           // start serial for output
}

From Library for Arduino and MPU-6050 communication:

void setup() {
  Serial.begin(57600);
  MPU6050mgr.begin(); // Initializes IMU module
}

You may also find this link useful: MPU-6050 Redux: DMP Data Fusion vs. Complementary Filter.


Servo library unable to control more than 11 servos I am working on assembling the ROFI robot from Project Biped (http://www.projectbiped.com/prototypes/rofi) and I have not been able to run any arduino program as they will not function correctly.

To be more specific, when I attempt to run 12 servos on a single Arduino Mega, the servos twitch uncontrollably and do not move to the positions which are set in the program.  At the same time the power light on the arduino mega blinks and does not turn solid (as opposed to if I use less than 11 servos when the pwr light is solid).  I predict it might be the power source but after checking the batteries with the multimeter they check out to be fine (7.6 V).  The circuit is pretty simple, I am using a servo shield connected to a 6V regulator connected in parallel to two 7.2 V 1350 mah LiPo batteries.  The arduino is connected through the dc power jack to the same circuit in parallel.

Here is the code...

   #include <Servo.h>

// 0 Right Ankle (roll)
// 1 Right Lower Leg
// 2 Right Knee
// 3 Right Middle Leg
// 4 Right Upper Leg
// 5 Right Hip (roll)
//LEFT LEG JOINTS
// 6 Left Ankle (roll)
// 7 Left Lower Leg
// 8 Left Knee
// 9 Left Middle Leg
// 10 Left Upper Leg
// 11 Left Hip (roll)

int c=0;

Servo rightAnkle;
Servo lowerLeg;
Servo rightKnee;
Servo rightMiddleLeg;
Servo rightUpperLeg;
Servo rightHip;
Servo leftAnkle;
Servo leftLowerLeg;
Servo leftKnee;
Servo leftMiddleLeg;
Servo leftUpperLeg;
Servo leftHip;

void setup(){
  rightAnkle.attach(0);
  lowerLeg.attach(1);
  rightKnee.attach(2);
  rightMiddleLeg.attach(3);
  rightUpperLeg.attach(4);
  rightHip.attach(5);
  leftAnkle.attach(6);
  leftLowerLeg.attach(7);
  //leftKnee.attach(8);
  //leftMiddleLeg.attach(9);
  leftUpperLeg.attach(10);
  leftHip.attach(11);
}

void loop(){
  rightAnkle.write(90);
  lowerLeg.write(90);
  rightKnee.write(90);
  rightMiddleLeg.write(90);
  rightUpperLeg.write(90);
  rightHip.write(100);
  leftAnkle.write(90);
  leftLowerLeg.write(90);
  leftKnee.write(90);
  leftMiddleLeg.write(90);
  leftUpperLeg.write(90);
  leftHip.write(90);
}

It sounds to me like you're exceeding the current limits of your power supply. Add up the current drawn by your servos (and their controller(s), and also the current drawn by your Arduino and any other circuits you have. I bet you'll find that at 12 servos, you go over the current limit of your regulator. You might need a higher current regulator or a second one.


Oscillating Output from Arduino Pins when not in use, why? I have A1 set to be an input, have the program read it, and then print to the serial monitor. My question is, when the circuit is not receiving power, but is grounded, and is still connected to A1, when do I see an output pattern of, for example:

0,0,0,0,7,23,16,9,4,0,0,0,0,3,18,21,15,0,0,0.....

I have a different detector inputing to A0 and if I don't have A1 connected then I get a reading that is similar to what I would see if I was actually reading A0 (around 900). Then if I plug back into A1 the value drops to around 350. When A0 is unplugged and only A1 is plugged in I only get noise (ie the pattern above in the code section).

I'm thinking along the same lines as CrossRoads and dandavis above. Would you be able to post a circuit diagram? If you haven't grounded the input, it could be floating or picking up noise from the surrounding environment. A 5k pulldown resistor may fix the problem, depending on what your circuit looks like and the environment its in.


Are there any ePaper modules that are bigger than 2.7 inches for arduino I am looking for a large ePaper Display for the Arduino. The issue is is that I cannot seem to find one any larger than 4.5 inches in size. That will be compatible with arduino. Even with a controller board.

Are there any companies that sell controller boards for these displays? Is there anyone who can manufacture these epd displays upon request?

I am looking to take this project to a pcb board after I prototype it so do I need to build my own controller? If what parts would you need? Is it easy for a designer with intermediate capability?

I can find all kinds of display like at pervasivedisplays.com and Mouser.com

The end goal is to create a Arduino based project that I can score skeet with to keep track of my average score.

I would suggest you to start the other way: find a sw stack that is known to work and check if any of the controllers/displays it already supports fits your needs. This is how I would do it.

Here is a starting point.


Using the Broadcom AFBR-S50 with Arduino I'm trying to interface with a Broadcom AFBR-S50MV85G ToF sensor over SPI using an Arduino, which is complicated by the fact that the provided library and reference application is written for Cortex M0-based NXP microcontrollers. The documentation says that implementing the SPI, IRQ, Debug and Timer interfaces would allow use with other platforms, but it doesn't explicitly state which functions require implementations, or if all of them do, and it's not demarcated within the source code either.

The documentation lists the available command words, but no register addresses, which I believe are used by the platform-independent compiled libraries that come with it. This leaves me with no way to interface manually over SPI, meaning that my only choice appears to be to attempt to implement the platform drivers myself, which will probably take me a significant amount of time.

Is there something else I should try before sinking time into something that may not give me results? Has anyone here used this sensor before, and if so, could you point me in the right direction?

P.S.: The documentation I'm referring to is included in the SDK provided in the downloads section of the product page, and I'm not sure I'd be allowed to rehost it somewhere else in order to link it here.

I recently looked into this again, and it turns out that Broadcom had released a porting guide for this library in August 2020 (nearly a year after I originally posted this question) that should prove useful to anyone trying to make use of this sensor. It's for the STM32 platform, not Arduino, but it's the most detail Broadcom has provided with regards to this product, and should provide a starting point at least.
I happen to have access to the Nucleo board used in the guide, but I had some issues with following it in some cases due to some differences in the SDK file/directory structure. I did eventually get a passing build out of it, but couldn't get anything out of the sensor itself, which means that I either did something wrong, or had damaged the sensor in my earlier attempts to interface with it; at the time of my last attempt, I was leaning towards the latter. I don't think I'll be revisiting this unit any time soon, so hopefully others will have better luck. And if anyone does get it working, please do report back; I'm curious to know if I'd actually be able to use this thing if I were to buy another one.
P.S: I'm not marking this as answered because a) my question was technically for the Arduino, and b) I haven't been able to confirm that this is working.


Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12) I have managed to get my 1602 I2C LCD working on a NodeMCU devkit. I can display text parsed from the web but I am not sure how to set it to autroscroll if message is greater than 16 characters. I tried the lcd.ScrollDisplayLeft() but it doesn't work. I figured I would have to do it manually and it is a matter of getting string length and then looping the characters.

This is what I have so far:

#include <ESP8266WiFi.h>
#include <Wire.h>  // This library is already built in to the Arduino IDE
#include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library >

LiquidCrystal_I2C lcd(0x3F, 16, 2);

const char* ssid = "ssid";
const char* password = "pass";
const char* host = "api.thingspeak.com";

int find_text(String needle, String haystack, int from) {
  int foundpos = -1;
  if (haystack.length() < needle.length())
    return foundpos;
  for (int i = from; (i < haystack.length() - needle.length()); i++) {
    if (haystack.substring(i, needle.length() + i) == needle) {
      foundpos = i;
      return foundpos;
    }
  }
  return foundpos;
}

void setup() {
  Serial.begin(115200);
  delay(100);
  lcd.init();   // initializing the LCD
  lcd.backlight(); // Enable or Turn On the backlight
  delay(200);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  lcd.setCursor(0, 0);
  Serial.print("Connecting to ");
  lcd.print("Connecting");
  lcd.setCursor(1, 1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    lcd.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Connected!!");
  delay(1000);
}
int value = 0;

void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

  }

  // We now create a URI for the request
  String url = "/apps/thinghttp/send_request?api_key=345345345345345";
  Serial.print("Requesting URL: ");
  Serial.println(url);
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Fetching Data..");
  delay(10000);

  // Read all the lines of the reply from server and print them to Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');

    int start_loc = find_text("<b>", line, 0);
    int end_loc = find_text("</b>", line, 0);
    if (start_loc > 0 && end_loc > 0)
    {
      lcd.clear();
      Serial.println("data:  ");
      lcd.print("data: ");
      lcd.setCursor(1, 1);
      for (int i = start_loc + 3; i < end_loc; i++)
      {
        Serial.print(line[i]);
        lcd.print(line[i]);
     }

  Serial.println();
  Serial.println("closing connection");
  delay(2000);

}
  }
}

Inspecting the library code, it is apparent that the method called only sets up a command bit field and it is actually the display that performs the operation.

So, you might check if your LCD is capable of performing the scrolling operation.

This web page contains a tutorial on how to use the scrolling feature.  In this code example from that page:

void loop() {
  // scroll 13 positions (string length) to the left
  // to move it offscreen left:
  for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
    // scroll one position left:
    lcd.scrollDisplayLeft();
    // wait a bit:
    delay(150);
  }

...you can see that it is not automatic.  That you need to call the method each time you want to scroll (in this case) one position to the left.


Sensing busy-ness of a restaurant? I'm planning on an Arduino project for a restaurant I work at that would require determining how busy it is at any point in time, but I'm not sure how I would go about procuring this information.

I don't have access to any of their IT systems or I would have simply pulled the data from their till systems.

I was thinking perhaps measuring the ambient sound of the restaurant as it gets quite loud during peak time but that could be thrown off when the music volume is adjusted.

There are a few ways to  go about it but my initial thoughts would be to detect people entering (and exciting) the front door and simply keep a running total.

Motion detector
http://www.adafruit.com/products/189

IR beam detectors
http://arduino-info.wikispaces.com/InfraredBeamPair


Sparkfun OpenLog both lights flashing I'm building a simple RS232 data logger with the Sparkfun OpenLog and a SEEED RS232-TTL adaptor. I'm powering it with a 9 volt battery and a 7805 voltage regulator.

It's dead simple. I built it on a breadboard first and determined that TX-TX and RX-RX connections are called for. I logged several files on the breadboard then soldered it all up. Now it's not working, sigh.

When I power it up  both lights will flash rapidly for about a second and then it settles down to a steady on-off with both lights.

If I delete the config file a new one is created, which shows that it recognizes the card at least.

I've triple checked my wiring and confirmed I have no shorts, and that the voltage is good.

I'm attaching a photo as built. Hopefully it's obvious what's what. The purple trace is ground.

The problem with the circuit was a bad rs232-ttl converter. Not sure how that messed up the openlog, but replacing it fixed the problem.

In the photo above, D1 on the converter is an led which should be normally on.


Calculation error with Optical Encoder I have corrected my code for reading the optical encoder index but I am now getting a different calculation error.  At the index the encoder reset's to zero but now my readouts are as follows:
Index point - resets to zero.
- At the 90 degree rotation mark I have a readout of 180 degrees.
- At the 180 degree rotation mark I have a readout of 0 because the code has it reset to zero after 359 degrees.
- At the 270 degree rotation mark I have a readout of 180 degrees.
- At the 0 degree mark it is zero again and that's what I would expect from the index.  If I restart the Arduino Mega at the 270 degree mark, the index resets itself to zero like it should.  Being new to this, before I had the index working it was working correctly minus the index function, now it seems to be double counting.  Any ideas?

// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT);
  digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINB, INPUT);
  digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINI, INPUT);
  digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

  // interrupts
  attachInterrupt(3, onInterrupt, CHANGE);  // encoder track A on interrupt 3 - pin 20
  attachInterrupt(4, onReset, CHANGE);  // encoder Index track on interrupt 4 - pin 19

  // enable diagnostic output
  Serial.begin (115200);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
  {
  encoder0Position = INTFLAG1;
  }
}

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }
}

I have figured out my issue, at least I am getting good results. With this code I had to change interrupts from CHANGE to RISING. I want to thank everyone that has made comments on this question. –


Assigning array variables to int variables I need to control thousands of rgb leds.To make animations I want to assign led numbers(addressable led strip) to arrays.For example floor[2]room[14]=106 106 is the number of led,there are many floors and rooms.I want to change floor or room numbers with that way I will make animations.
  We can say its 92x30 pixel monitor.I tried to create list of floor and rooms but I couldnt make it.
  I'm new to programming,help please!

Solved with this way #define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

You really don't need to maintain a list.

Just calculate the LED index from the location:

int room = 14;
int floor = 2;

const int rooms = 92;

int led = room + (floor * rooms);

That is, each floor below the current one (floors and rooms count from 0) is a full row of rooms (92 * floors), and there are "room" extra rooms on this floor to add to it.

You could make a macro:

#define LEDNO(FLOOR, ROOM) ((ROOM) + (FLOOR * 92))

Then your LED number is just:

int led = LEDNO(2, 14);

Here's an example taken from your code:

void floorsup(){

  FastLED.setBrightness(brightness);

  for(int a=1;a<255;a+=40){
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds2[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
    for (int floor = 0; floor < 30; floor++) {
      for (int room = 0; room < 92; room++) {
        leds3[LEDNO(floor, room)].setHSV(a, 255, 255);
      }
      FastLED.show();
      delay(300);
    }
  }
}


Linking Mulitiple Arduino's I have a project in which several Arduinos will be running independent programs. I would like to use an Arduino Mega as the main controller. It will receive input from a variety of switches, as well as data input from 2 Arduino Unos and 3 Arduino Nanos.

Each Nano will run a basic collection of switches and LED displays.

Each Arduino Uno will be connected to a 2 axis joystick and will have several button inputs from the joystick, as well as several 7 segment Led displays and several LED indicator displays.

The Mega would need to gather information of at least 16 bytes from each slave at highest possible speed, and be able to transfer at least 16 bytes to each slave at the same rate. I would also need the clock signal for all devices to default to the Mega.

What would be the best way to begin setting up the program logic to get these boards to interact in a smooth manner without a lot of lag in communication between boards?

Also, what would be the limitations on speed with this sort of com setup between the boards?

If more setup or function information is needed I can add description, just didn't want this post to be overly lengthy.

Why do you need so many Arduinos, Nanos and a Mega?  You want to read/control 2 joysticks, some switches and some LED.  If you do this using a multi-processor environment then you are adding a significant overhead to the processing and the development time which you can probably do without.

So, could you connect everything to a Mega, do you have enough IO pins?  If not would the use of GPIO expander ICs, I2C devices, etc help solve this issue.

Connecting the joysticks via interrupts will allow a more responsive system, can you do this?

Is an Arduino even the best platform for this?  What about an ESP32 or PI?

You want to minimise the comms overhead, so a star network would be better than a ring.
Serial is going to be the lowest programming overhead solution, but by far the slowest.  Using WIFI via an ESP8266 is going to be the simpelist and you can hand off some of the processing to the ESP.


Is there a limit on how much current a pin can sink? I've been experimenting with an 8x8 LED matrix controlled by an Arduino Uno. As I think is typical, the matrix uses a common anode for each row, and a common cathode for each column.

At the moment, I've got all the matrix pins connected directly to IO pins on the Uno, and I haven't had any problems lighting the LEDs one-by-one. Going through the whole matrix like this makes updates a little slow though, meaning the LEDs aren't as bright as I'd like.

As far as I know, I can't safely light up an entire row at once, because an individual pin on the Uno isn't capable of sourcing enough current to drive 8 separate LEDs at the same time (requiring at least 10mA each to be bright enough).

It occurred to me that the reverse might be safer. If I light up an entire column at a time, then each pin only has to source enough current for one LED, which should be no problem. However, it relies on one pin potentially sinking the current from all 8, totalling at least 80mA.

Is this possible, or am I going to fry my board?

am I going to fry my board?

Pretty likely outcome. Here's why:

The Arduino Uno uses the atMEGA328 microcontroller, which has an absolute maximum rating of 40 mA source or sink per GPIO. Also, the total current through the supply or ground rails (i.e. the total of all current OP wants the GPIO pins to sink, or source) is rated to a maximum of 150 200 mA.

Realistically, the current graphs in the atMEGA328 datasheet do not even go all the way to 40 mA, hence it is safest to restrict the current to perhaps 20 mA total per GPIO.

In other words, whether a GPIO is used as source or sink, the limits remain pretty low, and in practice, should be kept much lower than the absolute maximum ratings. Even below absolute maximum, running a microcontroller to too high a temperature reduces its life expectancy.

Solution:

Use either BJTs, MOSFETs, or some driver IC such as the ULN2003 to actually drive the current through the LEDs.


Why does Arduino use USB A-B plug, instead of A to micro USB plug? I understand that A-B plug used to be common but they could have switched to micro without issues.

My questions:

Why does Arduino use USB A-B plug, instead of A to micro USB plug?
What are the challenged Arduino would be facing if they switched to micro USB?

Note:
By "Arduino" I'm referring to Arduino models that do not come with a micro USB port such as the most common Uno & Mega.

Please note that this answer is based on speculation and some common sense rather than on insider information:

If you take look at the hardware index, you'll notice that significant parts of the layout (drill holes, pin spacing, and position and type of the USB jack) haven't changed between the Arduino Extreme and the current Arduino UNO R3), while other improvements have been made. For changes between the UNO R2 and R3, please see Arduino UNO FAQ at adafruit (link provided by jfpoilpret).

It is thus reasonable to me that keeping the USB jack was a deliberate design decision: Improve if possible, but keep the layout changes to a minimum and allow for maximum backwards compaptibility.

But again, this is just the guess of a user!


How to upload a sketch to an atmega328 via FTDI FT232RL UART and Arduino IDE? I have a sparkfun AVR Pocket Programmer and have burned the bootloader and uploaded programs using "upload using programmer" via USBtinyISP. It works fantastic.
I have a sparkfun FTDI Basic (as well as another FTDI breakout) that can send and receive bytes via the Arduino IDE serial monitor.
However, I cannot upload a new sketch or modified sketch to the atmega328 via FTDI. The IDE just hangs at the upload till timeout. Here is the list of some of my troubleshooting attempts:

I have tried uploading a plain bootloader, as well as a running program via the ISP programmer before attempting the FTDI.
I have tried direct connecting the FTDI DTR/RTS reset to the Atmega328 pin1.
I have also tried connecting the FTDI DTR/RTS reset to a one side of a 0.1uF cap, and the other side of the cap to the Atmega328 pin1. I assume the cap is to send just a reset pulse instead of a reset constant.
I have tried a different brand of FTDI FT232RL chip. No difference.
I have tried adding 1k resistors on the Tx and Rx lines. No difference.

Being able to program over serial is really the secret sauce that makes Arduino so much easier for beginners than a stock AVR chip. However, I have not been able to locate any detailed information on how this Arduino programming via serial really works. Also, I am not sure how the reset pin works in relation to this process. I remember something that on old Arduino boards you had to press or hold the reset when uploading, but have not be able to find any of this information either as it has been buried by time.
This Building an Arduino on a Breadboard Article and photo from that article below is a good outline of the setup I have right now. But in this configuration it seems that a sketch can not be uploaded. What do I need to add breadboard circuit in order to upload a sketch via serial? Or what procedure do I need to do with the reset button when uploading?

Thanks!
Atmega328 Spec Sheet PDF

Answering my own question; I just got lost in the troubleshooting.

Though I tested it both ways, I evidently overlapped issues, masking the core problem. Upload using programmer works great for transferring your sketch but it does NOT allow sketches to be uploaded via serial later. (Not sure if there is an inherent or logical reason for this, but this is what I have found by experimentation).
And like hcheung mentioned in the comments, a capacitor on the FTDI reset line is required. Connecting it directly will NOT work. I used a 0.1uF and it worked well. I have attached a couple different photos of my setup for someone following this path in the future. Note that the LED I am using has an internal resistor; a normal LED will need an 1k series resistor. Also, leaving the ISP programmer attached while uploading a sketch over serial did not seem to cause any issues.


ESP32S v1.1 NodeMcu vs ESP32 DevKitV1 I have two different ESP32 development boards labelled "ESP32S v1.1 NODEMCU" (A) and "ESP32 DEVKITV1" (B).  From what I can tell they have the same major components, but their pins and general layout are quite different. I assume they are both knock-offs.

When uploading from the Arduino IDE, both read the same revision number and features:
Chip is ESP32-D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz

From what I can tell NodeMcu has something to do with the firmware for the ESP8266 (wiki)?  Also, it seems my ESP32S NodeMcu board doesn't have the standard pin layout for ESP32 boards.
What exactly is this NodeMcu board and what are the differences between the two?

The DevKit is a development board by ESP32 manufacturer Espressif to demonstrate ESP32 usage and to support prototyping.
The NodeMcu is a board by NodeMcu intended for the NodeMcu Lua language firmware.
There is no standard pinout. The labels on the DevKit are io pin numbers of the MCU.
You can use both development boards with the ESP32 "Arduino boards support package".


Reliably reloading the calibration data of IMU BNO055 I am using the BNO055 IMU and the Adafruit Library.
I want to store the calibration data and load them after the microcontroller is powered off and repowered on.
The Adafruit Library provides an example for storing and restoring but, in actual facts, it does not work. It is always required to recalibrate the magnetometers, but even doing so, the library reperform the whole calibration including the accelerometers.

I would like to simply restore all the calibration data (including the magnetometers) so that no calibration needs to be performed when the IMU starts.

I have read a massive amount of posts on the argument, but I really could not figure out how to reliably load all the calibration data at boot and avoid recalibrating them.

Is there anyone who succeeded and can please share the code?

I found the solution. It is enough to add a function that when reperfoming the calibration of the magnetometer, checks ONLY if the magnetometer is calibrated (while the calibration for the accelerometer and gyroscope is reloaded from the EEPROM).

void performMagCal(void) {
  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;

  while (mag != 3) {

    bno.getCalibration(&system, &gyro, &accel, &mag);
    displayCalStatus();
    Serial.println("");
  }

  Serial.println("\nMagnetometer calibrated!");
}


Using ethernet, how do I navigate to a page on my local server I want to access the following page on my local using my Arduino with ethernet shield"  192.168.1.2/zombie/arduino.php.  My arduino is conencted to a PC through a router. The system keeps timing out

I am using the following code:

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
char server[] = "192.168.1.2/zombie/arduino.php";

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

I discovered the answer after some testing.

The server var:

char server[] = "192.168.1.2/zombie/arduino.php";

should only contain the ip address.  So it should look like this:

byte server[] = { 192,168,1,2 };

The additional URL elements should be added using:

client.println("GET /zombie/arduino.php");

after a connection has been established

The final code should look like this:

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

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,3 };
byte server[] = { 192,168,1,2 };

EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(9600);

  delay(1000);

  Serial.println("connecting...");

  int res = client.connect(server, 80);

  Serial.println(res);

  if (res) {
    Serial.println("connected");
    client.println("GET /zombie/arduino.php");
    client.println();
  } else {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.println("data:");
    Serial.println(c);
  }else{
    Serial.println("NA");
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}


arduino flexbot drone connected in a wrong way I have an arduino flexbot, I was making some test and accidentally I connected the battery in the opposite way. The drone turned on the six motors when I connected the battery, but any led turned on to see if the processor was working. I disconnected the battery and connected it in the wrong way again same thing happened the six motors turned on again. Then I realize that the battery was connected in a wrong way and connected it in the right way. The LED's turned on as always, and also the blue-tooth module was working I could detect the device using the control-application. I tried to fly the drone but the motors didn't turn on, I could hear little click and I saw a little movement of a motor.

I connected my drone to my PC using the micro USB connection, also I connected the battery. I tried to turn on the drone and in this way it looks to work fine.

But when I disconnect the USB port and I tried to fly it the same thing happens, the click and the little movement. Any idea of what can I do to fix this drone?

The motors turning on is expected because or the reverse diode in the mosfets driving the motor.

Looking at the schematic, it seems like the problem is on the 5v rail. If 5v isn't supplied by the USB port, it is provided by the LTC3200 (DC/DC converter)(U3 on the pcb). I think that's where the problem is, as that would explain why it only work when USB is connected.

To confirm this you'd have to measure the output voltage (pin1 (pin nearest to the ATMega) of U3, and see if it's 5 volt.

To fix it you should ideally replace this part. But it might also work without, if you simply connect the battery voltage directly to the 5v (i.e. jumper pins 1 and 5).


Code doesn't seem to work when trying to program 2 sensors Can anyone help me with this issue

I'm trying to program two FSR sensors through typing this code but I've realized that one is working instead of two.

The logic behind the code is that if you were to squeeze both sensors at the same time it will print out an output on the serial monitor acknowledging that both sensors have been squeezed. I have got only one to work by using this code.

The first sensor is connected to the A0 pin on the arduino and the second sensor is connected to the A1 pin

This is the code that I've written

/* FSR simple testing sketch.

 Connect one end of FSR to power, the other end to Analog 0.
 Then connect one end of a 10K resistor from Analog 0 to ground
 For more information see www.ladyada.net/learn/sensors/fsr.html */

int fsrPin = 0;
int fsr2Pin = 1;   // the FSR and 10K pulldown are connected to a1
int fsrReading ;
int fsr2Reading;   // the analog reading from the FSR resistor divider

void setup(void) {
    // We'll send debugging information via the Serial monitor
    Serial.begin(9600);
}

void loop(void) {
    fsrReading = analogRead(fsrPin);
    fsr2Reading = analogRead(fsr2Pin);

    Serial.print("Analog reading = ");
    Serial.print(fsrReading);
    Serial.print("\t");
    Serial.print(fsr2Reading);

    // We'll have a few threshholds, qualitatively determined
    if (fsrReading < 10) {
        Serial.println(" - Nothing");
    } else if (fsrReading < 200) {
        Serial.println(" - Light");
    } else if (fsrReading < 500) {
        Serial.println(" - Lightness");
    } else if (fsrReading < 800) {
        Serial.println(" - Medium");
    } else if (fsr2Reading < 1100) {
        Serial.println(" - No-Pressure");
    } else if (fsr2Reading < 1400) {
        Serial.println(" - Light-touch");
    } else if (fsr2Reading < 1700) {
        Serial.println(" - Light-squeeze");
    } else if (fsr2Reading < 2000) {
        Serial.println(" - Medium-squeeze");
    } else {
        Serial.println(" - Big-squeeze");
    }
    delay(1000);
}

So could anyone tell how to edit this code correctly in order to get two sensors to work?

The one connected to the A0 pin is working but not the other

As JFPoilpret says you if logic is wrong.
It might make it easier if you took that whole if block out and made it into a function that accepted the value from the sensor as a parameter.

void CheckReading(int reading)
{
    if (reading < 10) {
        Serial.println(" - Nothing");
    } else if (reading < 200) {
        Serial.println(" - Light");
    } else if (reading < 500) {
        Serial.println(" - Lightness");
    } else if (reading < 800) {
        Serial.println(" - Medium");
    } else {
        Serial.println(" - Big-squeeze");
    }
}

Notice that the values only go up to 800, going larger than 1023 won't work anyway.


connecting RTC DS1307 to ethernet shield What is the easiest way to mount DS1307 to ethernet shield?

I tried to do this:
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up

but my program just freezes when I try to read data from RTC. Is there any other ways to do it?

Code looks like this:

const int RTCpin2 = 2;
const int RTCpin3 = 3;

void setup() {
    pinMode(RTCpin2, OUTPUT);
    pinMode(RTCpin3, OUTPUT);

    analogWrite(RTCpin2, LOW);
    analogWrite(RTCpin3, HIGH);
}

void loop() {
     // process RTC time
}

I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module.  Well, there's two fundamental flaws with it:

Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.
analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.

So to fix it:

Use pins A2 and A3 instead of 2 and 3
Use digitalWrite() instead of analogWrite().


Arduino Uno Motor control using 2 Relays, 2 Limit switches and Bluetooth. Forward Reverse Stop Modified existing project from this link:  Problem : Trigger limit switch to stop DC motor

I modified this code to control two relays which are wired to motor poles for Forward or Reverse movements until they physically reach a limit switch on either side.

Serial input of 'A' turns on one relay. If Limitswitch1 is pressed, this relay switches off.
It detects the current state of the system and awaits the Serial input of 'B' which then turns on the second relay. If Limitswitch2 is pressed, this relay switches off.

The issues are:

Please help with code - I require option where the two relays switch off on the serial input of letter 'S' and to add the corresponding state machine. Essentially to add a Stop function.
The limit switches work intermittently, sometimes they respond flawlessly, sometimes not at all. I have bought three different brands of switches to test but all have the same behaviour. I have pulled switches up and down with resistors in vain. I have performed button count test using code from this forum and confirm that the switch also behaves erratically. Can changes to code improve switch feedback?

Suggestions will be greatly appreciated.

const byte RELAY1 = 2;
const byte RELAY2 = 3;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;

const byte State_Idle = 0;
const byte State_Forward = 1;
const byte State_Reverse = 2;
byte currentState;

void setup(){
pinMode(RELAY1,OUTPUT);
pinMode(RELAY2,OUTPUT);

pinMode(LimitSwitch1, INPUT);
pinMode(LimitSwitch2, INPUT);

Serial.begin(9600);
currentState = 0xFF; // Force a change to enter the idle state
 }

void loop(){
// Check if we need to change state
byte nextState = currentState;
switch (currentState)
{
case State_Idle:
    { // If we received a valid command, start the operation
        if(Serial.available() > 0)
        {
            switch (Serial.read())
            {
            case 'A':
                nextState = State_Forward;
                break;
            case 'B':
                nextState = State_Reverse;
                break;
            default:
                break;
            }
        }
    }
    break;
case State_Forward:
    if(digitalRead(LimitSwitch2))
        nextState = State_Idle;
    break;
case State_Reverse:
    if(digitalRead(LimitSwitch1))
        nextState = State_Idle;
    break;
default:
    nextState = State_Idle;
    break;
}

// If there was a change, switch state and trigger enter condition
if (nextState != currentState)
{
    currentState = nextState; // Move in the new state
    switch (currentState)
    { // Entering the new state
    case State_Idle:
        // Switch both Relays OFF
        digitalWrite(RELAY1, HIGH);
        digitalWrite(RELAY2, HIGH);
        break;
    case State_Forward:
        // Move Forward
        digitalWrite(RELAY1, LOW);
        digitalWrite(RELAY2, HIGH);
        break;
    case State_Reverse:
        // Move Reverse
        digitalWrite(RELAY1, HIGH);
        digitalWrite(RELAY2, LOW);
        break;
    }
}
}

Here I am again for another exciting episode of "Fun with StateMachines".. ;)

Ok, basically you modified the code well, but you thought of the modification in the wrong way.

First of all describe what you want to do in simple words. Let's say you want that

  When I'm moving in one direction and I receive the letter 'S', I immediately stop without waiting for the endstop

Consequently, you know that

you will have to add something when you are moving in one direction
this "something" will top you, which is what the endstop does

So, to implement this, you can do something like this:

switch (currentState)
{
case State_Idle:
    { // If we received a valid command, start the operation
        if(Serial.available() > 0)
        {
            switch (Serial.read())
            {
            case 'A':
                nextState = State_Forward;
                break;
            case 'B':
                nextState = State_Reverse;
                break;
            default:
                break;
            }
        }
    }
    break;
case State_Forward:
    if(digitalRead(LimitSwitch2))
        nextState = State_Idle;
    else  if((Serial.available() > 0) && (Serial.read() == 'S'))
        nextState = State_Idle;
    break;
case State_Reverse:
    if(digitalRead(LimitSwitch1))
        nextState = State_Idle;
    else  if((Serial.available() > 0) && (Serial.read() == 'S'))
        nextState = State_Idle;
    break;
default:
    nextState = State_Idle;
    break;
}

Now, your second problem is a bit harder to understand. When I read it, I immediately thought what chrisl already pointed out, which is switch bounces. But when I was halfway into completing this part of the answer I found out that.. no, the bounces are not what can give problems here, unless you are constantly writing 'A' or 'B' on the serial. So for the second part of the question please post your schematic and/or photos of the setup, so we can see if there is something not normal


Common Wire sizes for connecting peripherals to arduino Please don't judge me for asking this question i have never touch arduino before but We plan to use it in our thesis we are doing a budget plan and it must include wires. can anyone tell me the common wire sizes used? This is to estimate the prices.

Depends what you’re doing.

For low power (< 12v, 500mA) peripherals and digital signals:

If you’re going to use breadboard (and you really should start with breadboard) you’ll need solid core hook up wire. You can find pre-cut, pre-stripped sets with a variety of lengths and colours if you’re looking for neatness and simplicity.
(An example can be found at: http://www.maplin.co.uk/p/jump-wire-kit-fs65v)
Usually it’s 22AWG wire, so you could get a reel and cut it yourself if you’re going to need a lot or are going to solder it in place.

After you’re done breadboarding and want to make something more permanent you should look at rainbow cable. You can tear it to get anything from 2 to 32 way cables, and it’s almost impossible to get the wrong way around. You can solder it directly to a PCB or crimp connectors onto the ends for more flexibility.
(You can find this stuff everywhere, but Sparkfun is always there if you can’t: https://www.sparkfun.com/products/10649)

For higher power (> 12v, 1A):

Keep it away from the Arduino! Use switching transistors, relays, or MOSFETs and use cabling that meets, or preferably exceeds, the power that you’re going to put through it.

I don’t know where you’re going to buy this, but in the UK I use Mouser, Farnell, and RS for most of my electronics supplies. Never buy cabling off Ebay, a lot of it is counterfeit and won’t meet the claimed spec.

Hope this helps.


If statement comparing array to value list throws error In my program I have the following lines of code:

if (invest == {0, 1, 0, 0})
   {
      //code
   }

However, upon attempting to compile the code, I receive the following error:

exit status 1
expected ';' before '}' token

"Invest" is a bool array originally defined with`

bool invest[] = {0, 0, 0, 0};

How can I prevent this error from ocurring?

You cannot compare like that... you have to do it one by one (and check the length of the array).

if ((sizeof(invest) / sizeof(bool) == 4) &&
    (invest[0] == 0) &&
    (invest[1] == 1) &&
    (invest[2] == 0) &&
    (invest[3] == 0))
{
     ...
}

If you need to do such a compare often (with possibly different values), you of course can always write a dedicated function passing the array, and the array to check against and check the length and use a loop for checking all values.

Note that if invest is a boolean array, it's best to use false and true instead 0 and 1.


DS1307 Real-Time Clock I am trying to make an Arduino project based on the Sparkfun DS1307 RTC (real-time clock).

There are a few issues with how Arduino libraries don't support checking if the Arduino board has been powered down and check for that.

Then using that as a conditional as to when the program should fall back to the compiled time if the RTC isn't set to a time yet because of something else.

When I power down the clock, it will automatic fall back to the compiled time every single time, regardless of what is currently on the RTC. Clearly this is not something you would want.

Edited - This is my current code. Keep in mind there are a few more changes I could do like take Byte zero declare out of the loop so it is still rough.

#include <Wire.h>
#include <SparkFunDS1307RTC.h>

#define DS1307_ADDRESS 0x68

void setup() {
  Wire.begin();
  Serial.begin(9600);
  rtc.begin();
  if(false){
    //Should check RTC somehow to determine if should fallback to compiled time here.
    Serial.println("The DS1307 clock has lost power and reset to compiler's time");
    rtc.autoTime();
  }
}

void loop() {
  if(digitalRead(7)==LOW)
    printDate();
  delay(1000);
}

byte bcdToDec(byte val){
  return ((val/16*10) + (val%16));
}

void printDate(){
  rtc.update();
  Wire.beginTransmission(DS1307_ADDRESS);
  byte zero = 0x00;
  Wire.write(zero);
  Wire.endTransmission();
  Wire.requestFrom(DS1307_ADDRESS, 7);
  int second = bcdToDec(Wire.read());
  int minute = bcdToDec(Wire.read());
  int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
  int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday
  int monthDay = bcdToDec(Wire.read());
  int month = bcdToDec(Wire.read());
  int year = bcdToDec(Wire.read());
  //Print the date like 3/1/1/11 23:59:59
  Serial.print(month);
  Serial.print("/");
  Serial.print(monthDay);
  Serial.print("/");
  Serial.print(year);
  Serial.print(" ");
  Serial.print(hour);
  Serial.print(":");
  Serial.print(minute);
  Serial.print(":");
  Serial.println(second);
}

Easy. Here is one way to do it.

Read the clock off the rtc.
Wait a known period of time, based on the mcu frequency,
Read the clock off the rtc again.
Compare the two time reading and it should have advanced. If not, fall back to compiled time.

There are other ways to do it as well, like bor, or square wave output, interrupt on vbat line, ......