Class member variable would not update Code would not update variable inside drive method. The variable is updated inside the drive method, but it doesn't change in the rest of the class. I wrote a simple similar method in normal C++ and the variable actually updated in the rest of the class.

engine.hpp

#pragma once
#include <Arduino.h>

namespace engine
{
class Engine
{
public:
    Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward);
    void drive(unsigned int t_speed, bool t_isForward = true);
    bool isMovingForward() const;
    void stop();

private:
    const unsigned char m_motor;
    const unsigned char m_forward;
    const unsigned char m_backward;

    // Movements
    bool m_isActive;
    bool m_isForward;
    unsigned int m_speed;
};
} // namespace engine

engine.cpp init list

Engine::Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward)
    : m_motor(t_motor),
      m_forward(t_forward),
      m_backward(t_backward),
      m_isActive(false),
      m_isForward(true),
      m_speed(0U)
{
}

drive method

void Engine::drive(unsigned int t_speed, bool t_isForward)
{

    if (!m_isActive || m_isForward != t_isForward)
    {
        stop();

        // Set direction
        if (t_isForward)
        {
            digitalWrite(m_forward, HIGH);
            digitalWrite(m_backward, LOW);
        }
        else
        {
            digitalWrite(m_forward, LOW);
            digitalWrite(m_backward, HIGH);
        }

        m_isActive = true;
        m_isForward = t_isForward;
    }

    if (m_speed != t_speed)
    {
        m_speed = t_speed; // Updated here
        analogWrite(m_motor, t_speed);
    }
}

I figured it out.

I was passing the engine objects as references instead of pointers.

main.cpp

// Engines
engine::Engine
    engine1(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    engine2(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    engine3(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    engine4(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);

engine_controller.cpp init list

EngineController::EngineController(engine::Engine &t_e1, engine::Engine &t_e2, engine::Engine &t_e3, engine::Engine &t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}

The solution would be to use dynamic memory allocation.

main.cpp

// Engines
engine::Engine
    *engine1 = new engine::Engine(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    *engine2 = new engine::Engine(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    *engine3 = new engine::Engine(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    *engine4 = new engine::Engine(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);

engine_controller.cpp init list

EngineController::EngineController(
    engine::Engine *t_e1, engine::Engine *t_e2,
    engine::Engine *t_e3, engine::Engine *t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}


is there a timeout for Ethernet.begin? I'm working on a project, but just for testing, I haven't connected it to the internet yet, even though the code SHOULD be ready to roll out.

When trying to test some of my code with the serial console, I realized my program was locking up and I traced it down to here. Now my arduino uno and ethernet shield isn't currently connected to the internet, so my question is, how could I timeout this function so that I can keep my program running when there's no internet to connect it too.

Here's my code in the setup function

if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip);
  }

If anyone has any thoughts or suggestions, I'd definitely appreciate it.

The default timeout is 1 minute for DHCP. There is also a response timeout, and in the library millis is used for timeouts. I don't know if there is a timeout for everything, but I suppose there is.

If it stops working when no ethernet cable is connected, that would be a bug. If something like that is in the library, then you have no way to bypass the Ethernet.begin when it took too long. How long did you wait ?

This is the source code for Ethernet.begin: Ethernet.cpp


End stops for stepper motor I need to add some end stops to this stepper motor code. I'm using one axis of a joystick to control a carriage that goes back and forth on a long screw. I have hall switches for both ends, I just want it to stop going in that direction when it triggers the switch.
I didn't write this code but it would work great if I could just add the end stops. If I have the switches connected to pins 2 and 3.
How could I write something like: if pin 2 goes high, stop motor in that direction, and then the same for pin 3 in the opposite direction?
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop() {
  ReadAnalog();
  stepper.runSpeed(); // step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}

This is what I came up with. Note that the ReadLimits function is called after ReadAnalog and before runSpeed. In that order the stepper will not move in the direction of the limit switch, if it is pressed.
PS since you used setAcceleration, don't you need to call run instead of runSpeed?
void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }
}

edit to avoid some confusion; here is the entire code with my suggestion embedded:
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}


Adafruit_LSM303 tilt compensated compass I am having troubles with tilt compensating my compass.

I am using the LSM303DLHC accelerometer/compass in combination together with the Adafruit_LSM303_U.h.

I was able to get my compass to the right direction withthis little snippet:

  float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;

I also was able to get my roll and tilt angle with converting my X and Y of my accelerometer to angles:

   headingNew = asin(eventA.acceleration.x/10);
   float tilt = headingNew*180/PI/90*100;
   headingNew = asin(eventA.acceleration.y/10);
   float roll = headingNew*180/PI/90*100;

Now I need to compensate my angle to get a new x and y for inside my heading calculation but the problem is that I can't seem to get the right functions.
Online I found the functions below from a large tutorial about the sensor but this gives me completely wrong values.

    //Xh = event.magnetic.x*cos(tilt)+event.magnetic.z*sin(tilt);
    //Yh = event.magnetic.x*sin(roll)*sin(tilt)+event.magnetic.y*cos(roll)-event.magnetic.z*sin(roll)*cos(tilt);

or in the code itself:

   Xh = event.magnetic.x*(eventA.acceleration.z/10)+event.magnetic.z*(eventA.acceleration.x/10);
   Yh = event.magnetic.x*(eventA.acceleration.y/10)*(eventA.acceleration.x/10)+event.magnetic.y*(eventA.acceleration.z/10)-event.magnetic.z*(eventA.acceleration.y/10)*(eventA.acceleration.z/10);

I actually get the right angle on a flat surface. But it is even more inaccurate at an angle as the normal heading.
Does anybody have any experience with this sensor? Already a big thanks for the help.

The sin() and cos() functions expect their arguments to be in
radians. If you feed them with anything else, be it degrees, percent
slope, or whatever, expect the result to be just crap.

Edit: The OP changed the question, invalidating my answer. So here
comes a new answer...

You have mistaken eventA.acceleration.y for cos(tilt),
eventA.acceleration.x for sin(tilt), and so on. They are not the
same. You may think they are the same up to some multiplicative factor,
and that's right. However, the factor doesn't cancel out as soon as you
do computations like sin(roll)*sin(tilt). Don't rush your math: if you
want to transform known-good formulas to more practical ones, check every
step of the transformation carefully.


Broadcasting parallel data from Arduino using router I'm looking to read data from sensors using an ArduinoUNO in a greenhouse and then access the data wirelessly through a router. Hopefully through a webpage. No need for internet access, just local network access is good enough.

Preferably the only components involved would be the Arduino, the circuit, and a router with OpenWRT/DD-WRT to host the webpage and broadcast the network.

Pretty new to Arduinos in general, would this be possible? And how? The following 2 links from instructables.com seem to be the most relevant, can anyone give their input on how similar/different is this to my project?

http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/

http://www.instructables.com/id/Getting-Arduino-data-to-a-web-Page/

Use a NodeMCU (ESP8266 based) because it have WiFi included. It can work as a light web server. You can serve HTML, but not large files (like many .js).

Instead of HTML you can use websockets to get only data from NodeMCU and all the other files (html, js, images) from another bigger server. Websockets is fast, but you still have to deal with .html, .css, .js and other files in your webserver.

If you want something even easier and lighter, take a look at MQTT, which was developed with IoT in mind.

There is lot of MQTT client for Android/Iphone/PC/Mac. You use your client to send data and commands to your NodeMCU. No need to program anything here; you simply construct a visual interface by adding controls (buttons, meters) to a blank slate. No brains job.

You will need a broker, a server that acts as a relay, receiving commands/data from your Android and resending it to your NodeMCU. And your NodeMCU can publish temp, humidity, light levels and other data to your broker. You can use multiple client at once. There is no limit.

Your broker can be an public Internet broker (many) or a private one in your LAN. There is many brokers available for different platforms. You can run one in your smartphone or any old PC. Mosquitto is a free one.

Depending on your configuration, you will be even able to access your green house from Internet and look at your girls from far away.


Receiver xbee receiving data while the Transmitter is powered off? My receiver xbee is receiving data even if the transmitter is disconnected , so if i am sending the string hello world , the receiver will repeat this string .

void loop() {
    Serial.println("Hello");
    delay(1000);
}

void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

As @Garben mentioned, we do not know what is your question, problem or whatever...
Provide some more information about wiring. I looked at your question 5 mins and still can't get what is wrong...

What are you doing here??? Sending from Arduino+XBEE to another Arduino+XBEE???

void loop() {
    Serial.println("Hello");
    delay(1000);
}

Here you are resending what you got

void loop() {
     if(Serial.available()>0){
         Serial.print((char)Serial.read());
     }
}

So what is your problem? Or is this all your code???
Arduino has to have

void setup(){
//Set up your Arduino here
}
void loop(){
//Code here will run over and over and over...
}


Why is my transistor switched output so low? Help needed! I am using an Arduino Nano and a general purpose npn (2n2222a) transistor to provide a 12v signal to a low current 12vdc load in an automobile. The Arudino code is set to pulse D2 at bootup/startup for .5 second. The PWM output setting was 255 (since switched to digitalWrite). However, the switched output measures only 4.5v (expected close to 12v). What am i doing wrong?
Applying 12v+ directly to the black box works. The purpose is to simulate a temporary button push in the car so an auto function is enabled.

The problem is that you are using an NPN transistor as a high side switch.
The voltage at the emitter of the transistor will always be about 0.7V below the voltage at the base.  The "high" output from the Arduino is 5V.  The emitter will be at about 4.3V.
Have a look at the Wikipedia "emitter follower" page.  The emitter follower is also called a common collector circuit. That explains the "problem" in more detail.  It is only a problem in so far as it is not the correct solution for your task.
You need to use a "common emitter" circuit.
This usage is commonly called a "low side switch."
That would look like this:

simulate this circuit – Schematic created using CircuitLab
If your black box really needs its input pulled up to 12V, then you would do something like this:

simulate this circuit
The resistor values and transistor part numbers are place holders.  The values of resistors you will need depends on the transistors you use.  The transistor selection will depend on how much current you need to deliver to the black box.
I see in a comment that your black box only needs a few milliamperes.  In that case, the shown transistors should work just fine.  The resistor values may be a little too high, but I think they'll be OK.

A couple of additional points:

The Arduino has PWM outputs, not PCM.
The output voltage for your black box will be pulsing if you use any PWM value lower than 255.  Your black box probably won't like that, and your voltmeter won't read a correct voltage.

You should use D2 as a digital output rather than PWM.  Just turn it on or off rather than fiddling with the PWM duty cycle.  Use "digitalWrite" instead of "analogWrite" on pin D2.


Generating a 38 KHz signal without timers I am currently trying to generate a 38 KHz signal for my TSOP4838 (http://www.vishay.com/docs/82459/tsop48.pdf) with an ATtiny84A.

I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.

I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).

So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (micros(), millis() etc.) stopped working and prevented me from using my serial communication. I tried to change the code in wiring.c to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.

I am now stuck with two options I guess:

A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.

B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.

I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?

If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()

A 38kHz square wave at 50% duty cycle would be a transition running at 38x2=76kHz.  That is 1/76,000 = 0.000013158s, or 13.158µs.  That's quite a high accuracy to try and achieve with delays on a small chip like the 84A.

I assume you are running it at 8Mhz (internal calibrated RC oscillator) - that means each clock tick is 1/8000000=125ns long. so 13156ns would equate to 105.248 clock cycles. That can't happen, so the closest you would get is 105 clock cycles, which would be 13125ns, or 76.190kHz, or an end frequency of 38.095kHz.  So fairly close.

So now you need to create a tight loop that is exactly 105 clock cycles long including the toggling of the IO pin and the comparisons and branches for the loop.  For that you need to do some careful instruction cycle counting and work in assembly language.  Page 268 of the data sheet details the clock cycles used for each instruction.

The simplest (though most long winded) loop would be an OUT or SBR (depending on port) instruction (1 clock) to set the IO pin HIGH, then 104 NOPs (1 clock each), then an OUT or CBR to set it LOW (1 clock), then 102 NOPs (1 clock each), then an RJMP to go back to the start (2 clocks).  That is then a grand total of 210 clock cycles, or 1/(210*0.000000125) = 38.095kHz.

You could compress all the NOP instructions down into a tight loop themselves by setting a register to a pre-defined loop count value, decrement it each pass - repeat if it's not 0. That means even more careful instruction counting to get that loop to equal the 104 or 102 clock cycles needed for the precise timing.

However all that is pretty much academic, because the loop will keep being interrupted by your timer 0 interrupt and cause jitter in your output as the interrupt routine is being run instead of your IO pin driving loop.

If you don't need absolutely reliable timing anyway it might be easier (though far less accurate) to use the micros() function to find when 13µs have elapsed and do it all in C instead of assembly.  You will still need high speed direct port access rather than using digitalWrite() since digitalWrite() adds way too much overhead to be able to do that kind of timing reliably.  Something like:

uint32_t start = micros();
while(1) {
    if (micros() - start >= 13) {
        start = micros();
        PORTB ^= 1<<4; // toggle B4
    }
}

Note the use of while (1) there rather than relying on the loop() function repeating itself.  There is quite a large overhead in using the auto-repeating of loop() that can be avoided by looping within it with a while (1) like that.  Of course, anything else you want to happen repeatedly would have to be inside that while loop, and most likely would impact your output timing somewhat.

So a much better solution would be to use a timer, since that is what they are there for.  But fidding with timers breaks things like millis() and delay().  So the answer to that is don't use millis() and delay().  Instead create your own timing functions that are controlled by your own interrupt that does the pin IO - instead of relying on a system provided tick you create your own.  If your interrupt is firing every 13µs then add 13 to a global counter - that counter is then the number of microseconds that have passed.  When that count exceeds 1000 you subtract 1000 (don't zero it) and add 1 to a millisecond counter.  Now you have the equivalent to millis() in a global (remember to make it volatile) variable that you can use instead of millis().


How to send two different sets of int numbers over serial? I have a project that require for the main computer to do most of the processing then for it to send the X and Y coordinates of this processing to the arduino. This at the time didn't seem very hard but now that I have started to dive into serial some more I am completely confused. All of the example I have seen for serial only consist of 1 set of numbers and rather confusing.

The Arduino code I kinda want to go like this
http://pastebin.com/aLJfEExw (I know this is probably completely wrong but I am pretty lost right now)

The Python code is this right now
http://pastebin.com/4aN4dnSC

If you guys could help explain this better for me it would be amazing. I understand that my code is probably wrong. So if you guys could provide an example of how to send the two different sets of int's it would be amazing. Because I am completely and utterly lost.

I looked at your code, but the main problem seems to be that you have not defined the problem, and it is thus not possible to definitively answer.

The conventional solution to this would be to send 2 numbers with separator (usually space) followed by a newline. I know Arduino does not have an inbuilt function to do this, but you could write one. http://arduino.cc/en/Tutorial/SerialEvent shows one way this could be done.

Another approach is to send bytes (how long is each number? I would guess 16 bits) so you would send 4 bytes and on reception assemble them into 2 16 bit integers. Whether you need to ensure the data is synchronised depends on your problem. If you are sending continuous data this is essential, and you could use the kind of compelled sequence signalling you seem to be implying.

From the code it looks like you are sending from a Raspberry Pi. If I were doing this I would probably use I²C (at least over a short distance).


Can't use two SPI devices at the same time I can use the MFRC522 using the following code:

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

MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

And it works great. I can also use the dot-matrix (8x8) using the following code:

#include "LedControl.h"

LedControl lc = LedControl(12,11,8,1);

void setup() {
    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
}

And it works just fine as well. However, when I try to use both of them using the following code:

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

LedControl lc = LedControl(12,11,8,1);
MFRC522 mfrc522(10, 9);

void setup() {
    SPI.begin();
    mfrc522.PCD_Init();

    lc.shutdown(0,false);
    lc.setIntensity(0,3);
    lc.clearDisplay(0);

    lc.setLed(0,2,5,true);
    lc.setLed(0,5,5,true);

    lc.setLed(0,2,2,true);
    lc.setLed(0,3,1,true);
    lc.setLed(0,4,1,true);
    lc.setLed(0,5,2,true);
}

void loop() {
    if (  mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial() ) {
         // Do stuff
    }
}

In that case only one of them works (the MFRC522). I know that since they are connected in SPI mode they need to have different SS pins, so I used pin 10 for MFRC522 and pin 8 for dot-matrix. So, what's wrong? Why dot-matrix doesn't work at the same code with MFRC522??

The LedControl doesn't use SPI library but it's using shiftOut internally. So you can't use them both at the same pins as the SPI interface takes over them.

Basically SPI.begin() takes over the control on its pins and that means when you use digitalWrite or pinMode on those pins, it'll be ignored (at least on some of them).

If you add SPI.begin() into the second example (LedControl one) it'll stop working. However you can change pins for LedControl to other (free) pins and it should be working again.

And also there are mixed signals between both devices:

HW SPI wiring:
13  CLK    output
12  MISO   input
11  MOSI   output
9   SS     output

and LedControl wiring is:
12  MOSI   output (not really)
11  CLK    output

Something from the datasheet about alternate pin functions:

  SCK/PCINT5 – Port B, Bit 5
  SCK: Master Clock output, Slave Clock input pin for SPI channel. When the SPI is enabled as a
  Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is
  enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit.
  PCINT5: Pin Change Interrupt source 5. The PB5 pin can serve as an external interrupt source.
  MISO/PCINT4 – Port B, Bit 4
  MISO: Master Data input, Slave Data output pin for SPI channel. When the SPI is enabled as a
  Master, this pin is configured as an input regardless of the setting of DDB4. When the SPI is
  enabled as a Slave, the data direction of this pin is controlled by DDB4. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit.
  PCINT4: Pin Change Interrupt source 4. The PB4 pin can serve as an external interrupt source.
  MOSI/OC2/PCINT3 – Port B, Bit 3
  MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI is enabled as a
  Slave, this pin is configured as an input regardless of the setting of DDB3. When the SPI is
  enabled as a Master, the data direction of this pin is controlled by DDB3. When the pin is forced
  by the SPI to be an input, the pull-up can still be controlled by the PORTB3 bit.
  OC2, Output Compare Match Output: The PB3 pin can serve as an external output for the
  Timer/Counter2 Compare Match. The PB3 pin has to be configured as an output (DDB3 set
  (one)) to serve this function. The OC2 pin is also the output pin for the PWM mode timer
  function.
  PCINT3: Pin Change Interrupt source 3. The PB3 pin can serve as an external interrupt source.
  SS/OC1B/PCINT2 – Port B, Bit 2
  SS: Slave Select input. When the SPI is enabled as a Slave, this pin is configured as an input
  regardless of the setting of DDB2. As a Slave, the SPI is activated when this pin is driven low.
  When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB2. When
  the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB2 bit.
  OC1B, Output Compare Match output: The PB2 pin can serve as an external output for the
  Timer/Counter1 Compare Match B. The PB2 pin has to be configured as an output (DDB2 set
  (one)) to serve this function. The OC1B pin is also the output pin for the PWM mode timer
  function.
  PCINT2: Pin Change Interrupt source 2. The PB2 pin can serve as an external interrupt source.


MPU6050 Measure distance traveled or position How can I use MPU-6050 with an arduino to measure the distance the robot traveled from it's starting point or just it's current position on the map?

The Robot should be moving in a map same as a 2D array and I need to detect it's position while it is moving and send the data to a station.

You won't - not with any degree of accuracy anyway.

You could attempt "dead reckoning" whereby you estimate the current speed by the acceleration and deceleration over time, and from that get a rough idea about the distance travelled in any one direction, but the accuracy will be so poor and the drift so huge that it would be next to pointless.

Instead you really want to monitor the wheels. Count how many revolutions (or half revolutions, quarter revolutions, whatever accuracy you need) and combine that with the circumference of the wheels to calculate how far you have travelled.


Problem using 2 motors I would like both the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning. At the moment, when I push the joystick on x-axis and my x variable increases both motors spin, but when I push it in the opposite direction and x decreases, only motor A spins. Additionaly when I connect the arduino to the power (usb cable to my pc), motor B spins for approx 1 second and then stops.
This is the circuit I have (sorry for a lack of schematic, let's hope this wonderful drawing is enough):

The code:
int MotorAA = 7;
int MotorAB = 8;

int MotorBA = 11;
int MotorBB = 12;

int x = 0;

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

  pinMode(MotorAA, OUTPUT);
  pinMode(MotorAB, OUTPUT);

  pinMode(MotorBA, OUTPUT);
  pinMode(MotorBB, OUTPUT);

  digitalWrite(MotorAA, LOW);
  digitalWrite(MotorAB, LOW);

  digitalWrite(MotorBA, LOW);
  digitalWrite(MotorBB, LOW);
}

void loop() {
  x = analogRead(A0);
  Move();
  Serial.println(x);
}

void Move() {
  if (x == 0){
    return;
  }

  if (x > 520)
  {
    digitalWrite(MotorAA, HIGH);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, HIGH);
    digitalWrite(MotorBB, LOW);
  }
  else if (x < 480)
  {
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, HIGH);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, HIGH);
  }
  else{
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, LOW);
  }
}

The Arduino can definitely not power that many motors. The Arduino's max output current is 0.1A and you might be drawing around 0.5A. Use an external battery like a LiPo battery for the motor controller.
NOTE: Please watch out! Drawing that many amps from Arduino can kill it! So please use the LiPo or normal batteries!


Set a pin HIGH when crash occurs I'm using an ESP8266 (NodeMCU v3). I want to set a PIN high if a soft wdt reset occurs (not expecting one). Is there a way I can do that?

Can I attach something on TX pin of the board and watch for crash dump? Maybe another Arduino?

The ESP provides a reset reason API, which lets you differentiate between a crash and a normal reset:

extern "C" {
  #include "user_interface.h"
}

const char * const RST_REASONS[] =
{
  "REASON_DEFAULT_RST",
  "REASON_WDT_RST",
  "REASON_EXCEPTION_RST",
  "REASON_SOFT_WDT_RST",
  "REASON_SOFT_RESTART",
  "REASON_DEEP_SLEEP_AWAKE",
  "REASON_EXT_SYS_RST"
};

// .. in setup():

const rst_info * resetInfo = system_get_rst_info(); //populate reset info
String diag = String(RST_REASONS[resetInfo->reason]); // turn enum index to string

if(diag == "REASON_SOFT_WDT_RST") digitalWrite(TX, HIGH);// check string, take action


Arduino in Eclipse IDE: How to add SPI library (core library already added)? I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.
So far, so good.
But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, no .a)!

My sample code

#include <Arduino.h>
#include <SPI.h>

int main(void) {
    init();
    pinMode(13, OUTPUT);
    for (;;) {
        digitalWrite(13,1);
        SPI.setBitOrder(0);
    }
}

The pinMode and digitalWrite parts work, but with the SPI method I get an error:

05:33:26 **** Build of configuration Debug for project ArduinoTestProject ****
make all
Building file: ../main.cpp
Invoking: AVR C++ Compiler
avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp"
Finished building: ../main.cpp

Building target: ArduinoTestProject.elf
Invoking: AVR C++ Linker
avr-gcc -s -Os -o"ArduinoTestProject.elf"  ./main.o   -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" >ArduinoTestProject.symbol
./main.o: In function `main':
../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)'
collect2: error: ld returned 1 exit status
avr-nm: 'ArduinoTestProject.elf': No such file
make: *** [ArduinoTestProject.elf] Error 1

05:33:26 Build Finished (took 72ms)

Does anyone see the problem?

As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)

The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.

In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.

As such there is no SPI.a file created during the compilation process.
In CDT you can have both options (with or  without .a file) but the Arduino IDE way is the easiest, by far.

So lets first assume you want to compile the "Arduino way" aka without SPI.a.
What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path.
That is all there is to it.

If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build

Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.

I would strongly advise to start your arduino eclipse development with my arduino eclipse plugin because it is simply easier. Later you can evolve to the full freedom of CDT.

If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.


MIDI keyboard controlled LED strip My objective is to light a led on a strip corresponding to a keyboard note.
I have Arduino Uno with MIDI in module hooked up to a serial port. Piano is hooked with a standart midi cable, Led Strip is powered using Arduino's 5v (Figured i don't need more because Max 10 leds will be active at a time).

My setup works but not accurately. All is fine when only 1 note at a time is played, but the denser the music becomes (faster or more notes are played simultaniously) more inaccuracies show - more leds don't turn off or on, or the notes I didn't play light up.

At first i used software serial and there were even more mistakes, when i switched to hardware it became better.
Could it be that Arduino UNO is just not powerfull enough and cannot keep up with incoming midi input or is there another problem?

Here is the code:

#include <MIDI.h>
#include <Adafruit_NeoPixel.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define STRIP_PIN 11
#define STRIP_NUM_PIXELS 88

Adafruit_NeoPixel strip = Adafruit_NeoPixel(STRIP_NUM_PIXELS, STRIP_PIN, NEO_GRB + NEO_KHZ800);

void handleNoteOn(byte channel, byte pitch, byte velocity)
{
  strip.setPixelColor(pitch - 21, strip.Color(50, 50, 50));
  strip.show();
}

void handleNoteOff(byte channel, byte pitch, byte velocity)
{
  strip.setPixelColor(pitch - 21, strip.Color(0, 0, 0));
  strip.show();
}

// -----------------------------------------------------------------------------

void setup()
{
    MIDI.setHandleNoteOn(handleNoteOn);
    MIDI.setHandleNoteOff(handleNoteOff);
    MIDI.begin(MIDI_CHANNEL_OMNI);
    strip.begin();
}

void loop()
{
    MIDI.read();
}

The biggest problem is that updating the LEDs is an intensive task.

Hand-crafted assembly is written to get the timing right
Interrupts are disabled while the update is running
88 LEDs take a (relatively) long time to update.

At about 1.2µS per LED plus 50µS for the reset pulse, you're looking at about 155µS that the Arduino can't be doing anything else at all. That includes receiving anything through serial.  And since you update for every note you receive, if there is a second note coming in with 155µS of that one, it will be missed.

You may get better results with the FastLED library instead of the Adafruit Neopixel library, but ideally you want to work with a board that is fast enough to not need to do such tight bit-banging for the protocol, so that interrupts can still be enabled for receiving data.


How can I split data coming from JSON? In my recent project, I'm working with Arduino and JSON. Now, I get data from JSON and I can able to receive in Arduino side.

Below one is my Arduino code:

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String response = "";
bool begin = false;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin) response += (in);

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}

Output :

{"TPS":"0.40","MAP":"1.05","LOAD":"14"}

Now, I want to split data means store 0.40 in one variable, 1.05 in another variable and 14 in another variable. I don't know how to split this.

Finally, I got it. I have fixed length of data. So, I use a counter to calculate the how many characters are there in my data. Now using the index of this characters, I find out proper data and then store in a different variable.

Below is my code:

#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

String responseOne = "";
String responseTwo = "";
String responseThree = "";
bool begin = false;

int counter = 0;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      counter++;

      if(counter >= 9 && counter <= 12)   // This gives 0.40
      {
        responseOne += (in);              // 0.40 store in responseOne variable
      }

      if(counter >= 22 && counter <= 25)  // This gives 1.05
      {
        responseTwo += (in);              // 1.05 store in responseTwo
      }

      if(counter >= 36 && counter <= 37)  // This gives 14
      {
        responseThree += (in);            // 14 store in responseThree
      }
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  float newResponseOne = responseOne.toFloat();  // Convert string into Float
  float newResponseTwo = responseTwo.toFloat();  // Convert string into Float
  int newResponseThree = responseThree.toInt();  // Convert string into Integer

  lcd.setCursor(0, 0);
  lcd.print(newResponseOne);

  lcd.setCursor(8, 0);
  lcd.print(newResponseTwo);

  lcd.setCursor(0, 1);
  lcd.print(newResponseThree);
}


Run motor for a set amount of depending of Pressure Sensor I'm a noob when it comes to time-based coding.

I have a pressure sensor which shows me readings for when someone is sitting on a chair.

I want to turn a motor for 2 seconds when the pressure sensor says occupied
I want to turn the motor the other way for 2 seconds when the pressure sensor says empty.

Also after the motor has turned for 2 seconds, I don't want it to turn the motor at all until the reading of the pressure has changed to the other reading.

Here is my code.

#include <AFMotor.h>
AF_DCMotor motor(1,MOTOR12_64KHZ);
AF_DCMotor motor2(2,MOTOR12_64KHZ);
int fsrPin = 0;     //FSR and 10K resistor are connected to pin 0
int fsrReading;     //the analog reading from the resistor divider

bool WheelLock = true;  //controls whether the wheelchair is locked or not
long startTime = millis();
long stopTime = startTime;

void setup(void){
  Serial.begin(9600);
  motor.setSpeed(255);
  startTime = 0;
  stopTime = 5000;
}

void loop(){
  while(startTime < stopTime){
    if(onChair() == false){
      motor.run(BACKWARD);
      startTime = millis();
    }
    else{
      motor.run(FORWARD);
      startTime = millis();
    }
  }
  motor.run(RELEASE);
  Serial.println("RELEASED");
  startTime = 0;
  Serial.println(startTime);
}

bool onChair(){
  fsrReading = analogRead(fsrPin);

  if(fsrReading > 800){
    Serial.println("Wheelchair is occupied");
    WheelLock = false;
  }

  else{
    Serial.println("Wheelchair is empty");
    WheelLock = true;
  }
  delay(200);
  return WheelLock;
}

Fairly easy.

You have to determine if the pressure has changed from its previous reading.

If it has, you can start to turn the motor for two seconds.

Once the time is up, turn the motor off.

Once you put your code in that framework, it would be much easier to code top down.


Random number/sequence output The program I'm trying to build is:

Type in 1st name, hit enter, type in 2nd name and then hit enter again.
Register those names from string input to char naming in student struct.
Print out the names in serial monitor.
Use those names in the main program.

The problem is I got randomize results whenever I typed in the names.

My target output:

Program Starts
Insert 2 students name:

First student: Adam     //When input -> Adam
Second student: Eve     //When input -> Eve
First student: John    //When input -> John
Second student: Amy    //When input -> Amy
//the sequences should repeat

...but what happened is the sequences of the names randomized. For example:

Program Starts
Insert 2 students name:

First student: Adam
First student: Eve
Second student: John
First student: Amy
//the sequences will keep randomizing

Can anyone point out what I've missed out?

The program:

typedef struct
    {
        char naming[20];
    }student;

    student record[]{
      {""},
      {""},
    };

    String readString;
    String str="";

    // the setup routine runs once when you press reset:
    void setup() {
      Serial.begin(9600);    // initialize serial communication at 9600 bits per second
      while (!Serial);              // wait for Serial Monitor to open
      SerialUSB.println("Program Starts \n Insert 2 students name:");  // Title of sketch
    }

    void loop() {
        namedata();
        mainprg();
    }

    void namedata()
    {
    for(uint8_t i = 0; i < sizeof(record)/sizeof(student); i++){
          while (Serial.available()) {
            char c = Serial.read();
            readString += c;
            readString.trim();
          }

          if (readString.length() >0) {
            str = readString;
            str.toCharArray(record[i].naming,20);
            if(i==0){
               Serial.print("First student: ");
            }else if(i==1){
               Serial.print("Second student: ");
            }
            Serial.println(record[i].naming);
          }
            readString="";
        }
    }

    void mainprg()
    {
      //main program using student`s name
    }

Additional infos:

1.Why use struct? Because I've more data to process/store for one "student" in my main program.
2.Currently using Arduino Yun Mini, Arduino 1.8.7

Thanks in advance!

Even though this is not elegant by any means, for now this is what I've came out with:

typedef struct
{
  char naming[20];
} student;

student record[] {
  {""},
  {""},
};

int a = 0;

char buf[20];

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(9600);    // initialize serial communication at 9600 bits per second
  while (!Serial);              // wait for Serial Monitor to open
  Serial.println("Program Starts \n Insert 2 students name:");  // Title of sketch
}

void loop() {
  if (readline(Serial.read(), buf, 20) > 0) {
    if (a == 0) {
      Serial.print("First student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
      a = 1;
    }
    else if ( a == 1) {
      Serial.print("Second student: ");
      strncpy(record[a].naming, buf, 20);
      Serial.println(record[a].naming);
    }

  }
}

int readline(int readch, char *buffer, int len) {
  static int pos = 0;
  int rpos;

  if (readch > 0) {
    switch (readch) {
      case '\r': // Ignore CR
        break;
      case '\n': // Return on new-line
        rpos = pos;
        pos = 0;  // Reset position index ready for next time
        return rpos;
      default:
        if (pos < len - 1) {
          buffer[pos++] = readch;
          buffer[pos] = 0;
        }
    }
  }
  return 0;
}

Basically by using int a, the program decides the sequences of the name. Although it will not repeat the sequence after the 2nd input (ie 1st>2nd>1st>2nd), at least the sequence is not randomize anymore.

Btw thanks for the tips @chrisl!


What can I do to optimise this code? I have optimised it as much as I feel I can and want to know what suggestions you have that could make it more efficient etc.
Note: I know the array goes on forever :)
volatile uint16_t IRCode[]={340,171,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,21,21,64,21,21,21,64,21,64,21,64,21,64,21,64,21,21,21,21,21,21,21,64,21,21,21,21,21,21,21,21,21,64,21,64,21,64,21,21,21,64,21,64,21,64,21,1556,340,86,21,3654}; // ProntoHex to uint16_t delete first 4 array numbers.
volatile uint16_t MicrosPassed;
volatile uint8_t Array_Seq;
uint8_t State;

void setup() {
  Config(); // Config sketch will set working settings for different microcontrollers.
  SendIRCode();
}

void loop() {

}

void SendIRCode() {
  switch(State) {
    case 1:
      TCCR1A&=63; // Opposite of case 0 -193 = 63
      State=0;
      break;

    case 0:
      TCCR1A|=192;
      State=1;
      break;
  }
}

void Config() {
  DDRB|=10;
  ICR1=416;
  OCR1A=9983;
  TCCR1A=2;
  TCCR1B=24;
  TCCR1B|=1;
  TIMSK1=1;
}

ISR(TIMER1_OVF_vect) {
  MicrosPassed++;
  if(MicrosPassed==IRCode[Array_Seq]) {
    SendIRCode();
    MicrosPassed=0;
    Array_Seq++;
       }
}

As hinted by chrisl in a comment, there are various criteria you may
want to optimize for: speed, size, readability... Judging from the
current state of this sketch, I would say that your first goal at this
point should be to optimize for readability.
The hardest think to make sense of are most of the plain numbers. When
setting registers that are bit fields, do not use decimal values: use
either hexadecimal or binary. Or, better yet, use the names of the bits.
The avr-libc defines those names, as well as the macro
_BV(bit_position), which expands to (1 << bit_position) and is meant
to be used with those names:
void Config() {
  DDRB   |= _BV(PB1) | _BV(PB3);  // PB1 and PB3 as output
  ICR1    =  416;        // timer period = 417 cycles
  OCR1A   = 9983;        // ???
  TCCR1A  = _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
  TCCR1B  = _BV(WGM12) | _BV(WGM13);  // ...ditto
  TCCR1B |= _BV(CS10);   // clock @ F_CPU
  TIMSK1  = _BV(TOIE1);  // enable TIMER1_OVF interrupt
}

Granted, the bit names are somewhat obscure, but they do make the
program easier to read if you have the datasheet nearby. I do like to
have comments that make the code understandable even without reading the
datasheet.
Note that evaluating those expressions does not make the program any
slower, as they are evaluated at compile time.
When a variable is used in a single function, it is better to define it
in that function. Keeping the definition close to where the variable is
used makes the code more “local” and thus easier to read. Since you want
some of those variables to remember their values across invocations of
the function, give them the static qualifier.
You may not need to optimize this program for speed. There is, however,
a low hanging fruit here: remove the volatile keywords. This keyword
is meant to explicitly disable some compiler optimizations that are
unsafe when a variable is shared between the interrupt and non-interrupt
contexts. None of the variable you use needs this.
If I understood correctly, the function SendIRCode() just toggles a
couple of bits in TCCR1A. You can simplify it to this:
void SendIRCode() {
  TCCR1A ^= _BV(COM1A0) | _BV(COM1A1);  // toggle PWM output on OC1A
}

Finally, there is I believe a bug in this sketch. The variable
Array_Seq is continuously incremented and never reset. The program
will then end up reading past the end of the IRCode array.


fail to pass a value in constructor I'm making a JSON lib dedicated for my own needs, based on ArduinoJSON v6.

I try to define StaticJsonDocument<_docSize> doc in a parametric way but I get this error and I cant find the reason for it:

/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp: In constructor 'myJSON::myJSON(char*, int, bool)':
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:28: sorry, unimplemented: use of the value of the object being constructed in a constant expression
         StaticJsonDocument<_docSize> doc;
                            ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: error: 'this' is not a constant expression
         StaticJsonDocument<_docSize> doc;
                                    ^
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:36: note: in template argument for type 'unsigned int'
/Users/guy/git/Arduino/libraries/myJSON/myJSON.cpp:12:41: error: invalid type in declaration before ';' token
         StaticJsonDocument<_docSize> doc;
                                         ^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

I paste only relevant part of the code

myJSON.h :

#ifndef myJSON_h
#define myJSON_h

#include "Arduino.h"
#include <ArduinoJson.h>
#include "FS.h"

class myJSON
{
private:
int _docSize=100;
bool useSerial;
char _filename[30];

public:
myJSON(char *filename, int docsize, bool useserial=false);
bool file_exists();//char *file=_filename);
bool file_remove();
bool format ();

};
#endif

myJSON.cpp:

#include "Arduino.h"
#include "myJSON.h"
#include "FS.h"
#include <ArduinoJson.h>

myJSON::myJSON(char *filename, int docsize, bool useserial) {

        _docSize = docsize;
        useSerial = useserial;

        StaticJsonDocument<_docSize> doc;

        if (useSerial) {
                Serial.begin(9600);
        }
        if (!SPIFFS.begin()) {
                if (useSerial) {
                        Serial.println("Failed to mount file system");
                }
        }
        else{
                sprintf(_filename,"%s",filename);
        }
}

A class that uses <...> is called a template class.  That class uses a form of substitution at compile time to create a concrete class with those values and tokens substituted.

It is then that concrete class that is used to instantiate your object(s).

However, you are trying to use a runtime variable to convert a template class into a concrete class, and that can't be done at compile time - and there is no such thing as a runtime template in C++.

You need to re-think your implementation methodology.


How to read info from an Xbee Pro S2B to an Arduino with a Xbee Pro S2B I am using two XBee Pro S2B modules. One (Router) connected to the laptop via a UART cable. The other (Coordinator) connected to an Arduino Mega with the sketch below.  All I need it to do is turn a LED on and off and display the status in the IDE serial monitor.  I am using Arduino IDE (v1.6.0).

Arduino sketch:

#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (Serial.available())
    {
         int myData = Serial.read();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData, DEC);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData, DEC);
         }
     }
 }

Where did I go wrong?

You have two serial connections. One for the main USB of the board and one for the XBee.

So you need to read from the XBee and write to the serial USB?

I don't know what speed you have configured for your XBee so I have set it to 9600.

This example reads from the XBee and writes to the Serial/USB port

#include <SoftwareSerial.h>

SoftwareSerial xbee (2,3);

int myData = 0;
int ledPin = 13;

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

    pinMode(ledPin, OUTPUT);
}

void loop()
{
    if (xbee.available())
    {

         int myData = xbee.read();

         Serial.print("Data has arrived on the Arduino");
         Serial.write(myData);
         Serial.println();

         if(myData == '1')
         {
             digitalWrite(ledPin,HIGH);
             Serial.write(myData);
         }
         if(myData == '2')
         {
             digitalWrite(ledPin,LOW);
             Serial.write(myData);
         }
     }
 }

Note: Your example also used Serial.write() with the wrong argument DEC which applies to Serial.print(). X-CTU and Arduino both send ascii which is also what the Serial.print() does. However the Serial.read() just reads the byte so we need to use Serial.write() to send the same bytes back to the other end.

You can also make life a bit easier by replacing xbee.available() with Serial.available(). Then use the Arduino IDE serial monitor to both send and receive. This means that you just use the one USB connection to prove the code.


Atmega328P burn bootloader with FTDI I need your help.

I am using Arduino ProMini in my project.

In project board there is Atmega328P which doesn't have Arduino bootloader, and Atmega328P RXD, TXD pins are connected to FTDI Basic(sparkfun)'s TXD and RXD pins.
I searched on internet how to burn bootloader for arduino. Most of them use other Arduino's built in SPI or other method. Problem is Atmega328P is already assembled to PCB board and I cannot make any soldering or change. Atmega328 and FTDI basic are connected and assembled to upload sketch (if there is bootloader of Arduino inside of Atmega328P, no problem to upload sketch).

Is there any solution or suggestions to burn bootloader using FTDI?

Thank You.

You cannot upload the bootloader through the ATmega's UART pins.

Perhaps the the necessary pins (SPI & reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.

Otherwise you may just have to desolder the chip.

A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part.


Can I make so when I press a button on my Arduino Uno board, it will press a key on my computer? I looked up the question before, but they only gave answers for boards that are not the Uno. Is there any way to make it so when I press a button on my board, it registers as a key press on my computer? I'm trying to make a flight controller for PC sims.

Thanks!

Not without extra software on your computer side.

However if you use Arduino Micro, you can emulate keyboard and/or mouse directly.


Arduino IDE: How to get PROGMEM const length? I have defined a byte array as a constant in the Atmel's flash memory:

const uint8_t eye [] PROGMEM = {
  0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
  0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
};

How can I (repeatedly) read the length of this constant in the program? All the available functions in avr/pgmspace.h do not deliver the proper length, no matter how I use them. I tried strlen(eye), strlen_P(eye), strLen_PF(eye) and also sizeof(eye). I'm new to C, so I'm not sure about the whole pointer stuff.

Probably the best way would be to define below it

const int eye_len = sizeof(eye)/sizeof(eye[0]);

If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.


Are there different revisions of Arduino Uno SMD? I know there are different revisions of the Arduino Uno itself, but are there any revisions of the SMD? If they are is SMD R2 identical to through-hole R2? I have a board marked R2 SMD and I am wondering if that is the only version that they produced in SMD format and just are signifying that it is compatible with the standard R2.

The only difference with the SMD Uno is the fact you can't remove the chip. There are also 2 extra analog comparators not connected to anything.

The SMD boards are compatible with the thru-hole boards, but they have SMD components, which apparently make them easier to make and cheaper. As I said before, the two extra analog inputs (A7 and A6) are left unconnected on the official boards.

Here is my Uno R3:


Error message - Need help I found this Haptic Headband project on YouTube (link below) and I am trying to verify the code that was given in the instructions with the Arduino IDE. However, I keep getting the message below and am not too sure what I need to do to fix it. I'd appreciate any help I could get to solve this issue.
I have also attached a pdf of the instructions with the code to use for the headband.
PDF: https://cdn-learn.adafruit.com/downloads/pdf/haptic-headband.pdf?timestamp=1602887165
https://www.youtube.com/watch?v=xD7bfBx5D9M&ab_channel=AdafruitIndustries

libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::setRealtimeValue(unsigned char)'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::useERM()'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
libraries\Adafruit_DRV2605_Library\Adafruit_DRV2605.cpp.o (symbol from plugin): In function `Adafruit_DRV2605::Adafruit_DRV2605()':
(.text+0x0): multiple definition of `Adafruit_DRV2605::useLRA()'
sketch\Adafruit_DRV2605.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino Uno.

“Multiple definition” means that you have something defined more than
once. According to the error message, some methods are defined both in
libraries\Adafruit_DRV2605_Library and in your sketch folder.
It looks to me like you are trying to use two copies of the
Adafruit_DRV2605 library. One of them is properly installed as a
library, and the other is within your sketch folder. You don't need two
copies. If the library is properly installed, there is no point in
copying its source files to your sketch folder. Get rid of that extra
copy and try recompiling.


Arduino force feedback vibration gamepad I'm projecting a gamepad with Arduino Micro. I'm using the Arduino Joystick Library.

I'm building this gamepad for racing games so I need to catch signal like hit_the_wall, hit_another_car.

I wonder how the PC game output the signal of the vibration/force feedback and send throw USB to the gamepad.

I already know that the gamepad drivers and the game have to support this function, but I'm completely lost about how I can catch the input to trigger the vibration engine with Arduino.

I was thinking something about (pseudocode):

input = Serial.read();

if(input == hit_something_signal){

   digitalWrite(engine, HIGH);

}

Now my question is which is this magic hit_something_signal?

UPDATE

I'm reading the PID document and I notice on page number 24 the register addresses to implement the force feedback.

;Start Force Feedback command definitions
USAGE_PAGE (Physical Interface) 05 0F
;Effect Report Definition
 USAGE (Set Effect Report) 09 21
 COLLECTION (Logical) A1 02
 USAGE (Effect Block Index) 09 22
 LOGICAL_MAXIMUM (127) 25 7F
 REPORT_SIZE (7) 75 07
 REPORT_COUNT (1) 95 01
 OUTPUT (Data,Var,Abs)
 .......

In the Joystick.cpp file I notice the HID implementation:

// USAGE_PAGE (Generic Desktop)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x05;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// USAGE (Joystick - 0x04; Gamepad - 0x05; Multi-axis Controller - 0x08)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x09;
tempHidReportDescriptor[hidReportDescriptorSize++] = joystickType;

// COLLECTION (Application)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0xa1;
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x01;

// REPORT_ID (Default: 3)
tempHidReportDescriptor[hidReportDescriptorSize++] = 0x85;
tempHidReportDescriptor[hidReportDescriptorSize++] = _hidReportId;
.......
......

Do you think should be possible to implement the force feedback part? I do not need to catch all the forces, but run the vibrator engine every time the game sends and input of every kind of force.

The problem is that I'm not an expert about low-level programming and drivers. Do you have any idea?

That library has no support for vibration.

The HID report descriptor has to include the correct OUTPUT items for the PC to send the vibration instructions to the Arduino - and of course the library has to be able to handle that incoming data - none of which is implemented.

So you can't unless you massively expand that library. And that takes intimate knowledge of USB and HID protocols.


Arduino parsing Double is incorrect Im having some problems with parsing gps coordinates with the arduino ide.

To be honest I want to process the data without a library.

From my sensor I get this String: 4815.98450

The result of String.toDouble(): 4815.9843750

I also parsed it on my own, but i got the same result: (yes this code is not nice ;))

char buf[10];
  msg.toCharArray(buf, 19);
  double num = 0.0;

  int c;

  c = buf[0] - '0';
  double num0 = (c * 1000);
  c = buf[1] - '0';
  double num1 = (c * 100);
  c = buf[2] - '0';
  double num2 = (c * 10);
  c = buf[3] - '0';
  double num3 = (c * 1);
  c = buf[5] - '0';
  double num5 = (c * 0.1);
  c = buf[6] - '0';
  double num6 = (c * 0.01);
  c = buf[7] - '0';
  double num7 = (c * 0.001);
  c = buf[8] - '0';
  double num8 = (c * 0.0001);
  c = buf[9] - '0';
  double num9 = (c * 0.00001);
  num = num + num0;
  num = num + num1;
  num = num + num2;
  num = num + num3;
  num = num + num5;
  num = num + num6;
  num = num + num7;
  num = num + num8;
  num = num + num9;

Does somebody have a solution for my problems?

Thank you very much :=)

There is no easy solution. The Arduino you are using does not support
double precision floating point. The type double is just an alias for
float, which has 24-bit accuracy.

Your program is actually giving you the correct result, as the float
closest to 4815.98450 is exactly 4815.984375.


Handling double (8 byte) in Arduino mega 2560? I am receiving 8 bytes from serial.

I want to convert and save in double variable.

This is how i tried.

union u_data
    {
        byte b[4];
        double fval;
    } u;

double BytesToDouble (byte b8,byte b7,byte b6,byte b5,byte b4,byte b3,byte b2,byte b1)
{
    u.b[0] = b1;
    u.b[1] = b2;
    u.b[2] = b3;
    u.b[3] = b4;
    u.b[4] = b5;
    u.b[5] = b6;
    u.b[6] = b7;
    u.b[7] = b8;
 return u.fval;
}

But i am getting 0.00. Because here double size is 4 bytes.

Is there is any other way to do this?

Thanks

In the Arduino there is no such thing as a double. A double is just another name for a float.

So you will have to either:

Manually interpret the double format data and calculate that into a float value, or
Send the value as some other format, such as float (32-bit), ASCII text, or (a selection of) integer values.

Since you can't actually use anything more than float, sending data with a higher resolution is pointless, so you are probably best off just sending it as a float.


Get when a button close the circuit That seems to be a bit stupid to myself but I can't figure out to get to know when my button is pushed (closed) or released (open).

You must know that this not just a simple push button. Actually it is more of a complex button with multiples output (Y, G, 0V, COM, NO, NC, HORM, 12V).
With a multimeter i've been able to locale witch output are closed when the button is pressed. These are HORM (that is the name for two outputs -?!-) and on the other side COM and NO.

I've tried to plug that to my arduino Mega, on PIN 7, and getting the value with Digital.Read. Tho when i try to display it on the Serial, it doesn't work and return an error. (It did the same for HORM and COM/NO)

I also noticed something strange. When the button is pressed, Arduino seems to notice it because my "ON" led turns off and then turns back on. Like if the arduino was crashing. The 13th pin LED stay HIGH after the arduino goes back on.

Please, have a look at my code.

int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
}

void loop(){
  val = digitalRead(inPin);  // read input value
  Serial.write(val);
  if (val == HIGH) {         // check if the input is HIGH (button released)
    digitalWrite(ledPin, LOW);  // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);  // turn LED ON
  }

  delay(1000);
}

Do you guys have any advice ?

Thank you very much in advance.

Also please have a look at the circuit. The only difference is that instead of having this kind of simple pushbutton, i've got my NO and COM plugged the same way.

Ok then.

I just tried that again and it simply seems that the wiring shown on the tutorial is not good at all.
I made another wiring that worked exactly fine.


VSCode Platformio Schedule.h: No such file or directory I suppose this might be more an environment question regarding Platform.io and VSCode, as my code works great in the Arduino IDE, however the lack of syntax highlighting is driving me mad.

I've setup a Platform.io project in VSCode, copied my code across and setup my board (Wemos D1 Mini)

My platformio.ini file looks like:

[env:wemos_d1_mini32]
platform = espressif32
board = wemos_d1_mini32
framework = arduino

There are a couple of headers that are highlighted as having errors:

#include "FirebaseESP8266.h"
#include <ESP8266WiFi.h>

I've installed FirebaseESP8266 to my project from the PlatformIO libraries, however it still says:

  include errors detected. Please update your includePath. Squiggles are disabled for this translation unit
  (C:\Users\Greg\Documents\PlatformIO\Projects\Lovebox\src\main.cpp).C/C++(1696)

If I try to build it errors with src\main.cpp:1:22: fatal error: Schedule.h: No such file or directory

As for the ESP8266WiFi library, it simply says cannot open source file "ESP8266WiFi.h"

Anyone know where I'm going wrong?

Did you install the libraries you need / use?

You could do it either via the platformio screen or add the names directly to the
platformio.ini

lib_deps =
    Firebase ESP8266 Client@>=2.7.8

And additionally ESP8266WiFi.h is an ESP8266 library
for the ESP32 you should use the lib #include <WiFi.h>

EDIT: To update the project libraries, select 'Update Project Libraries' from the project tasks.


Arduino serial port programming I bought an Arduino-on-breadboard kit. I have several PCs with serial ports, and now I'm being told I need a USB-to-serial converter. I thought I was ready to start uploading sketches, so how can I do this?

I'm able to understand serial communications and am capable of wiring a MAX232 chip into a breaduino if necessary, but I'm not sure it will work, so to save some time I'm asking, mostly because I was unable to figure it out with Google searches alone.

PS: I also have a stk500, but then I would be out of the easiness of using Arduino sketches and the programming language. I need the fastest route to prototyping/testing my sketches.

An RS232 port wired via a level converter (as you mentioned max232) and a 1uF capacitor between RTS and "Arduino reset pin" Getting started with Arduino.

The capacitor is to trigger a reset on the Arduino so the bootloader kicks in and awaits a "Arduino sketch" via the serial port.

Your setup is AKA "Arduino Bare bone".


Controlling two AC devices, device turning on incorrectly I am making use of the code below to control the speed of an AC fan and the intensity of an AC Lamp with an Uno.

The problem I am having is that, when I set the lamp intensity to low or medium, the fan turns on at a very low speed as well, and I cannot turn it off even when setting the fan to off.

Also if I turn the lamp on and then off, the fan (which is still set as off), will spin slowly for a second or two in random intervals.

For troubleshooting purposes, I did separate this program into two programs, controlling each device and its circuit separately, and it works perfectly, but when I combine them, I get the above problem.

Any assistance in troubleshooting or ideas to solve this would be appreciated.
Haven't attempted AC control before.

int PWM = 3;
int FAN = 4;
int dimming;

void setup()
{
  Serial.begin(9600);
  Serial.println("Serial connection started, waiting for instructions…n0 =     Offn1 = 25%n2 =50%n3 = 75%n4 = 100%");
  pinMode(PWM, OUTPUT);
  pinMode(FAN, OUTPUT);

  attachInterrupt(0, zero_crosss_int, RISING);
}

void zero_crosss_int()
// function to be fired at the zero crossing to dim the light
{
  int dimtime = (75 * dimming);  // For 60Hz =>65
  delayMicroseconds(dimtime);    // Off cycle
  digitalWrite(FAN, HIGH);   // triac firing
  delayMicroseconds(10);         // triac On propogation delay
  //(for 60Hz use 8.33)
  digitalWrite(FAN, LOW);    // triac Off
}

void loop ()
{
  if (Serial.available()) {
    char ser = Serial.read(); //read serial as a character

    switch (ser)
{

  /* Lamp Control  */

  case '0':
    analogWrite(PWM, 0);  //lamp Off
    break;
  case '1':
    analogWrite(PWM, 50);  //lamp low
    break;

  case '2':
    analogWrite(PWM, 130); //lamp medium
    break;

  case '3':
    analogWrite(PWM, 255); //lamp high
    break;

  /* Fan Control  */

  case '4':
    dimming = 128;  //fan off
    break;

  case '5':
    dimming = 90; //fan low
    break;

  case '6':
    dimming = 65; //fan medium
    break;

  case '7':
    dimming = 35; //fan high
    break;

  default:
    Serial.println("Invalid entry");

    }
  }
}

The circuits it controls is based on these :

Lamp

Fan

Also, these circuits and code are based on these post, if it may interest you:

Lamp
PWM AC Lamp

Fan
Dimmer AC Fan

Imraan, you have most definitely NOT build your circuit safely as to do so is impossible on a 'breadboard' when using 220 VAC.  The contacts on these boards are extremely poor not to mention that the separation between the metal contacts is inadequate.  Please read up on track separation for mains voltages on PCB's to get an idea of what is required.
The commonly used 0.1" pitch strip board is also unsuitable for mains voltages.


How to implement a tilt compensated compass? So i was trying to implement a tilt compensated compass, using HMC5883L and MPU6050. The problem i am facing is, there are 2 equations for tilt compensation
Tilt Compensated X:   X,Y,Z are compass output (raw output)
new_X =  X*cos(pitch) + Y*sin(roll)*sin(pitch) – Z*cos(roll)*sin(pitch)
Tilt Compensated Y:
new Y =  Y*cos(roll) + Z*sin(roll)
Final Heading :
Azimuth =  atan2(Y, X) * RAD_TO_DEG
The angles which i am getting from the mpu are gyro-drift corrected angles which are coming through a kalman filter. Those angles are fed to these above equations and after atan2 i get the tilt compensated heading. But the issue/observation here is, when i rotate the body(on which the compass and mpu are) along the Z axis (YAW axis) the heading doesn't change(sort of locked on), but changes when i tilt the body in X/Y.
I searched for thorough references, but wasn't able to find any!
Here is my code snippet (uses compass part form adafruit library):
double HEADING(double r, double p){
  sensors_event_t event;
  mag.getEvent(&event);
  r = r * (PI/180);
  p = p * (PI/180);
  double x = (event.magnetic.x)*cos(p) + (event.magnetic.y)*sin(r)*sin(p) - (event.magnetic.z)*cos(r)*sin(p);
  double y = (event.magnetic.y)*cos(r) + (event.magnetic.z)*sin(r);

  float heading = atan2(y,x);

  float declinationAngle = 0.366667 * (PI/180);// (0°22')positve declination
  heading += declinationAngle;

  if(heading < 0)
    heading += 2*PI;

  if(heading > 2*PI)
    heading -= 2*PI;

  heading = heading * 180/PI;

  return heading;
}

The HMC5883L data acquisition I wrote :
// i just need a direction reference not actual heading, just to keep my drone
// steady on yaw axis with reference to that direction reference but it shall be Tilt compensated
#include<Wire.h>

#define MAG 0x1E

#define R 0
#define P 1
#define Y 2

float mag_raw[3],h;
float CMP_DEC = 0.36667 * (PI/180);

void setup(){
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(400000);

  Wire.beginTransmission(MAG);
  Wire.write(0x02);
  Wire.write(0x00);
  Wire.endTransmission(true);

}

void loop(){
  Wire.beginTransmission(MAG);
  Wire.write(0x03);
  Wire.endTransmission(false);
  Wire.requestFrom(MAG,6,true);

  mag_raw[R] = Wire.read() << 8 | Wire.read();
  mag_raw[P] = Wire.read() << 8 | Wire.read();
  mag_raw[Y] = Wire.read() << 8 | Wire.read();

  h = atan2(mag_raw[P],mag_raw[R]);

//  h += CMP_DEC;

  if(h < 0) h+= (2*PI);
  if(h > (2*PI)) h -= (2*PI);
  h *= (180/PI);

//  Serial.print("X : ");
//  Serial.print(mag_raw[R]);
//  Serial.print(" Y : ");
//  Serial.print(mag_raw[P]);
//  Serial.print(" Z : ");
//  Serial.print(mag_raw[Y]);

  Serial.print(" H : ");
  Serial.println(h);

}

Some guidance will be very helpful!

Inspecting your code, it does not appear you are compensating the raw magnetometer values for soft and hard iron effects.  These terms roughly refer to adjusting the range and magnitude of each of the individual magnetometers (X, Y and Z).  Some magnetometer manufactures allow writing these compensation values into the chip.  Even then the developer and user will still need to perform some form of calibration as the magnetometer can not predict under what conditions the magnetometer will be used.  Here is another explanation using matrices of hard and soft iron compensation.
Once the compass produces expected results on a flat surface parallel to the surface of the earth (in a place on earth where the magnetic lines roughly align with true north).  Consider adding tilt compensation.  Accelerometers usually do not need to be compensated as extensively as magnetometers.
This can be done using trigonometric math and Euler angles.  However, as with physical gambles, this can lead to a situation similar to gimbal lock.  Where the trigonometric math goes to infinity.
To avoid a gimbal lock like situation, most tilt compensated compasses use quaternions.  Quaternions use imaginary numbers and matrix math to describe 3 dimensional rotation.


Menu libaries for a clock I have a 7 segment clock with 4 digits, and 2 push buttons to control time (hours seconds days month etc). What is the best way to manage the settings of each sub menu when the user wants to change the time? Is coding it myself or using a menu library such as this one better for the task? https://playground.arduino.cc/Code/Menu

Thanks

I would make it myself.

One way to do it:

Create an enum with all states, like Normal, ChangeMonth, ChangeDay, ChangeHour, ChangeMinute };
Use one button to increase the item you are changing with 1
Use the other button go to go the next enum

You can make it fancier by using longer/shorter presses (e.g. to increase faster)

Don't forget to debounce button inputs.


Are there any Arduino libraries that allow you to upload data directly to PostgreSQL? Are there any Arduino libraries that allow you to upload data directly to PostgreSQL?
I have been turning the internet upside down to answer this question but most of the information is several years old.

The only solution to this question that I could find is a GitHub repository that hasn't been touched in several years called, SimplePgSQL. Feel free to add a better answer if you are able to find something more current. More current information would be useful!
https://github.com/ethanak/SimplePgSQL


Using an Arduino as an LED controller for an arcade stick I'm attempting what seemed to be a rather simple problem at first glance, but due to my limited knowledge of Arduino workings I need some help. I'm trying to use button outputs from a PS360+ arcade controller. Each of the button terminals output +5V, and is meant to be connected through a button to the grounds on the PS360+.
  What I want to do is have an Arduino somewhere in between the button output and ground on the PS360+, to control and animate LEDs. What I've done so far is connect the VCC of the PS360+ to the Arduino's VIN and the ground of the Arduino to the PS360+'s button ground, which powers the Arduino. I then have a button output from the PS360+ going into the button, and the button's ground is connected to an Arduino pin. That Arduino pin's mode is set to INPUT. I then have another pin with an LED which is set to the value of the input pin.
  For some reason, the Arduino seems to get random input from the button(Though it does seem to react somewhat to buttons presses), and the PS360+ does not recognize the button press. Setting the input pin to pullup mode has even less result, and never reads low.
Anybody got any ideas? Here's my current circuit diagram. 1P is a +5V output. I think that it's an internal pull-up pin like the Arduino's, but I am not certain.

And my current code:

int buttonlisten = 22;
int led = 53;
int val = 0;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(buttonlisten, INPUT);
}

void loop() {
  val = digitalRead(buttonlisten);
  digitalWrite(led, val);
}

Thanks!

I think the idea of putting the arduino between the button and ground is the problem here — 1P appears to be the input for the controller button, and you can't expect to take an 'input' from the button on both pins at once.

Try connecting one lead of the button back to its ground, and the other to 1P (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as INPUT_PULLUP.

This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share GND) when the button is pressed.


AnalogRead(0) always returns 0 on RFduino I'm using RFduino to do analogRead at pin 2 and pin 0. Pin 2 works perfectly, and I got the result. However, for pin 0 it returns all zero.

#include <RFduinoBLE.h>

static const int topPin = 2;
static const int bottomPin = 1;

int top;
int bottom;

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

void loop() {
  // put your main code here, to run repeatedly:
    RFduino_ULPDelay( SECONDS(0.01) );

    bottom = analogRead(bottomPin);
    top = analogRead(topPin);

    Serial.print(top);
    Serial.print(" ");
    Serial.print(bottom);
    Serial.print("\n");
}

I double checked the wires and it's OK. I measured the voltage across pin 0 and it's 3.3V. How do I fix this problem? There's no shortage between pin 0 and 3.3V.

Without RFDuino specs handy, I'm guessing - but I think it's likely - that the A/D converter gets shut down in an ultra low power sleep and requires some amount of time to wake up. The mis-reading pin, pin 0, is the one your sketch reads immediately on waking. That read call probably takes long enough that the A/D wakes up by the time your read pin 2 so it gives a better reading.

Try switching the order in which you read the pins and see if pin 2 mis-reads if you try to read it immediately after waking. If it does, the cure may be as simple as a 10-100 uSec delay between waking and trying to read any analog data. I just pulled that number out of the air; you might start with a couple of milliseconds and see how low you can make it before you start to see errors, then double that amount.


Use doorbell output (12VDC) to power arduino? Not sure if this is possible, but could I use my existing doorbell setup to power an Arduino? I'd also like to preserve the existing chime's functionality either through the existing button or triggering it through the arduino.

My doorbell chime is made by Nicor and its input is 120VAC, but outputs 12VDC. This seems to be a very unconventional setup, but I've confirmed its output with a multimeter (it's also printed on the chime itself). The chime is very similar to this: http://www.amazon.com/Nicor-18888-Door-Chimes/dp/B006T38PTU (only difference I can see is the output). The 12V line runs to my front door where it's connected to a light up button. Here is a picture of the button's circuitry: http://imgur.com/IjA50rT

What I'd like to do is use the chime's 12VDC output to power the arduino so I don't have to rely on another power source or batteries. I will be adding smart features to the doorbell via the arduino, but my main hangup is getting power to the arduino. I've tried connecting the doorbell wires to VIN and ground, which successfully powers on the Arduino, but it also triggers the chime. It appears closing the circuit triggers the chime to play.

Is this possible to do?

This seemingly simple task is actually quite complicated; a good challenge that's not impossible or easy to overcome.

The AC/DC transformer in your link only provides "12VDC/6mA"; not enough to run the Arduino, chime, and button LED; so it likely needs upgraded to something beefier; you can't have too many amps on such a transformer.

Then there's your chime, which could use a lot of current (buzzer/bell) or a little bit (speaker-based chime tones). If it uses a lot, you should replace it to simplify the other connections. Remember that power goes through the chime to get to the button; otherwise the circuit would be incomplete and the ringer's LED would be dark.

The chime is activated by the resistance of the button lowering itself to the point where the chime gets enough power, no longer being current-limited by the diode, 2.2k resistor, and small LED. Very simple design, but not ideal for easily intercepting.

So what's the easiest way to accomplish your task?

Looking at it closely, it seems the basic circuit is there for you already; you have a power-consuming node on the network in the form of the button's LED.

You need to replace/augment the LED on the ringer with the Arduino. The 2.2k R19 could/should be replaced with the Arduino as well; just make sure your LED isn't over-drawn when the Arduino is chugging at full-steam, and add additional inline resistance as needed to keep it safe.

The other problem is powering the MCU while ringing. You'll notice the LED goes out while ringing. While that's nice feedback to the user, it's not because the circuit designers were UX-focused, it's because the chime's simple circuit  pulls all the current out from under the LED, just as it will an MCU in the same slot.

You can get around this using a super capacitor. I would use an LM7805 in front of the Uno to deliver VIN +5 V instead of 12 V. Then you can "short" the Uno's GND to VIN with a 1 F 5.5 V capacitor ("F", NOT "uF"). Those caps are (amazingly) available for just a few dollars on eBay.

So, at the end of the day, you basically just need to "upgrade the LED" and maybe upgrade the transformer. You could also re-create the switching pattern on your ringer with diodes if you're handy with circuit design, but if i were you, i would just "bodge" a few wires onto the existing PCB, and possibly alter that resistor.

Good luck; sounds like a fun project and a good challenge.

EDIT:
I realized you might not need any circuit mods at all; a hall-effect current sensor anywhere the line, or just paralleling the chime terminals with a voltage-divider input to the Uno might suffice, if you didn't need the MCU physically at the button. Heck, a microphone sensor taped inside the chime could accomplish the task of detecting doorbell rings...


Varible Ramp up speed for motors controlled by joytstick I trying to create a piece of code which will ramp up the motors speed to a changing value controlled by a joystick. For example joystick requests 120 speed to motors so instead of going 0 to 120 it goes 0, 10, 20 …. 120. But the maximum value will constantly change between 0-130 so it needs to ramp up each time.
This is a snippet of my code to run the motors in the forwards direction.

{
  motorControl = analogRead(joystick);
  motorControl = motorControl / 4;
  if(motorControl > 129)

{

    digitalWrite(pwm2, 0);
    digitalWrite(pwm3, 0);
    speedI = (motorControl - 130);
    speedFadeI =
    Serial.println(speedFadeI-130);
    analogWrite(pwm1, (speedFadeI - 130));
    analogWrite(pwm4, (speedFadeI - 130));

thank you for anyone who has a idea

I assume from the 0, 10, 20 …. 120 series, that you want to have a linear ramp to the desired speed. This can be done really easily, if your requirements are not to high.

First we define the interval, in which we want to update the speed, and a constant acceleration, that you can choose. The current speed will be saved in a global variable.

#define INTERVAL        100
#define ACCELERATION    51
int current_speed = 0;

I chose an interval of 100ms and the acceleration value, so that it will ramp from 0 to 255 (full speed) in 5s (which results in 51 PWM values per second). Now, in the void loop() function, we use an if-statement with the millis() function to trigger an speed update at the regular interval. For this to work, we need a (here global) variable, that holds a timestamp. (If you don't know this technique, you can see it in the BlinkWithoutDelay example, that comes with the Arduino IDE, and there are many tutorials about this on the web)

Inside the if-statement, we write a second if-statement. It checks, if the current speed is above or below the set point, that comes from the joystick. If it's above, we will substract one speed step (calculated by acceration and interval and divided by 1000, because we used milliseconds and not seconds for the interval), if it's below we will add one speed step.

unsigned long timestamp = 0;

void loop(){
    int setpoint = analogRead(joystick)/4;
    if(millis() - timestamp > INTERVAL){
        if(current_speed > setpoint){
            current_speed -= ACCELERATION*INTERVAL/1000;
        } else {
            current_speed += ACCELERATION*INTERVAL/1000;
        }
        if(current_speed > 255) current_speed = 255;
        else if(current_speed < 0) current_speed = 0;
        analogWrite(pwm1, current_speed);
        timestamp += INTERVAL;
    }

I also added if-statements to cap the current speed between 0 and 255. Otherwise the value would overflow, when written to the corresponding 8-bit timer register by the analogWrite() function.

Of course, this method also has drawbacks. You will have to find a good value combination of ACCELERATION and INTERVAL, because when the current speed reaches the setpoint, it will oscillate around this value. The best way is to set the ACCELERATION, that you need, and choose a good interval based on that.

There are other ways to program this, but I like this way for being really simple.


GUI interface with microcontroller to control a device through SPI I am trying to develop a GUI to control a device hooked up on the Arduino. The Arduino communicates with the device through SPI. I have developed a GUI on MATLAB to visualize read by the Arduino. For this, I made Arduino write data from the MISO line to the serial port and MATLAB would read from the same port and do its magic. However, I am trying to come up with a method to write to the MOSI line using the GUI.

Right now I am thinking of making Arduino listen for a particular code (like a character) on the serial port and once it sees it, it will look for an x number of succeeding bytes. The bytes will be formatted in a particular way so that Arduino can then parse it and write to the appropriate registers.

Is there a better way to do this? As a generic question, what's a good way to write to a device hooked onto a microcontroller using I2C or SPI through a GUI?

I grappled with the same question for a while. Here is how I solved the issue.

1- Find a suitable exchange format and protocol

Here you need to decide what is the most important thing on the communication. Is it speed? Is it error detection? Is it memory footprint? For my project, for instance, I decided that I need my communication to be as error free as possible, with minimal memory footprint (up to 64 bytes) and I don't really care about speed, so I gone for a JSON messaging protocol where the desktop application send a short (up to 64 characters) JSON message and receives a short answer. This solved MY problem, your requirements might be different. If you need speed and don't care for memory, for instance, you can use a binary protocol with a header specifing size, the message and a CRC footer to check vailidity. Or you can use BSON and take this library to avoid the hassle.

2- Define the Serial Polling Cycle
How will the arduino firmware knows it is time to send or receive messages? It is always talking? Always ready to receive? It looks at the serial port buffer once each few microsseconds to know if there is an incomming message? How that is handled by your device? If you just need to output data without bothering whether there is someone listening or not, like an GPS device, just throw a Serial.print now and then, but if you need to wait for data, you will have to compartimentalize the process inside an FSM or using some kind of scheduler. If you are not using a scheduler, I recommend this one.

3- Define the Communication Cycle
Here you will take the data from serial port and storing it on a buffer for later usage.
The trick here is
1- Check the serial FIFO for incomming data. Serial.available() does it already.
2- If there is incomming data, copy the data to next available space in the buffer.
3- Check if there is more incomming data after a few millisseconds.
4- If there is no incomming data, mark the buffer as ready to use, and parse it.

The following code is unscheduled for simplicity,and I recommend you to replace the sleep() calls to proper scheduling least you want the arduino go unresponsive. It is also waiting text data, so you will need to make changes if you are waiting binary data.

  char buffer[64];
  memset(buffer, 0, 64);

  while (!Serial.available())
    delay(50);

  while (Serial.available()){
    Serial.readBytes(buffer + strlen(buffer), Serial.available());
    delay(50);
  }
  parseBuffer(buffer);


MFRC522: Firmware Unknown Can someone help me what is the meaning of this sketch? It always outputs in the serial monitor:

Firmware Version: 0x1C = (unknown)
Scan PICC to see UID, SAK, type, and data blocks...

This is the code of the MFRC522 library I use:

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

constexpr uint8_t RST_PIN = 9;          // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;         // Configurable, see typical pin layout above

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

void setup() {
   Serial.begin(9600);   // Initialize serial communications with the PC
   while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
   SPI.begin();      // Init SPI bus
   mfrc522.PCD_Init();   // Init MFRC522
   mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
   Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
   // Look for new cards
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
     return;
   }

   // Select one of the cards
   if ( ! mfrc522.PICC_ReadCardSerial()) {
     return;
   }

   // Dump debug info about the card; PICC_HaltA() is automatically called
   mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

The mention of unknown in the output line:

Firmware Version: 0x1C = (unknown)

isn't a good sign.

Run the firmware_check example to verify that first, before trying to run other code.

The unknown is output by line 1302 of MFRC522.cpp:

    default:   Serial.println(F(" = (unknown)"));

The firmware_check example states on line 49:

  Serial.println(F("Only known versions supported"));

So, your hardware (i.e. the reader) may not be supported.

The only thing I can suggest is try another reader. Also, read the README, there maybe some thing there, or contact the author and/or raise an issue to see if you can get support for your version of the firmware (0x1C) added.


expected primary expression before ')' token #define ANALOG_IN 0

void setup() {

  Serial.begin(19200);

  analogReference(INTERNAL);

}

void loop() {

  int val = analogRead(ANALOG_IN);

  Serial.print(0xff, byte);

  Serial.print( (val >> 8) & 0xff, byte);

  Serial.print( val & 0xff, byte);

}

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.

Why are you putting byte there? That isn't in the Serial.print reference page.

This compiles OK:

#define ANALOG_IN 0

void setup() {
  Serial.begin(19200);
  analogReference(INTERNAL);
}

void loop() {
  int val = analogRead(ANALOG_IN);
  Serial.print(0xff);
  Serial.print( (val >> 8) & 0xff);
  Serial.print( val & 0xff);
}