Servo motor (HSR-1425R) not running continuously

Look at how servo motors are typically controlled. As far as I know there are no servos that can just be "enabled to rotate" like you seem to expect.
Usually a servo's position is set by applying a pulse of a specific length. This means you can apply a PWM signal with proper frequency. Then the duty cycle should be proportional to the servos position. From my experience timing is quite critical when controlling a servo, so going the way you do (timing a gpio's output state with delay()s) will not work well. You have to use the atmega's hardware modules (which already is the case when using the arduinos digital write) to achieve adequate timing.


Please tell me if it is broken and how to fix it.

See Have I bricked my Arduino Uno? Problems with uploading to board

Those tips may also help with fixing problems with your Mega (if you ever have them). ;)


The voltage at any input must be less than VCC+0.3V unless it is restricted to only a few milliamperes (so it doesn't burn out the clamping diode). Use a proper voltage translator if it is available, otherwise use a 1kohm or greater resistor (at the cost of life expectancy for the MCU).


How can I convert Arduino String to C string type?

Try

unsigned char z[100];
IP.getBytes(z, 100);
z[IP.length()] = 0;
int n = atoi(z);

To retrieve bytes inside the string. This assumes IP string's length is shorter than 100.


Fading red to white to blue continuous loop on ws2812 LED strip

Think of a color as a point in 3d as defined by its r g b attributes

Think of two points here, one is your starting color in that 3d space, and another your ending color.

Figure out the path you want to take from the starting color to the ending cokor.

Chop it up in a few steps and use your code to walk the path.

Done


You'd have to test this but there's a chance you could supply the Arduino using a DC power supply on it's 5V pin. In this case DO NOT TURN YPUR SUPPLY HIGHER THAN 5V, as I don't believe there is any protection and will send the full voltage to the USB.

A safer option would be the Vin pin. Normally you'd want to put 7-12 Volts to this pin but you may want to start at 5V and work your way up just to be safe.

Someone please corrects if I am wrong, but if you never apply more than an external 5V your worst case scenario would be burning out the Arduino but not the USB device.


There's a few similar projects already done on YouTube, which you can use for guidance. If this is your 1st project using arduino I would recommend the Uno as is the easiest to work with. As you become more familiar with microcontrollers you can easily switch to the nano.
As for what sensors you decide to use is up to you. You have quite a bit of flexibility. Check out Adafruit and arduino websites for ideas. What you choose to go for would depend on the specifics of your project, which a bit vague in this post.


You are using Timer/Counter 1 in Fast PWM Mode with TOP set to OCR1A:
OCR1Aonly describes the number to what it counts up so, 0…391 in your case.
You have to define the duty cycle with OCR1B. 50% would be 195.


How to control Arduino using mBlock and Bluetooth?

When I connect HC-05, should I connect Tx to Tx OR reverse them?

  There are varying articles describing both ways of connection.

Yes, swap them. TX on the HC-05 to RX on the Arduino. However you could struggle to use pins 0/1 since they are the USB connection. SoftwareSerial (which is nasty) is what most people use instead.

  How much baud rate do I need to set on the bluetooth device?

Whatever rate you want to communicate at. It's up to you. However all baud rates must match throughout the system - the baud rate on the Arduino, the baud rate of the HC-05, the baud rate of the SPP port on your PC, etc.

  Do I need to use the voltage divider for Rx? Again there are varying tutorials.

Which RX? Arduino TX to HC-05 RX yes. HX-05 TX to Arduino RX no.

  Is mblock default arduino firmware sufficient for such a setup?

What is mblock?


Try to use this code:

// Graphing sketch

import processing.serial.*;

Serial myPort;        // The serial port
int xPos = 1;         // horizontal position of the graph

void setup () {
// set the window size:
size(400, 300);

// List all the available serial ports
println(Serial.list());
// I know that the first port in the serial list on my mac
// is always my  Arduino, so I open Serial.list()[0].
// Open whatever port is the one you're using.
myPort = new Serial(this, Serial.list()[0], 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}

void serialEvent (Serial myPort) {
// get the ASCII string:
String inString = myPort.readStringUntil('\n');

if (inString != null) {
// trim off any whitespace:
inString = trim(inString);
// convert to an int and map to the screen height:
float inByte = float(inString);
inByte = map(inByte, 0, 1023, 0, height);

// draw the line:
stroke(127,34,255);
line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning:
if (xPos >= width) {
xPos = 0;
background(0);
}
else {
// increment the horizontal position:
xPos++;
}
}
}

Also look at: http://www.arduino.cc/en/Tutorial/Graph


Purpose of extra holes for pins or Arduino clone

It's what they say they are.

SDA/SCL are I2C - what used to be A4/A5 on the old footprint. On the '328 based boards those are directly linked to the A4/A5 pins.

The blank pin isn't used. The 5V next to it is actually mislabelled and should be labelled "IOREF".

AREF has been there since the very first Arduino boards.

It's the standard "R3" Uno footprint, plus some extra breakouts for the I2C in different forms (probably to go with specific I2C devices they also sell).

All of that is on the Uno's product page if you'd care to read it some time...

The ones by the cheap Chinese USB interface chip will be something to do with that. Maybe RTS/CTS broken out on a header. You can ignore those - they are of no interest at all. In fact, just looking in their direction has a good chance of breaking the USB interface chip. Stay well away.


Use Arduino Mega to program Arduino Duemilanove

Yes, this is not an uncommon activity.  This is called using an Arduino as an In-System Programmer (ISP)

This page has the information and Arduino program you need.  You'll need to adjust for the Arduino Mega pin differences, but that's fairly easy.
http://arduino.cc/en/Tutorial/ArduinoISP

Where the ArduinoISP page references pin 13, on the Mega it's pin 52.
Where the ArduinoISP page references pin 12, on the Mega it's pin 50.
Where the ArduinoISP page references pin 11, on the Mega it's pin 51.
Where the ArduinoISP page references pin 10, on the Mega it's pin 53.

Otherwise you should be able to connect the Mega to the patient in the same way as described, load the ArduinoISP sketch into the Mega, preferably from the GitHub repository linked in the article (https://github.com/rsbohn/arduinoisp).


Running two NEMA 17 motors, one by one, using the Arduino Uno

A minor issue that probably won't affect your result is that

Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");
--> digitalWrite(9,LOW);  // This line 'needs' adding
digitalWrite(7,HIGH); // Set Dir high for y

I can't see anything in the code that will prevent the motors running, OK it will take ~13 seconds to start moving, but it should move.

So - without any hardware attached to the motor spindles - is it possible to switch the motors over to check for a wiring breakage issue?  With one motor working and one not it implies to me that either the motor is broken, the wiring is broken or the driver circuit is broken.  If the fault moves then its a motor/wiring fault if it stays the same then its a driver fault.


Judging by the comments, you are actually receiving your integer data as text, as a sequence of ASCII characters. This is what you send yourself using mosquitto_pub. The buffer is apparently not zero-terminated.

If these characters represent an integer value, then the way to retrieve it as an integer value would be

char buffer[128];

// Make sure here that `length` is smaller than the above buffer size.
// Otherwise, you'd need a bigger buffer

// Form a C-string from the payload
memcpy(buffer, payload, length);
buffer[length] = '\0';

// Convert it to integer
char *end = nullptr;
long value = strtol(buffer, &end, 10);

// Check for conversion errors
if (end == buffer || errno == ERANGE)
  ; // Conversion error occurred
else
  Sterial.println(value);

Another approach, which avoids using a separate large[ish] buffer just for the purposes of zero-termination, would be

// Build a `scanf` format string that will read no more than `length`
// characters without relying on zero-termination of the payload
char format[16];
snprintf(format, sizeof format, "%%%ud", length);

// Convert the payload
int payload_value = 0;
if (sscanf((const char *) payload, format, &payload_value) == 1)
  Serial.println(payload_value);
else
  ; // Conversion error occurred

However, this approach is less protected from integer overflow than the previous one.

Note that most of the above "jumping through the hoops" is dedicated to adding a zero-terminator to the input buffer. If instead you opt for ensuring zero-termination on the sender's side, then it would all reduce to a simple

// Convert C-string to integer
char *end = nullptr;
long value = strtol((const char *) payload, &end, 10);

// Check for conversion errors
if (end == buffer || errno == ERANGE)
  ; // Conversion error occurred
else
  Sterial.println(value);

No extra buffers required.


It should be perfectly possible to do it. As long as the SD cards and shields play ball then there should be no problem from a hardware perspective.

From a hardware perspective you should be able to share the MOSI, MISO and SCK lines and just have separate CS pins per card.

However some SD card shields employ level translation that doesn't properly release the SPI bus when idle, and some cheap SD cards don't release the bus in a timely manner too.

From a software perspective though it may be a different matter. I am not sure how well you can run two instances of the SD classes at once on an Arduino.  You may be better off looking at FatFS instead which is far more flexible.

You have two strategies when copying cards, each of which has a different way of programming it.

Block copy the entire card: this involves reading a 512 byte block from one card and writing it to the other one.  This would be the most efficient from a resource perspective (you don't need to care about the contents of the card, so don't need any filesystem code), but if the card is not close to full it will be very inefficient from a runtime perspective. Also the two cards have to be the same size for it to work well.
File copy. For this you need much more complex code, but it you only copy each file from one card to the other. It's much better though if the cards don't have much data on them - also the cards can be different sizes.


is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together?

Yes, that is perfectly possible.  Typically:

Accelerometer is either an analog, SPI or I2C interface.
GSM is usually a UART interface
The Arduino UNO has all four interfaces (analog, SPI, I2C and UART) available on separate pins.

The rest is just a SMOP.


It can take a while for a modem to register on the network - sometimes several minutes.

Turning on CREG URCs can help you monitor what is happening:

AT+CREG=1

You should now start getting +CREG notifications as the network status changes.

Before using AT+COPS? you should really select a reporting mode so you know what you are looking at. I prefer numeric, since it's easier to parse:

AT+COPS=0,2

That will switch to automatic registration and reporting as numbers.

AT+COPS?
+COPS: 0
OK

That is not registered.

AT+COPS?
+COPS: 0,2,"40404"
OK

That is registered on a network with ID 40404.

The +CREG reports tell you what is going on:

+CREG: 1

That tells you that you have just connected to your home network.

If you are roaming, you would see:

+CREG: 5

Of course, if your home network is not available (say you have an AT&T SIM and only Verizon is visible at the moment), and your SIM doesn't have roaming enabled, then registration will never work.  You'd expect to see +CREG reports of:

+CREG: 2
+CREG: 3
+CREG: 0

That is "trying to register" (2), "registration denied" (3) and "doing nothing much now" (0).

The best document for learning about these commands is the 3GPP Command Set which is the standard that all modern GPRS modems should adhere to.


Velocity from Sensor Data - Best Approach?

Welcome to the world of signal processing! (Starting off with a Kalman filter, though, is not very welcoming).

The first few things to address are in regard to the barometer:

(1) Inevitably, it's going to be noisy, and barometers in particular are known to be noisy. Considering the unfiltered data you posted, I'd say it's reasonable. The spikes are completely normal, especially being that your calculating the derivative from the barometer data. If you want to try to smooth the barometer data before passing it to the Kalman filter, you could apply a nth order low pass filter to the sampled data. This, of course, would add more lag to your calculations - it's really a trade off.

(2) Looking at the unfiltered data and the velocity calculated from the Raven, it appears that there might be an issue. Starting at time 0, the unfiltered data and the Raven data is nearly identical. Once the rocket reaches 180ft/s, though, the filtered data appears to diverge. After it passes the global maxima and hits 180ft/s again, the two data outputs start to converge. This makes me suspect that your sampling rate may be too low. A hard-core, by the book, DSP engineer will probably start crying when he reads this, but consider this: at a velocity of 180ft/s with a sample rate of 20S/s, each sample corresponds to a change in position of 9ft. So, at best, you have a resolution of 9ft per second. This can pose at least two problems. (1) The barometer has to continuously update temperature and pressure readings in order to calculate an accurate altitude. I only glanced at the datasheet, but it seems like the temperature (and I think one other parameter) is updated at a slower rate than the pressure sampling - that is, there's an oversampling factor for the pressure measurement. Hence, your calculation may start to diverge from reality. And as the rocket's velocity increases, this problem may be exacerbated. Of course, temperature changes at rate of about 9.8C/1000m, so it may not be that significant of an issue. Just wanted to throw it out there.  (2) Again, at 180ft/s with a 20Hz sampling rate, you basically have a resolution of 9ft/S. This isn't necessarily bad, but one thing to keep in mind is that a Kalman filter is predictive; it predicts the state of the system 1/20 of a second into the future. If your underlying model is off, this could lead to slower convergence and larger corrections that would make the filtered data look "jerky."

Just one more thing before we get into the filter...

It's worth considering how you're implementing this on the Arduino. There shouldn't be any issues with computation time that could result in significant lag. If your only sampling the altitude at 20Hz and then feeding it to the filter at the same speed, you should be good to go. The only issue I can foresee is if you're using the Arduino Libraries. If you are, you'll probably run into bottlenecks and missed deadlines.

Anyway, the primary issue you're having - in my opinion - is not related to computational speed or hardware issues. Instead, I suspect it's your implementation of the filter.

One thing that stood out to me were your values of R and Q. R is the measurement noise covariance, and Q is the process noise covariance. Covariance ranges between [-1, 1]. Your Q = 5. I quickly scanned the link you provided, so I might have missed a simplification they did. I've seen in some cases that the covariance is simplified to a proportional expectation value and left unnormalized, similar to what's seen in Gram matrices.

Regardless, here's some insight that may be useful:

The Kalman filter is very much dependent on how you model your system.

To illustrate this, let's consider an example analogous to your rocket. (I came across this example at some point, but I don't recall the source):

Say you want to measure the water level in a bucket, but you have a sensor that gives you noisy data. And of course, to filter the data, you decide to use a 1-D Kalman filter.

We assume that we have a pretty accurate model of our system, so we'll let Q = 0.001. We iterate through the filter, and we may get data that looks like this:

The filter works fairly well.

But what if our model happened to be off - that is, it doesn't reflect what's really happening?

In the image above, the water level was constant. In reality, perhaps the tank was filling at a constant rate. What happens now if we use the same filter?

Clearly, the filter is diverging. The lag, as you call it, isn't really lag or a delay in the sense that the computation is slow. (In some ways it is a delay, but only in the mathematical sense that the filter is slowly converging). The "lag" effect we're seeing is due to our model. In essence, the filter we designed thinks our model is so good (as indicated by our low Q) that it gives greater weight to our model of the system. As you probably guessed, one way we can fix this problem is by increasing Q. So, let Q = 0.1:

You can keep increasing Q, and when Q = 1, your filtered data should actually match your measurement data.

This, though, really ins't the best way. Ideally, you need to start with a relatively accurate model. Q can be thought of as a measure of the error in your model, and you want to minimize error. At this point, you'll inevitable need to start work with matrices. This won't increase "lag." In fact, it should help your filtered data converge quicker.

There is one more thing to note. Kalman filters prefer linear data (speaking generally here). Look what happens when you feed in nonlinear data:

To accurately and effectively apply a Kalman filter to non-linear data without such pronounced "lag",  you need to use what is known as an extended Kalman filter - which basically linearizes your data.

Before you go down that route, which would probably be overkill, I would suggest improving your model used in your Kalman filter to better reflect it's true state. This means ditching the simplified filter you found and going into the matrix math.

In any case, I hope this helped. Feel free to ask any questions.

(Another method just crossed my mind that may be a simpler approach than a Kalman filter. I'll add it tomorrow).


You would indeed need to use analogWrite to send a PWM signal to the motor. PWM will turn on and off the power to the pin really fast. In effect powering the motor with pulses. The length of these pulses will determine how much power the motor receives.

The DUE also has a true analog output, but you don't want to use that for motors. The use of the word analogWrite is a bit misleading when it's used for generating a PWM signal.

analogWrite will ask for a value between 0 and 255 to indicate the pulse length. 0 is OFF, 255 is full ON, 127 is ON for 50% of the time.

Also note that most motors require more current that the Arduino pins can provide, so you need to use a transistor/mosfet to "amplify" the signal to a higher current.


There is nothing wrong with your code. But it could use some cleaning to make it efficient.

The code at the moment will be 'deaf' to any user inputs for twenty seconds between light changes.

This can be fixed by using a timer interrupt and changing the lights every 20 seconds and listen for other inputs or do other things. You can use the arduino timer library, this is well documented and you should be able to find examples of its use. Basically you would monitor a variable until it reaches a point and then trigger the lights.

The other option would be to use the millis() and every 20 seconds change a light, but do stuff between those 20s. This can be done like this:

unsigned long previousMillis;  //hold the previous time
unsigned long currentMillis;   // hold the current time

long threshold = 20000;
int count = 0;

int pins[] = {13, 14, 15};

//setup code stuff

//put the following at the top of loop()

currentMillis = millis();

if(currentMillis - previousMillis > threshold){

    previousMillis = currentMillis;

    for(int i = 0; i < 3; i++){
    digitalWrite(pins[i], LOW);  //turn off all

    }

    if(count > 2) count = 0;

    digitalWrite(pins[count], HIGH);

    count++;
}


Question regarding Servo including Serial monitor display

So what you want to do is be able to activate the servo when 4 green bars appear over the course of one minute correct?

I think you would need to create three if statements and one new variable. The first if statement will be, if it detects four green bar, then m=(millis() + 60000). Then you will need to nest another if statement in here to say if it detects ONLY three bar, then m = 0.
Your third if the statement is if it detects the four green bars AND m == millis() then the servo will activate.

This is how I would do it, but I am not very experienced. I'm pretty sure others will have a cleaner and simpler code but this should work.


How do I connect my Luxorparts keypad to my Arduino?

There's a guide here that helped me out: Keypad Tutorial, that will show you the means of figuring out how the keypad is wired. I followed it and figured out that for that specific keypad (the Luxorparts keypad) the setup is as follows:

(From left to right on the keypad pins and on the rows and columns)

Pin1: Not connected
Pin2: Connected to the 2:nd collumn
Pin3: Connected to the 1:st row
Pin4: Connected to the 1:st collumn
Pin5: Connected to the 4:th row
Pin6: Connected to the 3:rd column
Pin7: Connected to the 3:rd row
Pin8: Connected to the 2:nd row
Pin9: Not connected

I modified the example code from the link above to reflect this specific Keypad:

#include <Keypad.h>

const byte ROW0 = 3;
const byte ROW1 = 8;
const byte ROW2 = 7;
const byte ROW3 = 5;

const byte COL0 = 4;
const byte COL1 = 2;
const byte COL2 = 6;

const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'#','0','*'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = { ROW0, ROW1, ROW2, ROW3 };
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = { COL0, COL1, COL2 };

// Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

#define ledpin 13

void setup()
{
  pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);
}

void loop()
{
  char key = kpd.getKey();
  if(key)  // Check for a valid key.
  {
    switch (key)
    {
      case '*':
        digitalWrite(ledpin, LOW);
        break;
      case '#':
        digitalWrite(ledpin, HIGH);
        break;
      default:
        Serial.println(key);
    }
  }
}

To run that, simply connect each pin from the keypad, in order, to the arduino, so the second pin from the keypad goes to the second digital pin on the Arduino and so on.

I asked the question after I'd already figured out the answer in hopes of helping anyone else who bought that specific keypad.


Correct connections: 7-segment, 4-digit display with common anode

That circuit looks OK to me.  It will allow you to light (reliably) a single segment at a time.  The A* pins will be used in digital output mode.

The A* pins are connected to the four anodes of the digits - each digit has common anodes for all the segments.  They should be driven HIGH to 'select' a digit.

The D* pints are connected to the cathodes of each segment.  They should be driven LOW to light that segment.

For example, to light the 'A' segment of the first digit, you would set:

A1 HIGH, to drive the anode of the first segment
A2, A3, A3 LOW, so that the other three segments are not driven
D5 LOW, so that current flows from A1 to D5, lighting the digit
D6-D12 HIGH so that no current flows from A1 through any of the other segments.

The expectation is that you will cycle around (very fast), lighting each required segment on each required digit in turn.

Without a (proper) data sheet we can't tell you what the correct resistor value is, but the 220R shown is probably OK.


Not able to receive the operation results from the slave after the command being sent by Master - SPI

Since I wrote that example, I'll try to answer this. First I tested with the code from my page about SPI.

SPI Master

This is the master:

#include <SPI.h>

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

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{

  byte a, b, c, d;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Adding results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('s');  // subtract command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Subtracting results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  delay (1000);  // 1 second delay
}  // end of loop

SPI Slave

And this is the slave:

// what to do with incoming data
volatile byte command = 0;

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;

  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}  // end of loop

Test results

Testing gave the expected results:

Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

So, what is different in your code?

Your slave ISR:

ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }

This isn't quite the same, is it? In my code you get the command in one session (one interrupt) and what to use it for in another one.

Hence I had this:

  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

Sending a "command" of zero clears the current command. So the sequence being sent is like this:

0    <-- start a new command
command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55

Perhaps confusingly, I didn't send in that order, because I knew that the command would be zero initially(1), so I actually sent:

command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55
0    <-- start a new command

There would be other ways of achieving this, but the fact is you changed the way the slave interpreted the incoming data.

I knew it would be zero because the slave sets the command to zero in the main loop if SS is not asserted.


Adafruit Motor Shield and Bridge Library for Yun Shield

Looking at Bridge.begin() description here
 you can see this is blocking function.

  begin() is a blocking function. Once you call Bridge.begin(), nothing else will happen in your sketch until it has completed. This process takes approximately three seconds.


Your first snippet is the correct solution.

pinMode(pinnumber,OUTPUT)
digitalWrite(pinnumber,LOW)

Be careful though, you can only sink up to 6mA or 9mA per pin (as per the documentation ["Input and Output" section], I never tried more). If you need more current, use a transistor (this looks like a good example, you just need to invert the output pin to HIGH).

When the pin is configured as input it is supposed to be high impedance, not what you want.


Sending data using Bluetooth SPP-C Module without a Breakout-Board

I found a solution myself.
The modules are working as they are supposed to and are not faulty.
Also I did nothing wrong.

The Problem are my development machines. Mac mini (Late 2009) and MacBookPro (Mid 2009), both having a Broadcom 2046 Bluetooth host chip. I used those to connect via Bluetooth and open a tty session using minicom. Running macOS and using "Hardware IO Tools" to log Bluetooth packets I saw that there was clearly nothing coming in.

After that I turned over to my Windows and used Hype! Terminal. Everything worked!

Then I went to my Raspberry Pi and Linux. After pairing using bluetoothctl and issuing a few commands from Bluetooth as ttyUSB. Everything worked as well.

Then I tried BlueSPP on an Andriod phone. And again, it worked as it was supposed to.

So my conclusion is that there is some sort of incompatibility between the SPP-C module and the Broadcom 2046 host controller.


How to create a 1 hour timer with ATtiny13A microcontroller?

As the unchanged blink sketch blinks with 8.4 seconds, I think my assumption is right. The clock of the Attiny is running 8 times slower, than the code thinks.
When you have installed the Attiny core, there should be a menu entry for the clock frequency. Most likely the standard is 8MHz. But having 8MHz set does not mean, that the Attiny is using 8MHz. To choose between different clock sources and frequencies, you must change the fuses of the microcontroller (which are just some bits of special non-volatile memory in the chip, that set special hardware configuration; more information in this question). This is done, when you burn the bootloader to the chip. That's the easy version. Alternatively you can use the avrdude command directly to set the fuses. That's the advanced way.
Currently the fuses of your Attiny seem to be set to the 1MHz internal clock. But the compiler uses the frequency, that you have chosen in the menu, hence 8MHz internal clock. So the compiler thinks, that the chip runs at 8MHz and thus generates the timing code for this execution speed. But your chip is currently 8 times slower, than the compiler thinks.
TL;DR: Burn the bootloader onto the chip to let the Arduino IDE set the right fuses for your clock frequency.


Bluesmirf Mate Silver (RN-42) enter command mode when in HID mode

I believe that the problem is caused by the mode I entered. According to the datasheet on pg 10 Auto-Connect Master Mode (SM,3) enters high speed mode and this connection cannot be broken via commands or software break characters.
It goes on to explain that both Auto-Connect DTR Mode (SM,4) and Auto-Connect ANY Mode (SM,5) (which I used) function like Auto-Connect Master Mode (SM,3), so I guess that in these modes the $$$ escape characters cannot be used to enter command mode either.

I was able to resolve this by performing a hard factory reset on the Bluesmirf Mate Silver (RN-42). I previously tried following a couple of you-tube tutorials that weren't very clear and didn't have any success. I looked at the instructions in this thread titled 'Factory Reset the RN-41 or RN-42' to get me on the right lines.

This worked for me:

Connect the Bluesmirf Mate Silver GND pin to GND and disconnected all other pins
Connect a wire to 3.3v on Ardunio
Load the Ardunio with an empty sketch, and keep it powered on
Touch the 3.3v wire repeatedly (3+ times) to the GPIO4/PIO4 connection hole on the Bluesmirf. This is a third of the way down one edge of the board.
Factory reset should now be complete - note I didn't see any indication lights during this process.

Then I could wire up the Bluesmirf as normal and use ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.


make servo stay at the current position when attach() is called

You can't read the servo's position, so your sketch has no chance to know the real current position.

And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.

So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"

You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.

Some ideas how to "get better":

Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
Add a circuit that detects the power loss before the CPU stops. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.


Having problems registering my SIM800 with the network

I think you are not giving it enough power, SIM800 module needs 5v/2A stable power source in order to register to network. Try to use a desktop computer power supply it has 5v/2A output wire (refer to colors).


AttachInterrupt - fail to initiate inside a class

Firstly, if detection_door is a non-static member function, then C++ simply has no such expression syntax as just detection_door. Such functions have to either be called (with () operator) or be taken address of (with & operator). You can't just say detection_door. That's meaningless, which is what the compiler is telling you.

Secondly, as you already realized, regardless of the syntax a non-static class member function cannot be used as an interrupt handler. You need a freestanding ("ordinary") function as a handler or a static class member. Non-static class methods are beasts of completely different and incompatible nature.

I see that you have multiple ledDoor objects that you want to attach to interrupts independently.

At the level of attachInterrupt and void (void) handlers you will not be able to use a single interrupt handler function and then properly dispatch the handling to multiple individual objects. The high-level attachInterrupt mechanism is insufficient to work around this limitation in a proper way. (At ISR level you can do that, the same way Servo.h handles multiple servos, but it is more complicated.)

For this reason, in your case, as long as you want to stay at attachInterrupt level, it is better to just implement two separate interrupt handlers as external functions that will call your class methods for your existing global objects

ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void handler_door1()
{
  door1.detection_door();
}

void handler_door2()
{
  door2.detection_door();
}

and then just attach these handlers to your desired pins in a regular way.

static in this case can only change things in a purely cosmetic way.

On the second thought one can wrap the above into a quasi-elegant implementation that might look as follows

constexpr unsigned N_PINS = 16; // Range of attachable pin numbers

class ledDoor
{
  // ...

  static ledDoor *self[N_PINS];
  static void (*const HANDLERS[N_PINS])();

  template <unsigned PIN> static void handler()
  { // This is the actual interrupt handler that will dispatch the call to
    // the `detection_door` method of the proper class object
    self[PIN]->detection_door();
  }

  // ...

  void attach()
  {
    self[_sensorPin] = this;
    attachInterrupt(digitalPinToInterrupt(_sensorPin), HANDLERS[_sensorPin], CHANGE);
  }

  void detection_door()
  {
    // Your code
  }
};

And somewhere in one of the .cpp files

// Definitions and initializers for static members

ledDoor *ledDoor::self[N_PINS] = {};

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  ledDoor::handler<0>,
  ledDoor::handler<1>,
  // ...and so on...
  ledDoor::handler<15>
};

This uses a dedicated callback for each pin. Maybe a better idea would be to use interrupt number (i.e. the result of digitalPinToInterrupt) for indexing instead of pin number.

The same thing can be rewritten through lambdas instead of a template. I.e. one can get rid of ledDoor::handler<> template and instead initialize the HANDLERS array as

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  [](){ ledDoor::self[0]->detection_door(); },
  [](){ ledDoor::self[1]->detection_door(); },
  // ...and so on...
  [](){ ledDoor::self[15]->detection_door(); }
};

Note that this approach is a bit more memory wasteful that it could have been, since it uses a number of static tables of pre-determined size. In essense this is a slightly different implementation of the same "gluing" approach as described here.


How can I alter my program to read PWM signals from Arduino Mega?

It looks like the code in the ISR is slow and it may compute incorrect results.

It is slow because of using floating point arithmetic in throttle_pwm and aileron_pwm calculations.  It may be so slow that the trailing edge of a PWM pulse occurs while the leading edge still is being processed.  This will delay trailing edge processing, and mis-measurement of pulse lengths.

The main thing to do to reduce the amount of code executed in the ISR is separate the input measuring phase from the output actuating phase.  You could compute pulse widths and store them in volatile variables for a loop in main to pick up and use in analogWrite() statements there.

Note, in 16-bit int arithmetic, the value of expression (t-1500)/1000 is 0 for 500 < t < 2500.   Because throttle and aileron are supposed to be RC pulse lengths in the range 1000 to 2000 μs, your  throttle_pwm and aileron_pwm will be zero.  That means you can replace the following code,

int throttle_pwm = (throttle - 1500) / 1000;
int aileron_pwm = (aileron - 1500) / 1000;
int v = (0.5 - abs(aileron_pwm)) * (throttle_pwm / 0.5) + throttle_pwm;
int w = (0.5 - abs(throttle_pwm)) * (aileron_pwm / 0.5) + aileron_pwm;
int lm = v + (w/2) * 255;
int rm = v - (w/2) * 255;

with this code:

int throttle_pwm=0, aileron_pwm=0, v=0, w=0, lm=0, rm=0;

which should save you several milliseconds of computation!  Also, having lm and rm as constant zeroes means that you don't need all those lengthy and laborious if and else blocks.   You can replace those 24 lines of stuff with just the following:

analogWrite(8,0);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(11,0);

Slightly more seriously, it looks like you intended for your arithmetic like (throttle - 1500) / 1000, etc. to determine whether to raise or lower the throttle, etc.   Instead of doing that time-consuming division, just say:

int throttle_pwm = throttle > 1500 ? 1 : -1;  // or whatever values you meant to have
int aileron_pwm = aileron > 1500 ? 1 : -1;    // ditto

Instead of all those 24 lines of stuff, just say:

analogWrite(8,  (rm>0) * Level);
analogWrite(9,  (rm<=0)* Level);
analogWrite(10, (lm>0) * Level);
analogWrite(11, (lm<=0)* Level);

where Level is some level you want to set the control to.  Note, an expression like (rm>0) has a value 1 when it is true and and 0 when it is false.  So when rm>0, you have, in effect, analogWrite(8,Level); and analogWrite(9,0);.

If instead you end up with a calculation where lm and rm are actually usable PWM levels, ie numbers from 0 to 255, you could instead say:

analogWrite(8,   (rm>0) * rm);
analogWrite(9,  -(rm<=0)* rm);
analogWrite(10,  (lm>0) * lm);
analogWrite(11, -(lm<=0)* lm);

or could say:

analogWrite(8,  rm>0  ?  rm : 0);
analogWrite(9,  rm<=0 ? -rm : 0);
analogWrite(10, lm>0  ?  lm : 0);
analogWrite(11, lm<=0 ? -lm : 0);

Also see my answer to the question  Read RC receiver channels using Interrupt instead of PulseIn and see my answer to the question  Arduino read PWM duty cycle value with input (analog / digital).


As noted in a comment, you can measure connection resistances, which should be near zero.  (Typical DVMs / multimeters will show an ohm or two for a short, because of leads resistances.)

Measuring voltages may give you more definitive results than measuring resistances.  To measure voltages, install a sketch that toggles known pins in a known pattern.  For example, the sketch below toggles PB0...PB5 high, low, high, low, ... every two seconds.

//  jw - Dec 2016 - toggle bits PB0-PB5 every 2 seconds
enum {PinMask = 63};    // Mask for PB0...PB5, or d8 ... d13
void setup() {
  PORTB = DDRB = PinMask;  // Set pins as high outputs
}
void loop() {
  delay(2000);      // Delay 2 seconds
  PINB = PinMask;   // Toggle the pins
}

To use this sketch, attach a meter lead to ground on your Uno.  If you have small enough clips, hook a lead to pin 6 of the 6-pin ISP connector, as in  the diagram.  Then verify that pin 2 of that connector shows a steady +5V, and that each of pins 1, 3, and 4 on it are toggling between +5 V and 0 V every two seconds.  Those pins are connected to PB4, PB5, and PB3, which are Arduino digital pins #12, 13, and 11, respectively.  Note, toggling #13 should turn the on-board LED off or on every two seconds.

Note, pins 1 and 2 are closer to the RX-TX corner of the Uno board than are pins 5 and 6.  The latter are closer to the A4-A5 corner.

After you have the sketch loaded and verified (that is, have seen properly toggling voltages at the ISP connector), with one lead still attached to ISP pin 6 ground, point a probe at each LCD land where a wire connects.  That is, make the probe contact the copper you intended to solder to, rather than contacting the wire.  This is to get closer to end-to-end measurements.  With the sketch shown above, you will touch your probe to the lands of LCD pins 6, 11, 12, 13, 14 (assuming you've followed pin assignments shown in your link).  If you find those points toggling ok, you've got basic connectivity.  If not, resolder, using proper solder and a hot-enough iron.  If basic connectivity is ok but LCD still doesn't work, you may have some lines mixed up, or may have shorts between lines, etc.  You can run a sketch like the one shown below to test individual lines.  Set WhichPin to values 1, 2, 4, 8, or 16 in turn, to test  Arduino digital pins #8, 9, 10, 11, 12, respectively.

//  jw - Dec 2016 - toggle one of PB0-PB5 every 2 seconds
enum {PinMask = 63};    // Mask for PB0...PB5, or d8 ... d13
enum {WhichPin = 1};    // Set this to 1, 2, 4, 8, or 16 for PB0-PB5
void setup() {
  PORTB = DDRB = PinMask;  // Set pins as high outputs
}
void loop() {
  delay(2000);      // Delay 2 seconds
  PINB = WhichPin;  // Toggle the selected pin
}

For testing Arduino digital pin #7, you can add pinMode(7,OUTPUT); digitalWrite(7, HIGH); in setup() and digitalWrite(7, !digitalRead(7)); in loop().

Edit 1: The first sketch shows a brief way of toggling six lines at once, using port-level IO instead of using a half-dozen digitalWrite() calls.  The sketch generates a low-frequency square-wave.  The reason for measuring if LCD pin-voltages toggle up and down when the Uno outputs a square wave is to find out if there are ok connections between pins on the Uno and corresponding pins on the LCD.

One cannot realistically expect the LCD to work unless the connections are solid.  Making solid connections requires finding out which connections are good, and which are bad, and fixing the bad ones.  A quick test for if a connection exists is to output a square wave to an Arduino pin and observe if that square wave arrives at its destination pin on the LCD.

In the sketch, PinMask selects which bits of port B get toggled.  (A 1 OR'd into PinMask selects PB0 or digital pin #8 to be toggled; a 2 OR'd in  selects PB1, #9; a 4 selects PB2, #10; and so forth.)  In the second sketch, WhichPin is a bit mask containing one bit, which is used to select one pin to be toggled instead of toggling all six pins.


Arduino randomly freezes during runtime?

You should replace:

if(currentTime - previousTime == delayTime){

with

if(currentTime - previousTime >= delayTime){

There is always a chance that, since you are using a servo which is quite intensive with interrupts, that millis() may skip a beat and that statement can never be true.


Yun as a Conventional Wireless Access Point

Check out this project, made by @Vadorequest the early days of the Yun: he hacked a car to control it via his smartphone. There's a nice video on youtube.


Will Funduino Joystick Shield work on a Mega?

The shield will work on Mega, except of the SPI connection for the nRF24L01 connector. The shield expects SPI on pins 11, 12, 13 and Mega has them on 50, 51, 52. Other shields use the SPI pins on the ICSP header to have compatibility with different boards. This shield doesn't connect to the ICSP header.

You can wire the nRF24L01 to SPI pins on 50, 51, 52.


Serial.read() doesnt work in IF statement

Your problem is that you are assuming that all you see in the Serial Monitor is all there is. You see "OK", so you expect to compare the text that comes in with "OK".

However it's not. Serial communication (at least, text based serial communication) generally includes some kind of line ending marker. That could be any combination of Carriage Return (\r) and/or Line Feed (\n). Different devices use different combinations.

As it turns out the XBee uses '\r' as the line ending marker.

There are two ways of dealing with it:

Include the line ending in your comparison ("OK\r"), or better,
Incorporate the line ending in the reading.

The second point there involves the use of readStringUntil():

String x = xbeeSerial.readStringUntil('\r');

That is a more reliable way of reading the response since it reads everything up to the line ending, rather than reading until it times out with nothing else to read. You should find your whole program runs smoother with that method.


The reason they keep trying to turn is mechanical. The physical stop in the gears is hit before the encoder/potentiometer reaches its end point.

You can make the servo stop fidgeting by completely relaxing it if you want. just use

s1.detach();
s2.detach();

and your arduino will stop sending any signal.

Bear in mind that "reading" the value of a servo in arduino gives you the servo's current set point, not its current location. Your code in unfortunately unaware of a servo's actual location. With that in mind, setting your servo to go to 0, waiting for it to get there with a delay, and then detaching it will have the desired effect, but since it will not maintain position and you will need to reattach it to function again, using 1 or 2 as your far left endpoint is likely the better option.


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

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

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

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

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

You would use the class as this:

LowHigh temp, pressure, humidity, rainfall, altitude;

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


incompatible types in assignment of 'int*' to 'int [0]'

The issue is with flexible array int _teamIRCodes[]; This is an old technique which I don't recommend. But if you want to use it, you need you use malloc to create a class object, adding on enough space for the array:

// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:

for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

I think it's much simpler to use a pointer:

int* _teamIRCodes;

Then you can make your ctor:

Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

And don' forget to add a dtor:

~Gun() {
    delete [] _teamIRCodes;
}

Or, if teamIRCodes is persistent throughout the lifetime of the object, you can just use a pointer to it:

 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).


communicating with arduino over serial via terminal

This was fixed this morning after a reboot and upgrade command, still don't know which one of these fixed it but it seems to work now.

Ah figured it out we were using the 0 and 1 rx gates to communicate over serial rather then usb and as the used power supply turned out to be only 5V rather then 9-12V it didn't quite work as intended.


Most likely you fried the voltage regulator or the diode on your Arduino board (depending in which power source you used), because the servo has drawn too much current.

Many Arduino Kits or Starter Packs come with really small servos. These do not need much power (especially when no mechanical load is attached to them), so you can power them directly from the 5V pin. Greater/stronger Servos draw much more current and cannot be safely run in the 5V pin.

Many tutorials show this, because it is an easy start for a beginner. And with the right servo it works. More sophisticated cases are not covered there.

EDIT:

Since your Arduino works fine, the voltage regulator and/or the diode should be fine. I tested the Knob example on my Arduino Nano, while powering the servo on the Arduinos 5V pin (and the Arduino is powered over USB). When the Servo is moving, you can see that there is a significant power draw (The power LED gets a bit dimmer), but not so much, that it would be a problem for the Arduino or USB port. Also the example code works as it should, without the servo heating up. I also used a SG90 Micro Servo (9g, by Tower Pro; same as in the tutorial you linked). I also tried the same with an external power source (5V from a powerful USB charger). It still works as intended, but with more power, since the servo now can draw much more current to produce a higher thrust.

So the only thing, I can think of for your problem is, that you either have corrupt hardware, or you have connected it wrong (for example wrong polarity). My Servo has the same color coding for the wires as in the tutorial you linked. Brown is ground, Red is 5V Vcc and Yellow is for the pulse signal.


Fastest way to read an array of numbers from python

If you don't know the length of the data then you need to be sending start and end markers so your other code can tell where the transmission starts and ends.  I usually use < and >, so the data packet might look like <12345678>.  You don't have to use those particular characters, just pick something that you know won't show up in your data.


Unreliable function of transistor, pump and ESP32

As can be seen from the datasheet for the PSNB5R6 (Fig 7) at 3.3V the MOSFET is barely even beginning to switch on.
You need to select a more suitable MOSFET that switches on fully at a voltage well below 3.3V, such as the STP40NF04L.


Mega  esp8266 comms sending baffling data

The esptool auto-reset feature by default sets io 0 LOW over the RST line and then makes a reset over the DTR line to put the esp8266 into flashing mode. After the upload the esptool resets the board over the DTR line.

On this board Mega+WiFi, only the DTR line is wired like for AVR MCU. For flashing the io 0 pin is put LOW with the pin 7 of the DIP switch manually. So the reset after upload sets the esp8266 back to flashing mode.

The esp8266 arduino package changed from version 2.5.0 the upload tool to the python version of the esptool which makes this reset after upload. This reset can be turned off by changing the command line of the esptool in platform.txt (--after no_reset in tools.esptool.upload.pattern before write_flash)


How do i improve this Code? (or how to pass a Char String into a Function to behave like a Variable)

The question is somewhat confused, but I think I got what you mean. Your
code suffers from too much repetition. You only showed the handling of
two selectors, but you want to handle 6 of them. Repeating all the logic
6 times would make the code unwieldy and hard to maintain. So you
want to put the logic in a function and just call that function six
times.

I actually only had to pass the number to the function, like "3" to
change some Variables and Char Strings accordingly

You do not need to pass the number as a string: you can use
Serial.print() to format the number instead. And you do not need to
write a function either: you can just put a for loop inside the
loop() function:
const int rmd_count = 6;

Bounce rmd[rmd_count] = {
    Bounce(48, 10),  // rotary selector on pos. 0
    Bounce(47, 10),  // rotary selector on pos. 1
    Bounce(46, 10),  // rotary selector on pos. 2
    Bounce(45, 10),  // rotary selector on pos. 3
    Bounce(44, 10)   // rotary selector on pos. 4
    Bounce(43, 10)   // rotary selector on pos. 5
};

void loop() {
    for (int i = 0; i < rmd_count; i++) {
        rmd[i].update();
        if (rmd[i].fallingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 1");
            rotary_mode = i;
            Serial.print("rotary_mode = ");
            Serial.println(i);
        }
        if (rmd[i].risingEdge()) {
            Serial.print("rmd[");
            Serial.print(i);
            Serial.println("] = 0");
            rotary_mode = 0;
            Serial.println("rotary_mode = 0");
        }
    }
}

The key to using for loops is to structure your data in arrays,
instead of collections of variables named with numbers. Thus, instead of
rmd3 you would use rmd[3]. Note that array indices start at zero.
Obviously, you could put the body of the for loop inside a function,
but at this point that would not help much in simplifying the code.

Edit: As a clarification, and per Delta_G's suggestion, I'll try to
explain the difference between an array and a collection of variables.
Each variable you define is mapped by the compiler (technically, the
linker) to a memory area. You can think of the variable names as
convenient names assigned to those memory locations. If you write:
Bounce rmd0(48, 10), rmd1(47, 10), rmd2(46, 10), ...;

You get:
      ┌───────┐        ┌───────┐        ┌───────┐
rmd0: |       |  rmd1: |       |  rmd2: |       |  ...
      └───────┘        └───────┘        └───────┘

In the picture above, the boxes are the memory areas. They are large
enough to hold a Bounce object, i.e. their size is sizeof(Bounce).
Each one has a name. You have no control over where, within the memory,
those variables are allocated: it's the linker's call.
In contrast, when you declare an array, you get a single variable
which is mapped to a contiguous memory area large enough to hold the
whole array:
Bounce rmd[6] = { ... };

Gives:
     ┌───────┬───────┬───────┬───────┬───────┬───────┐
rmd: |       |       |       |       |       |       |
     └───────┴───────┴───────┴───────┴───────┴───────┘

The individual cells do not have a name, and you instead use indices to
access them. For instance, rmd[0] references the first cell. Please,
note that in this example there is no variable named rmd0: if you try
to use that identifier the compiler will complain it is not defined.
Again, an array is not a “collection of variables”: it is a single
variable.
The array cells do behave in some sense much like individual variables
(they are called lvalues), as you can use rmd[0] in the same way you
would have used rmd0 in the previous code. The point of using an array
is that the indices do not need to be literals: you can use a variable
instead (rmd[i], where i is a variable), which comes handy when you
want to loop over all the cells.

Edgar pointed out that I can write the variable rmd3 by int i = 3
and rmd[i].

I hope it is now clear that this is not the case. There is no variable
named rmd3 unless you create it explicitly. Declaring an array named
rmd does not create such a variable.

[Can I] "form" a variable by "characters"?

Your question is not very clear, but my guess is you are talking about
computed variable names. This is a programming technique where you
access a variable by computing its name at run time. For example, you
combine the strings "rmd" and "3" in order to build the name of the
variable "rmd3". Then you use this computed name to access the variable
that has this name.
Computed variable names are quite often supported by interpreted
languages. For example, in PHP this is called variable variables:
$foobar = 42;           // the variable we want to access
$start = "foo";         // one piece of the name
$end = "bar";           // the other piece
$name = $start . $end;  // build the name from its pieces
print $name . "\n";     // prints the variable name: "foobar"
print $$name . "\n";    // prints the variable's value: "42"

Computed variable names are not supported by C++, which is the
language you use to program an Arduino. And for a good reason: when the
compiler translates your program to machine code, the names of the
variables are lost, they do not make their way to the actual Arduino.
And this is a good thing, as you would not want those names to consume
memory on the microcontroller.
Note that the names are present in the .elf file, as they could be
useful for debugging. If you were programming for a PC, you program
could in principle look into the file and find those names. On Linux you
would do that with the dlopen() and dlsym()
functions, from the libdl library. The libdl technique is, however, very
far from the capabilities of your typical Arduino, orders of magnitude
more complex than a simple array, and perfectly useless for your use
case.


The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that
depends on the supply voltage. Most 328P-based Arduinos are clocked at
16 MHz though.

  what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the
timer to count microseconds. You can set it to 8 or to 64, but there is
no intermediate setting in between.

Maybe you could leave the prescaler at 8 and count half-microseconds
instead?

Edit: On the 328P, Timer 0 has two control registers, named
TCCR0A and TCCR0B. To set it to normal counting mode at F_CPU/8,
you have to:

TCCR0A = 0;
TCCR0B = _BV(CS01);

If you are programming in plain C, the first line is not needed (but it
won't hurt either), as the initial value of TCCR0A is zero on reset.
If you are using the Arduino core library (and you write setup() and
loop() instead of main()), then you do need this first line, as the
Arduino core configures Timer 0 for PWM at 977 Hz. But note
that the Arduino core also uses Timer 0 for timekeeping
(millis(), micros() and delay()). Thus you may want to use another
timer.

You could switch to Timer 2 by replacing every “0” with a “2” on
the register and bit names of the two lines above. Then you would also
replace every occurrence of TCNT0 in the code with TCNT2.


Copying an SD card (cloning) is easy enough to do.  On Windows you can use Win32DiskImager.  On Linux and OS X you can either use dd from the command line:

(read)
$ dd if=/dev/sdb of=MySD.img bs=32k

(write)
$ dd id=MySD.img of=/dev/sdb bs=32k

For OS X the device names will be different, also in Linux you need to check which /dev/sd?? it is.

Also in Linux and OS X there are GUI applications that can do it for you - the Disk Manager in OS X, and "Gnome Disks" in Linux.

That is only good for the actual SD card contents though.  If you need to clone the actual Yún itself then it becomes more tricky.

Fortunately there are tools available to help you.

Details on how to create and restore a backup of an OpenWRT system (which is what the Yún is) can be found on the OpenWRT Wiki: http://wiki.openwrt.org/doc/howto/generic.backup

Note that again it requires a Linux or OS X (preferably the former) system to do it since it relies on the standard Unix scripting tools and commands that are lacking on a Windows system.

You may be able to do all the above on a Windows system if you make it look like a Linux system by installing Cygwin.


The MPU-6050 has an address pin, marked as A0, which can be used to set the LSB (least significant bit) of the address. So if you connect A0 to ground, the address will be 0b1101000, if you connect it to Vcc it will be 0b1101001. You can find this information in the table under capter 6.4 in the MPU-6050 datasheet (page 15). Normally this pin is getting hardwired, but you can also connect A0 to a digital output pin of your Arduino and dynamically change the address of the MPU.

So with this pin you can have 2 different MPU-6050's on the bus. If you need more, you can keep all MPU's on one address, while pulling the MPU, that you want communicate with, to the other address. I described this principle at the end of my answer to this question. It is about a different chip, but the principle is the same.

It is important, that you cannot have multiple devices with the same address on one I2C bus, unless you never communicate with that address. When you try to use an address, where multiple devices will answer, the I2C bus most likely will get stuck, or the data will get corrupted. As long as such an address is never called, everything is fine.


Arduino Esp8266 Signal(TIMER0_COMPA_vect) can’t compile

That instruction is for setting up an interrupt handler for the timer. It is very much specific to the AVR.
There's a lot more to do that just adjust that one statememt - you have to completely rewrite the whole of the timer code that you're using to operate with the ESP8266 SDK calls.
Without knowing what your code intends to achieve it's impossible to help you further, but this library may be of help to you.


Maybe this link will be helpful for you.

Arduino-mkr1000-getting-starter-wifi

#include <WiFi101.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <WiFiSSLClient.h>
#include <WiFiUdp.h>

/*
* This example is modified from the original file
* https://github.com/arduino-libraries/WiFi101/blob/master/examples/
 SimpleWebServerWiFi/SimpleWebServerWiFi.ino
*/
#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "yourNetworkSSID";      //  your network SSID (name)
char pass[] = "yourNetworkPassword";   // your network password
int keyIndex = 0;                 // your network key Index number (needed    only for WEP)
int ledpin = 6;
bool val = true;

int status = WL_IDLE_STATUS;
WiFiServer server(80);

void setup() {
Serial.begin(9600);      // initialize serial communication
Serial.print("Start Serial ");
pinMode(ledpin, OUTPUT);      // set the LED pin mode
// Check for the presence of the shield
Serial.print("WiFi101 shield: ");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("NOT PRESENT");
return; // don't continue
}
Serial.println("DETECTED");
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
digitalWrite(ledpin, LOW);
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid);                   // print the network name (SSID);
digitalWrite(ledpin, HIGH);
// Connect to WPA/WPA2 network. Change this line if using open or WEP          network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin();                           // start the web server on port 80
printWifiStatus();                        // you're connected now, so print out        the status
digitalWrite(ledpin, HIGH);
 }
 void loop() {
 WiFiClient client = server.available();   // listen for incoming clients

if (client) {                             // if you get a client,
Serial.println("new client");           // print a message out the serial     port
String currentLine = "";                // make a String to hold incoming data from the client
while (client.connected()) {            // loop while the client's connected
  if (client.available()) {             // if there's bytes to read from the client,
    char c = client.read();             // read a byte, then
    Serial.write(c);                    // print it out the serial monitor
    if (c == '\n') {                    // if the byte is a newline character

      // if the current line is blank, you got two newline characters in a row.
      // that's the end of the client HTTP request, so send a response:
      if (currentLine.length() == 0) {
        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
        // and a content-type so the client knows what's coming, then a blank line:
        client.println("HTTP/1.1 200 OK");
        client.println("Content-type:text/html");
        client.println();

        // the content of the HTTP response follows the header:
        client.print("Click here turn the LED on pin 9     on
");
        client.print("Click here turn the LED on pin 9 off
");

        // The HTTP response ends with another blank line:
        client.println();
        // break out of the while loop:
        break;
      }
      else {      // if you got a newline, then clear currentLine:
        currentLine = "";
      }
    }
    else if (c != '\r') {    // if you got anything else but a carriage      return character,
      currentLine += c;      // add it to the end of the currentLine
    }

    // Check to see if the client request was "GET /H" or "GET /L":
    if (currentLine.endsWith("GET /H")) {
      digitalWrite(ledpin, HIGH);               // GET /H turns the LED on
    }
    if (currentLine.endsWith("GET /L")) {
      digitalWrite(ledpin, LOW);                // GET /L turns the LED off
    }
  }
}
// close the connection:
  client.stop();
  Serial.println("client disonnected");
  }
}

void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());

// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);

// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}


GSM shield 2 - Fully erase memory buffer

Well, after many trials, here is the thing: the GSM shield actually can suck up a lot of electric current (up to 2A at full whack).
So, for some functions (connecting to the GSM network, deleting SMS), if you MEGA or UNO is only powered through your computer's USB port, chances are that the whole program will get stuck in a loop waiting for the command to execute.
Good news: if you just plug a 12V power cable even in the middle of the freeze, the program will go on.

So, the bottom line: never try to use the shield without a good powering system.


Is there any way to use a JTAG programmer with the Arduino IDE?

For a one-click upload, you can make a custom hardware definition that calls any executable of your choosing.


How can I have code in a project that won't compile for Arduino?

I would use conditional compilation, like this:

#ifndef(ARDUINO)
// Non-Arduino code.
#endif


Arduino Ethernet Shield 2: How can I automatically determine the MAC Address?

No, the W5500 chip does not have a mac address. You can give it any mac address that you want. The router might not like some mac addresses though.

There are online mac address generators.

The sticker with the mac address is an extra service. It is unique number. But it is just a number on a sticker, it is not related to that specific shield.

Often the mac address DEADBEEFFEED was used. But when two different Arduino boards use the same mac address, the router thinks it is the same device. When there are two devices with the same mac address at the same time connected, that is for sure a way to mess up the router.


Controlling Servo Motors with push button. Problem though

You might need to add more time to the delay. Also, check how your powering the servo. If you're powering from the Arduino, it might be drawing to much current and causing issues. If it's a bigger servo, try to hook it up to an external power source and just connect the PWM line and it's ground.


How do I measure speed and manipulate the speed based on distance covered?

They key point here is to know the distance. The simplest way of finding that distance is to know how many times the wheel has completed an entire revolution. Multiply that number of revolutions by the circumference of your wheel and you have the distance the wheel has covered.

Depending on how precisely you want to measure that distance you may get away with a simple magnet and hall effect sensor. Place the magnet on the wheel, and locate the hall effect sensor so the magnet passes it close enough to trigger. Each pulse from the sensor is one rotation of the wheel.

You could increase the resolution by adding more magnets - 4 magnets set at 90° points around the wheel will give you a pulse for each quarter of a revolution (so multiply pulses by a quarter of your circumference).

If you want better resolution and accuracy you could attach a rotary encoder to the axle of the wheel. This, depending on the encoder, can give you far better resolution than simple magnets. Some will also give you the angle the wheel is at (not that such information would be of interest in this project).


Using two ultrasonic sensors for counting cars when they enter to a garage

If you have two sensors, you use analogRead.

int sensor1 = A0;
int sensor2 = A1;
int distance = 50; // or whatever you want here
bool car_passing = false;

void setup(){
    int counter = 0;
}

void loop(){
    if(analogRead(sensor1) < distance &&
       analogRead(sensor2) < distance &&
       !car_passing)
    {
        car_passing = true;
        counter++;
    }

    if(analogRead(sensor1) > distance){
        car_passing = false;
    }
}

To prevent the counter keep counting while the car is passing by, we need to make a boolean, so the counter does not wait for count again, before the car has passed.


'"/dev/ttyACM0": Permission denied' on Ubuntu 18.04

As stupid as it may sound but "have you tried turning it off and on again?".
Changes to groups only become effective when you have logged out of your account


Some Arduino components seem ridiculously cheap

The cheaper option is not always lower in quality. You can find items for sale on Amazon, Ebay and Aliexpress that all have the same "seller name" and a identical picture of the item. The price is usually 5 to 10 times higher on Amazon than Ebay. Aliexpress is usually the cheapest.

During the past year, I've ordered over 100 Arduino related sensors/modules from Ebay and Aliexpress. Four from Ebay and one from Aliexpress were defective. I got a refund for all five items.

If you are going to buy the cheaper products, it's a good idea to order more than you need in case one is defective.

Some items should not be sold at any price. For example, I purchased a DHT11 temperature and humidity sensor when I first started with Arduinos. It's an inaccurate piece of garbage, and that's exactly where it went.


Why we can wake Arduino Uno from sleep using only pin 2?

It's not just Pin 2 that can wake from sleep. Depending on which sleep mode you are in different interrupts (both internal and external) can wake the chip up.

The datasheet contains this helpful table:

The external interrupts (pins 2 and 3 on the Uno, and only "Level" trigger mode), pin change interrupts, I2C address matching, and the watchdog are the only interrupts that can wake the chip from any sleep mode. Other interrupts only work in certain sleep modes since they require parts of the chip to still be running in order for the interrupt to fire.

So that means that yes you can use any pin you like (using the "Pin Change" Interrupts) to wake the chip.


EMI resets atmega on switching ON relay with inductive load like a 230v fan

This can also be a power shortage as there will be a drop when the relays turn on, depending on you psu it might not respond quick enough, so you get a brown out. I added a bit 4700uF cap on the psu power line to the arduino.


string.indexOf() always returns a non-zero value

The problem here is that indexOf returns the position of the character in the string, or -1 if it's not found.

In C 0 is false and everything else is true. That includes -1.

However, your usage if String here to just check for one character is incredibly wasteful and should be avoided. Instead, use strchr:

if (strchr(new_password, '#') != NULL) {
    ... contains # ...
}


Soft Serial is totally unreliable. You may have a better error rate at other baud rates, but you will never achieve the same as a hardware based serial connection.  I'd switch my debugging connection to the software serial, nd use the hardware serial for the XV-11.


Is it possible to sample sound with arduino?

For the AtMega328's ADC the datasheet says

  • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

So, sampling two channels at 10bit resolution and 44.1kHz is not possible.
If 8bit resolution is enough, and if there's only one channel to sample, it should be able to do the job.

Edit:

To answer Connor's comment:
Of course, this does only apply when using the internal ADC. Connecting an external ADC (via SPI or whatever) makes it possible to sample data at the desired speed.

But anyway, the next question is: Is 16MHz fast enough to process the sampled data (which are received every (22.6/channels) microseconds? ;-)


Turning all 35 leds on sequentially with MM5451

I think you need something like this.

#define CLK 2 // to MM5451 pin 21
#define DATA  3 // to MM5451 pin 22

void setup()
{
    pinMode(CLK, OUTPUT);
    pinMode(DATA, OUTPUT);
    digitalWrite(CLK, 0);
    digitalWrite(DATA, 0);
    Serial.begin(1200);
}

// the loop routine runs over and over again forever:
void loop()
{
    for( byte led=0; led<35; led++ )
    {

        lightLed(led);

        delay(1000);
    }
}

void lightLed(byte index)
{
    //always send a one first
    sendOne();
    // turn off all leds preceding index
    for( byte i=0; i<index; i++ )
        sendZero();
    // one led on
    sendOne();
    // pad with leds off
    for( byte i=index+1; i<35; i++ )
        sendZero();
}

void sendOne()
{
    digitalWrite(DATA, HIGH);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}
void sendZero()
{
    digitalWrite(DATA, LOW);
    digitalWrite(CLK, HIGH);
    digitalWrite(CLK, LOW);
}


Replacing atmega8 with atmega328 on Arduino Single-Sided Serial Board

Yes and no. It will work on this board, but won't get programmed by arduino IDE directly.

ATmega328 and ATmega8 are fully pin compatible. ATmega328 is like bigger and powerful in terms of onchip resources. However, if you want to program ATmega328 on the arduino board, you must install bootloader. Otherwise you will have to program it everytime using ISP programmers such as USBASP. This will connect to the ICSP socket shown on the above board.

Refer to: http://tutorial.cytron.com.my/2011/09/30/how-to-program-arduino-by-using-avr-usbasp-programmer/


Adding slave device to Arduino Uno-SPI | Configuring pins

You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.

Here are the links to the relevant files in the library, so I can comment on them.

INO example file
Library header file
Library source file

Ok, first of all let's have a look at the example. you can see that the constructor is called as

Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

When looking at the lines 144 and following of the source file, you can see

hwSPI = false;

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS), you will use the hwSPI.

Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.

You can also see it in the example:

// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.

As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data


How can I make my arduino start when a magnet is sensed, and stay running until the application determines it was to shut down

Put your Arduino into deep sleep and attach an interrupt to a pin that is monitoring your reed switch. Once triggered it can run your code before deep sleeping again


Arduino add two spi slaves that has no slave select pin

Ss or cs pin ISS not mandatory for SPI.

A few solutions.

Power on or off the devices. A group pin can do that.
Cut off mclk.
Have a separate sclk pins for individual chips. You will need to share the serial data pins, ored with some diodes or pull up.
Software SPI.

...

I'm sure others will come up with more solutions.


Digispark ATtiny 85 erases flash after power loss

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

EDIT:

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

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

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


I would suggest using strtok() to chop the string up:

char *prefix = strtok(mystring, ",");
char *firstString = strtok(NULL, ",");
char *secondString = strtok(NULL, ",");

That has the effect of slicing the existing string up in memory replacing the commas with \0 and placing three pointers at the start of the three substrings. It has the advantage that it doesn't need to copy the contents of the string anywhere, so doesn't use any extra memory (other than the few bytes for the pointers).


Arduino connection to brainwave analyzing module

As per the datasheet you provided, it is quite straight forward.
It can be connected to RX (pin 0) and TX (pin 0) pins of the Arduino Uno.
But, the pins have to be crossed;

Arduino RX (0) <> TGAM T (TX)

Arduino TX (1) <> TGAM R (RX)

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

Good luck.


Arduino pin 3 to 7 used in serial data transfering

pins 0,1 are rx/tx for the hardware UART peripheral. Arduino (I assume UNO/Nano) have just one hardware UART.

there is a software library which makes use of any 2 pin to simulate hardware UART pin behavior for additional software UARTs (this is called bit banging). these "software" UARTs are not as fast as hardware ones and can't be relied on for fast baudrates (speeds). but for 9600kbps, they're good.
keep in mind, that despite they are easy to implement and versatile, they use CPU time when communicating and if you are using interrupts in your code, data flow will be affected.

https://www.arduino.cc/en/Reference/SoftwareSerial


Can i use arduino code, without using arduino board but just using MCU included

Yes, you can. Once you have a .hex file for a specific MCU and environment you can use a programmer to upload it to a discrete MCU.


The Esp8266 module has different firmware, the old one was running at 9600 and the new one is running at 115200.

Try to upload this code on  your arduino Nano and send AT commands over the Serial monitor of the Arduino.

If you send AT it should returns "OK", if not, try to swap RX to TX and try to play around with the baudrate 9600, 57600, 115200.

It might be that your Wifi module doesnt have any firmware loaded which might need to be done.

#include <SoftwareSerial.h>

SoftwareSerial wifi(10,11); // RX, TX

void setup()
{
Serial.begin(9600); // FTDI
wifi.begin(9600); // GPS; 9600 first time, 38400 second time
}

void loop()
{
if (Serial.available())
wifi.write(Serial.read());
if (wifi.available())
Serial.write(wifi.read());

}


Am I missing the point here or wouldn't the C# just have to open a Serial connection to the board and read and write to that to control the program running on the Arduino?
Yes the board is connected by USB, but that's only so it can open a serial connection.
To be honest I don't think you will be able to sample at that speed, you might be better looking at ICs that directly interface with GPIO and RS232/USB.


Safely enabling voltage divider on a 12V battery

I use a similar system on a product I recently worked on to monitor the battery voltage - and of course I didn't want it on all the time to drain the battery.

The trick, though, is to do the exact opposite of what you are doing.  Instead of isolating the ground (which leaves the battery then directly connected to the Arduino) you need to completely isolate the battery from the divider.

This can be accomplished by using a P-channel MOSFET which you can then drive with an N-channel MOSFET:

The theory is, when the Arduino DOUT is either LOW or not connected (pulled low by 10K resistor) the N channel MOSFET is turned off.  That means the gate of the P channel MOSFET is being pulled up to the battery voltage by the other 10K resistor, so the P channel MOSFET is off, which isolates the whole divider from the battery.

When DOUT goes HIGH it turns on the N channel MOSFET which then pulls the gate of the P channel MOSFET down to ground which then turns it on, thus connecting the divider to the battery.

When the P channel is OFF the only circuit connected to the ADC is the connection between the ADC input and ground through a 10K resistor, so everything is happy and safe.

You should not use resistors greater than around 10K in size on the input to the ADC because the ADC itself has a resistance (the impedance) which is placed in parallel to the lower resistor of the divider.  If the divider's resistors are too large that impedance will affect the accuracy of your readings because the total resistance of the lower resistor will be skewed slightly.  Yes, it's possible to compensate in software, but as long as you keep to a limit of 10K or so for the resistors you won't need to worry about doing such things.

Note that it is important to use a P-channel MOSFET for this, not a PNP transistor.  A P-channel MOSFET, when on, looks like a very small resistor.  A PNP transistor is seen as a fixed voltage drop skewing your results.  The N-channel MOSFET can be replaced by an NPN transistor if you wish, it makes no real difference. I nearly always use MOSFETS these days instead of BJTs though as a matter of course.

As an aside, the only other way of achieving this whilst maintaining the isolation of the ADC from the battery would be to replace the P channel MOSFET with a small relay (say a reed relay), but then you still have to build a relay driving circuit which is just about as complex as this one.


Including libraries from header files sometimes doesn't work

The problem here is that it's a header file.  The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.

In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.


How to avoid calling multiple times Wire.begin() in libraries?

What you are interested in is this bit of the Wire library:

TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

The important bit is the TWEN bit - TwoWire ENable.

If that bit is set in the TWCR register than Wire.begin() has been called already and you don't need to call it again:

if (TWCR & _BV(TWEN) == 0) {
    Wire.begin();
}

However, it really doesn't matter if you call it multiple times.


How to converte EPOCH time into time and date on Arduino?

Epoch are seconds from 1970-01-01. Get it from JSON as unsigned long. They are a number in the returned JSON (no ")

from https://openweathermap.org/ doc:

"sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},

to convert it to string with TimeLib.h:

#include <TimeLib.h>
#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);

  const char* json = "{\"country\":\"JP\",\"sunrise\":1369769524,\"sunset\":1369821049}";

  DynamicJsonBuffer jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(json);

  unsigned long t = root["sunrise"];

  char buff[32];
  sprintf(buff, "%02d.%02d.%02d %02d:%02d:%02d", day(t), month(t), year(t), hour(t), minute(t), second(t));

  Serial.println(buff);
}

void loop() {
}


Can you use crystal oscillators to change the frequency of infrared?

Still not clear on exactly what you are trying to do.  If you drive the IR LED directly with a crystal oscillator (38 kHz or anything else) there's no data there, just a steady carrier.  So maybe you are trying to modulate that carrier with the Arduino?  It sounds like your plan is to use an output pin to power the crystal oscillator, and modulate by essentially turning the power off and on. This is probably not such a good idea.  Even if the Arduino pin could handle the current (doubtful), the crystal oscillator might not take kindly to this approach... it's meant to go on and stay on.
So you need some sort of switching circuit.  Depending on what you have on hand, you could connect the Arduino (modulator) output through a resistor to the base of an NPN transistor.  The emitter of the transistor goes to the high side of the LED and the collector goes through the LED's dropping resistor to the +5 rail.  If this is a low-power LED then you may be able to use the +5 from the Arduino itself, and a small-signal transistor.  If you have a powerful LED, you'll not only need a separate supply, but a power transistor as well... and maybe wired with a small signal driver in a Darlington configuration if the power transistor needs more base current than the Arduino can give.  Lots of other switching options, but we need to know more details!  Boggyman


It looks like you're trying to measure the resistance of soil by connecting an ADC input through the soil to VCC.  That is not the way to to it.

At the moment you effectively have this schematic for that portion:

simulate this circuit – Schematic created using CircuitLab

The voltage dropped across the soil is proportional to the current flowing through it. And there is no current flowing through it1 because there's no path to ground, only the very high impedance of the ADC.

So you never see anything except VCC (or a floating input when the probe is not in the ground).

To measure a resistance like that you have to have it as one half of a potential divider, just like you would for an LDR.

simulate this circuit

What actual value R2 should have depends entirely on the resistance range detected by your probe. It can be good to experiment with different values until you find one that works for you.

1: Actually there is some small leakage current through the ADC to ground, but that is so tiny we can ignore it.


This line of your sketch irrecv.blink13(true); tells the IRrecv object to flash the LED on and off when an IR signal is received. boarddefs.h in the IRremote folder has pin number 13 defined as the default BLINKLED. The code you have written in loop() is trying to do something different with the same LED. I would remove this line irrecv.blink13(true); then try your sketch again. Once the LED is working correctly, try removing both of these lines delay(1000);.


The ENC28J60 Shields have a Chip-Select-Pin (CS) so you could select between the two shields with this.

I'm using the EN28j60 with the Ethercard library and I'm not sure if this could handle two Ethernet shields because you have to set the CS pin at init on the first call in the function, and can't change it at runtime.


You've opened the port before you've configured it.


Generally you should not provide power to any pin of a device, which is powered off. That can cause current flowing through clamping diodes to ground and might destroy the pins hardware or the device (also it can lead to weird situations, where the device is somewhat powered through the IO pin, which might lead to instability).
You can either cut the connection between the devices, if only one of them is powered (this should be possible with some extra components), or you can power both devices from one USB port. For the other port you would cut the V+ (positive supply voltage) line of the USB port/cable (this makes sure, that you don't get a bad current between both computers on the USB power line, if they provide a bit different voltage). Since the ground wire still connects both computers and the Arduinos, the communication will still work correctly.

if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at Wire.begin(4)?

The Wire.begin() line won't get stuck, since it doesn't do much on the lines and it doesn't know, if something is connected on the other end, until some transaction happens on the bus. But it might be, that any transaction from the powered Arduino (the master) might cause a blocked I2C bus (since at some places the library waits for the lines to get high. The connection through the clamping diodes might hold the line at low. I'm not sure about that). Then you would need to reset both Arduinos, to make sure, that the bus is in a healthy state.
The solution from above (powering both Arduinos from one USB port) will also make sure, that both Arduinos start at the same time and thus won't block the bus through the clamping diodes.


Getting error 32 in multi-master I2C sketch with library https://github.com/rambo/I2C

You cannot use the I2C library and the Wire library at the same time. From the code I guess you wanted the Wire library to do the slaves job and the I2C library to implement the master. But since both libraries use the same hardware, this cannot be divided between them. Combining two libraries for the same hardware isn't that trivial. The I2C library only provides master functionality. So, to reach your goal, you would have to find a library, that provides both master and slave functionality while doing correct bus arbitration (which is the term for correctly handling master data collisions). Or you have to change one of the two libraries yourself, to provide the missing functionality.

And the error you get is defined in #define MT_SLA_NACK    0x20 in I2C.h (0x20 is equal to 32). This means, that you haven't got an acknowledgement from the slave you have addressed. This suggests, that in your current code only the master functionality is working. (But it may have another meaning considering the interaction of the two libraries on the same hardware)


Own type definition using a struct does not name a type

This is a bug in the Arduino IDE: when converting your .ino file to a
.cpp file, it added a declaration for the function ledFactory()
before the declaration of the type led_t.
As it appears to be adding those declarations right before the first
function of your sketch, a simple workaround is to put all your type
definitions before your functions.


Trying to measure change in light levels over time

Break this into pieces. Solve the pieces one at a time.

Write code that reads the 2 photocells and calculates the difference between them. Log that difference to the console.

Then add a global variable to remember the old difference, and a max difference. Each time you take a new set of readings and calculate the difference, compare it to the old difference. If the new difference is greater than the old difference, update the max difference. Then update the "old difference" with the new reading.

Figure out how to use millis() to record a starting time, and monitor the reading difference until an hour has passed. If the reading difference is below your "large amount" threshold, start the light blinking.

Then you need to decide what to do about times greater than an hour. Do you track the max difference over the most recent 60 minutes and flash the light if it is below your threshold? Maybe save a difference reading every 5 minutes into a ring buffer with 12 entries (an hour's worth of entries) and keep checking the ring buffer for a difference value greater than your threshold? (You should be able to Google search "C ring buffer" for sample ring buffer code. It's actually quite simple to implement.

You might also want to calculate a moving average difference reading, and compare each reading to that. I recommend using an Exponential Moving Average (EMA).

I have code in my project that uses EMA to calculate a single brightness value rather than a difference, but the idea is the same. Here is an excerpt from my code:

Define a global:

float   photocellAverage =      0;

#define sampleCountToAverage 100  //The larger the number of samples, the more slowly the average will change with each new reading.

Then

int photocellValue = analogRead(photocellPin);
photocellAverage -= photocellAverage / sampleCountToAverage;
photocellAverage += float(photocellValue)/sampleCountToAverage;

For you, you'd be calculating a difference reading and an EMA of that difference reading:

float   photocellDifferenceAverage =      0;

int photocell1Value = analogRead(photocell1Pin);
int photocell2Value = analogRead(photocell2Pin);
int photocellDifference = photocell1Value - photocell2Value;
photocellDifferenceAverage -= photocellDifferenceAverage / sampleCountToAverage;
photocellDifferenceAverage += float(photocellDifference)/sampleCountToAverage;


I did some work in Java using USB some years ago and I can share some experiences:

Things are not neary as straightforward as using serial.
Your code will probably be platform specific, windows being a bit more weird about handling usb. (unless using something to abstract that away, like PyUSB which wraps libUSB or openUSB, this however does not guarantee platform independency because these libraries also have their weirdnesses).
If you drop down to USB level programming, things can get very messy (again, this can be abstracted away). USB is (at least in my opinion) a complicated protocol, especially for beginners.

So unless you really need something that only USB can provide, a nice and dandy serial communication will give you much less headaches. Thats why serial did not die until now.

As for debugging why your communication is not reliable I would try several things:

See if your application might send something that is interpreted as a control character
Drop your baud rate to something lower and see if it still loses data. If so, you might overflow the buffer of your receiver (and you would need flow control in this case)
Check your hardware! I've had bad wires or solders on numerous occasions