Relative position using Accelerometer I have a simple scenario please:

Two Arduino Nano 33 IoT devices started moving randomly from the same exact origin(Point = [X0, Y0, Z0]);

Can I use the coordinates queried from each device Accelerometer to get the Euclidean Distance between them?

In other words, Is the relative coordinate/position retrieved from the Accelerometer reliable?

Because I read that getting the relative position every time requires double integrations which leads to big accumulated error over time. Though I might be totally wrong.

Your help is very much appreciated.

What you heard (about double integration and accumulating errors) is correct. Mathematically, you can do this, by integrating each device's acceleration to get its current speed, and integrating the speed to get it's current position, then taking the vector difference in the their positions to get the distance between them.

If you had highly accurate accelerometers in a very noise-free environment (both mechanical and electrical noise), you could do it for a (short) while before the inevitable tiny errors (which are also being integrated!) begin to dominate the data and make the results useless. But as a practical matter - especially for us experimenters using inexpensive equipment and subject to a lot of mechanical and electrical noises on the experimental platform, plus environmental electrical noise - this will happen even more quickly.


Arduino write to memory and self shut down (over MOSFET) - An idea help i would like to ask you for help with design of an circuit.

I have and atmega328p, with detection for voltage on its Vin (Vcc).
I have made and voltage divider and its output i connected to Analog Pin. And i would like to, if an voltage decrease under an certain level (4.5V), to shutdown itself (atmega328p).

As i said the voltage detection is no problem (there is an voltage divider), programing it is as well no problem, but i though that i program it like this:

  Detect voltage on analog pin A0, if the voltage is less than certain
  level (4.5V), write to memory and send to digital pin 3 an "LOW" (0)
  logical state.

This will turn the mosfet off and the atmega will loose its ground (GND) and its shuts down, but i have there an pull-up resistor which when the atmega shutsdown takes its lead an set Gate at MOSFET to high (transistor will turn on) and atmega turns on, then it shuts down and this will do the infinite cycling until there's no power to turn on atmega.

I want to use an Supercapacitor (2.2F 5.5V) to power it when the main input is lost and to give an atmega a time to write to memory and steadily turns off.

I am adding an schematics to better look at the problem.

I know that there is no crystal and capacitors and the other things to make it reliable and fully functional, but this is not a subject of this question.Its an first sketch, which is not completed.

I know some ICs that can detect Voltage and turn its output to some logical state (1 or 0), like an MAX809 (803 or 810) and so on and of course this is my backup plan, but i want to ask you, if you have any great idea to make this without any special ICs and more easily? I also thought about some OPamp or thyristor maybe, i don't know......

Can you help me with an idea or better with an schematics how to do it ? Thanks.

You should be using a P-channel MOSFET (which is set to be normally OFF with a pull-up resistor) and the Arduino is responsible for keeping it on:

simulate this circuit – Schematic created using CircuitLab

In this schematic M1 is normally off.  You press and hold SW1 and the Arduino gets power. The first thing it then does is turn on the GPIO. That turns M2 on, which in turn pulls the gate of M1 LOW turning it on. You can now release M1 and the Arduino will stay on.  When you want to turn off, just switch off the GPIO, turning off M2, which then allows R1 to pull the gate of M1 up again turning off the power.

This arrangement means:

You can control an incoming voltage higher than 5V (thanks to M2 doing the actual switching of the power MOSFET)
You get a soft-power switch to turn the power on
Current draw of the control circuit is basically the incoming voltage divided by the resistance of R1 (you can safely increase this if you want to reduce current draw - 1MΩ is fine).
You can have all the rest of the circuitry on the Arduino side of M1 so it has power removed when switched off (to prevent over-discharge of your batteries)
You are switching VCC, not GND (switching GND can cause all sorts of problems).


Is there an equivalent to Grbl for Excellon PCB drilling? For CNC milling we have code such as Grbl Controller in the PC, and Grbl itself in an Arduino, and these handle the appropriate G-code files. Is there an equivalent package to handle Excellon files and drive a 3-axis drilling machine?

No, there is no existing Arduino library to parse Excellon format drill files in order to control a drilling machine. Looking at the specification it looks to be very similar to G Code, and some brief googling shows that there are various utilities for converting it to G Code that could be run from something like grbl.


How can I declare custom pins when using with ESP8266 in MPU9250 library I want to declare SCL and SCK pins like   Wire.begin(sda_pin, scl_pin); to use with ESP8266 to integrate a MPU 9250/6500 sensor.
I can't figure out a way to declare that in this code exaample provided by https://github.com/bolderflight/MPU9250

in the example of the above it has just passed as Wire to and created object like MPU9250 IMU(Wire,0x68); which was meant to be used with UNO boards(as I think)

And in any case if any of you have seen a library that can be used with the ESP8266 for the MPU 9250/6500 point me on that direction please (I'm trying to get the roll, pitch, yaw)

You can use Wire.pins(sda, scl); before IMU.begin();.
IMU.begin() then calls Wire.begin() without parameters.


Motion Tracking Using Arduino? I'm trying to make a human following robot.Tried using ultrasonic sensors to follow a specific person by Having ultrasonic sensor with the person to send echo to the robot,But it didn't workout.
Any way to track a specific person and follow ?
Any sensors/algorithm to track fast moving object(a person but not specific)?

You need the person to emit a signal and the robot to receive it, sounds simple, but it isn't.  What you are trying to do is position fix the transmitter, in the same way as an ATC locates a plane.

The robot will need at least two directional receivers positioned a certain distance apart (depends of frequency and accuracy) to allow the robot to triangulate the transmitter.  The more receivers the more complex the triangulation.  The frequency of the signal you transmit will affect the distance that the robot can be from the person, research Frequency spectrum and transmission distances.  The longer the distance the signal can travel the stronger the signal will be at close range.  You also have to counter reflections and side lobes which will give you inaccurate readings on the transmitter direction.
Once you have dealt with all of that all you need to do is scan for the strongest signal on your frequency, triangulate it and then head towards it.
Whatever sensor you use the theory is the pretty much the same.

Could you tag the person with a GPS receiver and WIFI/BT and get it to transmit its location.  The robot could then consult its GPS and calculate the delta and move accordingly.


How to put 2 variables in a macro? In a previous question (Append Text to Variable Names: Please Help Me Shorten This Code) I learned that in order to shorten this code:

fanSpeed = readEEPROM(AT24C32_ADDRESS, 1, fanSpeedPos);

I could define a macro at the top of the script like this:

#define readEE(VAR) VAR = readEEPROM(AT24C32_ADDRESS, 1, VAR ## Pos)

And then just use the following shorter code:

readEE(foo);

Which would be expanded out to:

foo = readEEPROM(AT24C32_ADDRESS, 1, fooPos);

My current question is: How can I write a macro that accepts 2 arguments instead of just 1? I couldn't find much information about this concerning Arduinos, so I studied about how to do it in C++ (like from here: http://en.cppreference.com/w/cpp/preprocessor/replace) but it was too complicated for me to understand.

In particular, I would like to learn if it's possible to shorten the following code:

void writeToEE(byte location, bool value, bool &var) {
  writeEE(loc, value); var = value;
}

(Sidenote: the writeEE function looks like this: void writeEE(uint8_t entry, uint8_t data) { writeEEPROM(AT24C32_ADDRESS, 1, entry, data); }. Since the first 2 arguments are almost always constants, that's why I shortened it with another function).

Since whenever I'm using writeToEE, the "entry" variable name is always the "data" variable name with "Pos" appended, I would ideally like to do this (pseudo-code):

#define wrEE(VAR, VAL) VAR = writeToEE(VAR ## Pos, VAL, VAR)

so that when I write this:

wrEE(fanSpeed, 3);

it will be expanded out to:

writeToEE(fanspeedPos, 3, fanspeed);

I just don't know how to pass the 2nd argument ("VAL") into the macro, which is the value being stored in the "fanSpeed" variable, in the "fanSpeedPos" location in the EEPROM. When I try to compile my pseudo code example (was hoping to get lucky!), I get the following error message: "void value not ignored as it ought to be"

In the parameter list of the #define for the macro, separate the second argument from the first with only a comma.  For example:

#define wrEE(speed,var) writeToEE((etc))

The "void value not ignored as it ought to be" error message is a consequence of trying to store the void result of writeToEE.  The solution is to not try to store it.

In C, variable, parameter, and constant names are case-sensitive.


Adafruit Feather 32u4 BLE compatible with Software SPI? Let me preface by saying that I am not super experienced with electronics. I have an Adafruit Feather 32u4 that is using Hardware SPI to communicate over Bluetooth. Unfortunately, I'm also hoping to use the SD library, which also uses Hardware SPI. I am hoping to change the board to use Software SPI instead, so that the two may work together.

The Bluefruit code by default has the following commented out:

/* ...software SPI, using SCK/MOSI/MISO user-defined SPI pins and then user selected CS/IRQ/RST */
Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_SCK, BLUEFRUIT_SPI_MISO,
                             BLUEFRUIT_SPI_MOSI, BLUEFRUIT_SPI_CS,
                             BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);

Which leads me to believe I could use SW SPI but simply uncommenting this and commenting out the HW SPI doesn't seem to work.

I am just not sure if it's not compatible with the board, or I need to do more than this...?

Read SparkFun's guide, Serial Peripheral Interface (SPI), especially the multiple slaves section:

Multiple slaves
There are two ways of connecting multiple slaves to an SPI bus:

In general, each slave will need a separate SS line. To talk to a particular slave, you'll make that slave's SS line low and keep the
rest of them high (you don't want two slaves activated at the same
time, or they may both try to talk on the same MISO line resulting in
garbled data). Lots of slaves will require lots of SS lines; if you're
running low on outputs, there are binary decoder chips that can
multiply your SS outputs.

On the other hand, some parts prefer to be daisy-chained together, with the MISO (output) of one going to the MOSI (input) of the next.
In this case, a single SS line goes to all the slaves. Once all the
data is sent, the SS line is raised, which causes all the chips to be
activated simultaneously. This is often used for daisy-chained shift
registers and addressable LED drivers.

Note that, for this layout, data overflows from one slave to the next,
so to send data to any one slave, you'll need to transmit enough data
to reach all of them. Also, keep in mind that the first piece of data
you transmit will end up in the last slave.
This type of layout is typically used in output-only situations, such
as driving LEDs where you don't need to receive any data back. In
these cases you can leave the master's MISO line disconnected.
However, if data does need to be returned to the master, you can do
this by closing the daisy-chain loop (blue wire in the above diagram).
Note that if you do this, the return data from slave 1 will need to
pass through all the slaves before getting back to the master, so be
sure to send enough receive commands to get the data you need.


Which Bluetooth Module can I use with Arduino Micro/Mini? I need to use a Bluetooth module with an Arduino Micro/Mini.

Please suggest which one would be the best, HC 05/06, or any other?

I have had good results using the Bluefruit LE UART Friend module from Adafruit with a 32u4 micro Arduino type module, there are only a few pins to connect up to get things going (do remember to follow the instructions to pull the CTS pin to ground).

As per the previous answer it really does depend on what you want to do with it - but this module does Low Energy, can be configured as a "Beacon" and there is a companion App for Android/iOS.


Set the wall clock time or change GMT offset without ntp server? I have been able to get the current time from an NTP server and set what appears to be an internal clock using the configTime() function from the ESP32 core.  I can then get the current time with the function getLocalTime().

I would like to be able to set the time returned by getLocalTime() from user input rather than from an NTP server.  I would also like to be able to update the GMT Offset without needing to reconnect to the server.

How do I interact with the clock value used by getLocalTime()? Is there documentation for this clock somewhere?

per request the SimpleTime example from the ESP32 install:

#include <WiFi.h>
#include "time.h"

const char* ssid       = "YOUR_SSID";
const char* password   = "YOUR_PASS";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;
const int   daylightOffset_sec = 3600;

void printLocalTime()
{
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
}

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

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

void loop()
{
  delay(1000);
  printLocalTime();
}

The functions configTime and getLocalTime are from ESP32 core file esp32-hal-time.c. This wraps the ESP32 SDK functions. You can use the SDK functions to set the time and zone. They work with the RTC peripheral of the ESP32.

You can use setTimeZone to set the time zone.

The time.h is standard C time library. The ESP32 SDK makes it to work with the built in RTC (reference). To set the time it gets complicated. You would have to use undocumented SDK time functions.


Only return button state once in X amount of time? I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW) {
    Serial.println("PASSED!");
  }
}

Would spit out something like this with a single quick press of the button:

PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!
PASSED!

But what I want is for a single button press to just return PASSED! once for that single button press.

To avoid this problem you can use a boolean variable as a flag that permit to enter inside the if only once.

bool flag = true;

void loop() {
  passButtonState = digitalRead(passButton);

  if (passButtonState == LOW && flag) {
    Serial.println("PASSED!");
    flag = false;
  }
}


How can I create a battery level circuit Im trying to create a circuit so that I can monitor the voltage drop on my battery and send an message when the voltage drop reaches the drop out. But I'm having some problems with my voltage divisions.

I created this circuit to enable a flow so that it does not flow (drain the battery) while not necessary. But as I understand it analog input must not be above 1 volts.

The +3.3V represent the MCU (ESP-12, arduino with wifi) turning the circuit on, letting battery flow to the analog input (red circled ground). However, at analog input, the volt is 2,24V, which is more than the 1V it should be. Do I just divide it again? If I divide it again ill be at 1,12 so I need to divide it yet again. I don't think Im doing it right.

The maximum voltage of the analog pin on the ESP-12 is 1V. How can I get there?

Firstly, if I understand your schematic right, you're not "dividing" anything there. If the ringed red symbol is where you are connecting the ADC then either you will see near 4V on there (if it's only connected to the ADC), or 0V (if it's connected to ground).

You should be connecting the ADC between the resistors to get a reading.

Secondly, you should be using a P-channel MOSFET, not a PNP transistor. You can use a PNP transistor, but you will have to subtract the voltage drop imposed by the transistor from your calculations to get any meaningful reading. With a P-channel MOSFET, the on-resistance would be (or should be if you choose a sensible one) negligible compared to the resistance of the voltage divider.

You are right that you can't exceed 1V on the ADC, so you will have to size your resistors accordingly. You aren't restricted to just using a pair of 10K resistors - you can choose any values you like that yield the correct result.

simulate this circuit – Schematic created using CircuitLab

In this example, 10K and 2.2K give you no more than 0.9V from a 5V input. (Tip: choose an input voltage slightly higher than you expect to give a small safety margin).

I calculated those by:

Use the voltage divider formula R2 = R1×(1/((VIN/VOUT)-1)) to calculate the lower resistor (2500Ω).
Choose the next lowest "common" resitor (2200Ω)
Re-calculate the new output using the chosen resistor values using VOUT = (R2/(R1+R2))×VIN (0.9V)


How can I send and receive data from an Arduino Uno to Arduino Mega using I2C? I am trying to send data as a string from an Arduino Uno to another Arduino Mega. I have read about the I2C connection where we connect the RX to TX oppositely.

How to start and send and receive data between them? I have no idea how the code can be written.

At instructables there is a good post.

In short the code is

Master code:

// Include the required Wire library for I2C
#include <Wire.h>
int x = 0;
void setup() {
  // Start the I2C Bus as Master
  Wire.begin();
}
void loop() {
  Wire.beginTransmission(9); // transmit to device #9
  Wire.write(x);              // sends x
  Wire.endTransmission();    // stop transmitting
  x++; // Increment x
  if (x > 5) x = 0; // `reset x once it gets 6
  delay(500);
}

Slave code

// Include the required Wire library for I2C
#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}
void loop() {
  //If value received is 0 blink LED for 200 ms
  if (x == '0') {
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

In the instructables post a lot more explanation is shown.


Problem with NFC on Arduino MEGA My Objective :

I am trying to send my Mifare's unique number with some other parameters to my server database. As soon as the tag come closer to NFC, it detects, and some additional details are passed to the server Database.

Steps done :

I have Arduino UNO, Arduino GSM shield and Adafruit NFC shield . I had tried my test with UNO and works well. But to add some more features, due to memory salvation it could not be achieved through UNO. Then we moved to MEGA.
There are some changes need to be done with MEGA to make [url]http://arduino.cc/en/Guide/GSMShieldLeonardoMega[/url] GSM shield coordinate with the microcontroller[Take the Pin 2 out from GSM shield and with jumper connect Pin 2 with Pin 10]. Then we did and we tested it with GSM web client example and worked fine.
Now to accomplish our goal, when we placed NFC shield above the GSM shield and executed same GSM web client example, it is not working. And Suddenly once in a blue moon it connects to the GSM network and works . But often, it fails.

[code]

/*
  Web client

 This sketch connects to a website through a GSM shield. Specifically,
 this example downloads the URL "http://arduino.cc/asciilogo.txt" and
 prints it to the Serial monitor.

 Circuit:
 * GSM shield attached to an Arduino
 * SIM card with a data plan

 created 8 Mar 2012
 by Tom Igoe

 http://arduino.cc/en/Tutorial/GSMExamplesWebClient

 */

// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP

void setup()
{
  // initialize serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while(notConnected)
  {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

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

  // if you get a connection, report back via serial:
  if (client.connect(server, port))
  {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for(;;)
      ;
  }
}

What is the problem? and where is the problem ?

It is likely that placing the GSM shield between the Arduino Mega and the NFC shield is interfering with the GSM antenna.  Antennas react in strange and usually less useful ways when large conductors are placed nearby.

You could try reversing the order of attaching the shields, or you could try spacing the shields further apart using "stackable Arduino headers" (you can do a web search for suppliers).  If there is an option for an external antenna, that would be even better.

If you get GSM working, you might still have some trouble with the NFC shield, as it's possible that the GSM transmitter being so close could interfere with the NFD's circuitry - not because they use the same frequences, but just because any conductor so close might pick up electrical noise, and there will be various sensitive circuitry in the NFC electronics.


Serial, Numbers sent as Floating Point and Characters are different at 1e-8 level I have some code that generates random numbers on the Arduino, it then sends these random numbers firstly, using Serial.print(float data,int lenght) and as a floating point number using the following function

void send_float (float arg)
{
  // get access to the float as a byte-array:
  byte * data = (byte *) &arg;

  // write the data to the serial
  Serial.write (data, sizeof (arg));
  Serial.println();
}

I then receive this data using python, take the absolute difference of the two values, discard any differences less than the length with which I send the string and output the rest to the screen.

I observe two things, a) Fluctuations of the order with which I send the data (ie. if I send to 6 decimal places then I see fluctuations of ~1e-6), this is reasonable and b) I see fluctuations of absolute value 1e-8 or lower independent of what accuracy I send the string.

Even if I send the string to 11 decimal places, when I compare against the float I see fluctuations up to but not above 1e-8.

Why? This doesn't make any sense. My full code is actually the answer to an old unanswered stack exchange question

This is a somewhat dumb question but, in case anyone else searches it as pointed out:

  The precision of a float is around 7.2 decimal digits. en.wikipedia.org/wiki/Single-precision_floating-point_format –  BrettAM

So in python the number goes float -> double -> decmial, whereas on the arduino the number goes float -> decimal. The additional step of the double in the case of python causes the discrepancies. But anything after the 7th decimal place is nonesense anyway.


I2C send and read 2 bytes many slave I've already sent you the code but you told me to format it, so I tried this way ..

the problem I got is it doesn't read good the 2 slave (sender) to the master

(reader) ...you told me LAST TIME (DON'T DO SERIAL PRINTLN IN THE CALLBACK

ROUTINE) so I tried this code (I've got some data from both but not in order)

here's the slave 1 and 2 code (I only change the  slavedeviceId address)

#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

byte x = 0;
//
const byte AnalogueInputPin = 0;

const byte SlaveDeviceId = 2;

void setup() {
  // Start I2C bus as master
  Wire.begin();
}

void loop() {
  int input0 = analogRead(x);
  // Send two bytes to slave.
  Wire.beginTransmission(SlaveDeviceId);
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);
  Wire.endTransmission();

  delay(10);

  x++;
  if (x == 4) {
    x = 0;
  }

  delay(40);

}

here's the master (reader)

thanks for your time it is realy intructive for me !!!

#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
int S1;
int S2;
int c;
int cc;

void setup() {
  // Start I2C bus as a slave
  Wire.begin();
  Wire.onReceive(receiveCallback);
  Serial.begin(9600);
}

void SLAVEone() {
  Wire.begin(SlaveDeviceId);
  delay(5);
  Wire.onReceive(receiveCallback);
  delay(5);
}

void SLAVEtwo() {
  Wire.begin(SlaveDeviceId2);
  delay(5);
  Wire.onReceive(receiveCallback2);
  delay(5);
}

void receiveCallback(int aCount) {
  if(aCount == 2) {
    int receivedValue  = Wire.read() << 8;
    receivedValue |= Wire.read();
    //Serial.print(c);
    //Serial.print(" S1 = ");
    //Serial.println(receivedValue);
    S1 = receivedValue;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount);
  }
  c++;
  if (c == 4) {
    c = 0;
  }
}

void receiveCallback2(int aCount2) {
  if (aCount2 == 2) {
    int receivedValue2  = Wire.read() << 8;
    receivedValue2 |= Wire.read();
    // Serial.print(cc);
    //Serial.print(" S2 = ");
    //Serial.println(receivedValue2);
    S2 = receivedValue2;
  } else {
    Serial.print("Unexpected number of bytes received: ");
    Serial.println(aCount2);
  }
  cc++;
  if (cc == 4) {
    cc = 0;
  }
}

void loop() {
  for(int y = 0; y <= 3; y++) {
    SLAVEone();
    Serial.print(c);
    Serial.print(" = S1 = ");
    Serial.println(S1);
    delay(10);
  }
  for(int y = 0; y <= 3; y++) {
    SLAVEtwo();
    Serial.print(cc);
    Serial.print(" = S2 = ");
    Serial.println(S2);
    delay(10);
  }
}

There are so many mistakes in your code. I'll do my best to correct them using comments. The code for the slaves should be as follows:

#include "Wire.h"

//
// i2c_test_01

//
// This demonstrates a master transmitting to a slave.
//

// The master transmits a value read from an analogue port.

// The slave sends the value to the serial device.
//

int inp = 0;  // input pin

const byte SlaveDeviceId = 2;

void setup() {
  Wire.begin(SlaveDeviceId);  // here the slave joins the bus, with its address as argument to begin()
  Wire.onRequest(callback);  // here you indicate what the slave should do if a bus master queries it
}

void callback() {
  int input0 = analogRead(inp);
  // Send two bytes to master
  Wire.write(input0 >> 8);
  Wire.write(input0 & 255);

  inp++;
  if (inp == 4) {
    inp = 0;
  }

}

void loop(){}

This is the master's code:

#include "Wire.h"

const byte SlaveDeviceId = 1;
const byte SlaveDeviceId2 = 2;
char inputDev = 4;  // number of devices connected to slave analog inputs

void setup() {
  Wire.begin();   // no argument here since its a master
  Serial.begin(9600);
}

//the onReceive() method is for slaves receiving from a master, so we dont use it here

void loop() {
  Serial.println("\r\nSlave 1: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }
  Serial.println("\r\nSlave 2: ");
  for (char i = 0; i < inputDev; i++){
    Wire.requestFrom(SlaveDeviceId2, 2);
    delay(1);  // more than enough time for all the data to come in
    int val = Wire.read() << 8;
    val |= Wire.read() & 0xFF;
    Serial.print(val);
    Serial.print(",");
  }

}


Graphing force sensor data routed through HX711? I'm using the code off of the sparkfun website HX711 hookup guide (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide#arduino-code) to attempt to create a scale.

Currently I have output data of weight in the serial monitor - is there an easy way to then graph this data with regards to time? I've spent an hour fooling around with Processing and googling, but haven't had any luck.

Thanks!

Include the Time library in your sketch, then print the time and your sensor output as a comma separated list. Your output to the serial monitor can then be written to .csv file using PuTTY, which you will need to download in order to collect data (I used online tutorials to figure out writing to a file with PuTTY). Once in a .csv, you can open the file in Excel to graph the data.


Secure HTTPS request fails 90% of the time I'm using a NodeMCU, which is connected to an enterprise network at a school. The information given in the GET requests that the ESP8266 sends is sensitive, so naturally we want to make it secure and encrypted - enter SSL. We do the request like so;

HTTPClient http.begin(url, thumbprint)

However, on the network at the school, doing this request fails 90% of the time, so I did a few tests - 100 requests to the exact same IP and certificate, noting how many went through;

School network

HTTPS requests: 10/100 successful [10%]
HTTP requests: 100/100 successful [100%]

Private home network

HTTPS requests: 100/100 successful [100%]
HTTP requests: 100/100 successful [100%]

We have also tried using the WiFiClient class, and while 100% of the requests went through, each one took 15 seconds which is too long.

My question is; what would the problem be, and what can we do to fix it? Can I do something in the code, or on the network?

Increase the timeout for your request with HTTPClient.setTimeout(). Note the timeout is in milliseconds.

HTTPClient http;
http.setTimeout(15000); // 15 Seconds
http.begin(url, thumbprint);


How to connect multiple NodeMCUs and 1 PC over wifi and have PC control NodeMCUs? I am trying to design a laser tag system using multiple NodeMCUs in the guns. I am trying to figure out how to connect and control them over WiFi. I also need a computer connected that will control the game. I was origionally just thinking I could use the PC as a server that tells all the guns what to do. Im sure this is possible, but it looks very complicated and I dont know a whole lot about theese types of things. So then I was thinking it might be better to have another NodeMCU connected to the computer with USB. That NodeMCU would then act as a WiFi server for the clients(Guns). That way, the PC would only have a GUI for that MCU, and once started the MCU would actually control the game. Is that the best option or is there some easier and simpler way? That seems like the best solution to me. I am just making sure this will work. Are there any other solutions or tips? Here is a basic idea of what would happen when someone shoots someone else.

Gun 1 will send IR signal (Shoot) gun 2.

Gun 1 will tell the server that it tried to shoot gun 2.

Gun 2 tells server it got IR signal from gun 1.

Server will first make sure no other guns were shot accidentally at the same time. If they were, it will determine which gun received the IR signal stronger. That gun will be the one actually shot.

Server will add points to gun 1 score and remove points from gun 2 score on both PC monitor and small screens on guns themselves.

Thanks!

I would not consider it easier to connect a NodeMCU to the PC just to act as a Wifi interface. Most computers already have means of connecting to a network. Wether it is via Wifi or LAN is not important. Every PC has a LAN port on it's mainboard. You could connect it directly to your Wifi router.

Using a NodeMCU as you proposed would mean, that you have to program for 2 platforms: The main logic on the PC and the Wifi communication on the NodeMCU. That does not really make it easier.

The communication depends on your wanted topology. I would build the PC as Server and the NodeMCUs as clients. You can easily create a webserver programmatically with python, for example with Flask, as I have done it once. Though there even might be better webserver modules for python. It is really not that difficult and you already need to write a program for the game logic on the PC,so why not using python. Though of course you could choose any language, that you like. Python is just an easy choice, that I already did.


Weight scale with Arduino: calibration step I'm not an expert about Arduino and I'm studying to create a project related to the bees remote monitoring.
I would like to monitor the internal humidity and temperature and the weight of the beehive boxes.
About the weight parameter my idea is to make a structure with 4 load cells.
I watched some video tutorials related to the creation of a weight scale with Arduino. I saw that it's necessary to calibrate the scale without any weight on the scale every time that Arduino will be started.
I'm not able to understand if there is a way to have this calibration in a different way: I mean,  I will place the beehives on my weight scales only one time and Is not possible to remove and put them back for each calibration step.
Is it really necessary or is there a way to have the calibration with the weight on the scales also?

It may be that in this application (beehive monitoring) it is not required to re-calibrate your load sensors before each use.  When a person is observing a scale to measure their own weight they will be sensitive to the scale reading zero before each use.  Even though being, say, a lb off is likely less than a 1% error when measuring their total body weight.  This site talks about load cell calibration and "recommends a yearly recalibration interval".  They also talk about temperature compensation.
As temperature and humidity will be monitored.  And nonlinear load sensor response to weight can be compensated in software, consider testing your setup under different conditions to determine what considerations need to be taken into account to provide the desired accuracy.

This image is from https://www.futek.com/load-cell-calibration-services


Is my BMA421 locked up? I have been trying to set up the BMA421 motion sensor in a nrf52 based smart watch, using the datasheet for the BMA423, which has the same interface. I had got the sensor working well with the original source code, but I was trying to set it up myself. It is connected via I2C, address 0x18.
I made some mistakes in my original code. I was trying to initialise the chip with a 6Kb byte stream (as in the original source), in chunks of 64 bytes. I didn't resend the register at the start of each data chunk, so ended up writing bytes to random registers.
Unfortunately, I have managed to get the sensor into an unrecoverable state - it now returns 0xFF to all reads, and doesn't respond to a soft-reset code (register 0x7E=0xB6). Even exhausting the watch battery to power cycle the chip doesn't seem to help.
I have found someone with a similar issue on the Borsch Sensortec forum, so I am hoping that a complete battery discharge works.
Does anyone have any other suggestions?

The BMA421 was not locked. An erroneous write to the wrong register had switched it to the (non-existant) SPI interface. The solution was to power cycle the sensor.


How to wire a small quadcopter drone with resistor and breadboard (If possible)? http://www.instructables.com/id/SpeechVoice-Controlled-Arduino-Drone/?ALLSTEPS

Hi guys!

I am following this project but I do however not have all the items currently at home so I was thinking if there is an optional solution.

I do not have any resistors or a breadboard currently at home so I was wondering if there is an optional solution.

What I have is, arduino uno + arduino mini and hc-05 bluetooth and of course 4 small drone motors. On top of this I have TIP-122 transistors and a l293d motor driver.

Could I somehow make it work with that considering i do not have resistors or a breadboard at home?

I know how to solder of course so if I need to solder wires that is not a problem. I appreciate any help very much!!

You need resistors where that article puts them, otherwise you could brownout the whole thing. You may be able to get away without a PCB, at the cost of reduced stability. Find or borrow the three resistors needed for the project, and then I recommend that you order both a large pack of 1% resistors as well as a variety of PCBs when you are able to.


Low power wifi temperature sensor I want to make a wifi-enabled temperature sensor and place it inside my HVAC system to measure and push the temperature to a central server, every minute or so.

I have a LoLin NodeMcu v3 unit laying around, and I am wondering if it is possible to use this one - and have it last for many years inside the HVAC system?

I realize the LoLin unit has a onboard wifi chip, I also realize LoLin takes 3v input. Aside from that, I am pretty blank.

Yesterday I tested the LoLin board by programming it with the following code, which lists networks in the vicinity. It worked great:

#include "ESP8266WiFi.h"

void setup() {
  Serial.begin(9600);
  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(2000);
  Serial.println("Setup done");
}

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

  int n = WiFi.scanNetworks();// WiFi.scanNetworks will return the number of networks found
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

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

The actual question

Is the LoLin board a feasible board for making a low power wifi enabled temperature sensor? Or should I rather make board that communicates with a wall-connected parent unit via radio?

Yes, the NodeMCU can connect to a temperature sensor and forward that on to your WiFi access point to send to the internet.

Yes, the NideMCU can run from batteries.

Can it do it off one battery for many years? Only if that battery contains a small nuclear reactor.

Running something from battery for many years requires incredibly close attention to detail and incredibly tight component specifications, even down to the precise battery chemistry used. It's a very very difficult task for which people are very highly paid.

When you start looking at periods like that you begin to run up against the problem of battery self-discharge. Getting your power consumption down to an absolute minimum is a must, but even then if you have near zero power consumption the battery is still going to go flat by itself. So you have to invest time and effort into selecting a battery technology with a very low self-discharge.

All that is pretty moot though with the NodeMCU since:

WiFi is a power hungry technology. You can expect hundreds of mA while transmitting, and doing that once a minute for, say, 10 seconds (reconnecting to the WiFi takes time) will give you quite a high average power consumption just from the WiFi
The NodeMCU is far from optimised WRT power consumption. Linear voltage regulators, poor choice of components for low power consumption, etc, abound.

So yes you can run it from batteries, but be prepared to replace the batteries very often. By "very often" I mean every couple of days.

That means you basically have two options:

Don't use the NodeMCU but instead use something designed to be incredibly low power and run for long periods on battery (typically it won't use WiFi but something more efficient like nRF24L01+)
Don't use batteries. Hard-wire your NodeMCU into a mains-connected power supply.


How to compare a string How to compare a string coming from serial monitor with some predefined text stored  as a local variable?
If I say:

int led = 2;
String a = " abcds";

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

void loop() {
  String b = Serial.read();
  Serial.println(b);

  if (b != a) {
    digitalWrite(2,LOW);
  }
  else
  {
    digitalWrite(2,HIGH);
  }
}

just as an example, this code will not compile because on the serial I receive bytes and I want to compare with a string.
So my question is...
how should be done?

version using String (not recommended, but it makes simpler to understand the following C-string version)

#define LED 2
const char* a = "abcd";

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    String s = Serial.readStringUntil('\n');
    s.trim();
    if (s == a) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}

the version with C-string:

#define LED 2
const char* a = "abcd";
char buffer[32];

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    size_t l = Serial.readBytesUntil('\n', buffer, sizeof(buffer - 1));
    if (buffer[l - 1] == '\r') {
      l--;
    }
    buffer[l] = 0; // the terminating zero
    Serial.println(buffer);
    if (strcmp(buffer, a) == 0) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
}


Arduino Uno + SIM808 EVB 3.2.4 not working properly? So recently I found this tutorial online about the SIM808. It looked super cool so I ordered the sim808 evb 3.2.4 off amazon. Hooked up the module and connected the RX (11) and (10) TX pins.
Here is the code I'm working with tried to follow along as best I could with the tutorial but now I am completely confused, purchased a SIM card activated the SIM card and it seems to be connecting just fine
In the serial monitor sometimes I receive this: 14:05:06.243 -> Init Success, please send SMS message to me!
But most of the time I'm receiving this: 14:04:37.586 -> Sim808 init error
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>
#define MESSAGE_LENGTH 160
char message[MESSAGE_LENGTH];
int messageIndex = 0;
char MESSAGE[300];
char lat[12];
char lon[12];
char wspeed[12];
char phone[16];
char datetime[24];
#define PIN_TX 10
#define PIN_RX 11
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,
void sendSMS();
void getGPS();
void readSMS();
void setup()
{
mySerial.begin(9600);
Serial.begin(9600);
//******** Initialize sim808 module *************
while(!sim808.init())
{
Serial.print("Sim808 init error\r\n");
delay(1000);
}
delay(3000);
Serial.println("SIM Init success");
Serial.println("Init Success, please send SMS message to me!");
}
void loop()
{
//*********** Detecting unread SMS ************************
messageIndex = sim808.isSMSunread();
//*********** At least, there is one UNREAD SMS ***********
if (messageIndex > 0)
{
  readSMS();
  getGPS();
  sendSMS();

  //************* Turn off the GPS power ************
  sim808.detachGPS();

  Serial.println("Please send SMS message to me!");

}
}
void readSMS()
{
Serial.print("messageIndex: ");
Serial.println(messageIndex);
sim808.readSMS(messageIndex, message, MESSAGE_LENGTH, phone, datetime);
//*In order not to full SIM Memory, is better to delete it
sim808.deleteSMS(messageIndex);
Serial.print("From number: ");
Serial.println(phone);
Serial.print("Datetime: ");
Serial.println(datetime);
Serial.print("Recieved Message: ");
Serial.println(message);
}
void getGPS()
{
while(!sim808.attachGPS())
{
Serial.println("Open the GPS power failure");
delay(1000);
}
delay(3000);
Serial.println("Open the GPS power success");
while(!sim808.getGPS())
{
}
Serial.print(sim808.GPSdata.year);
Serial.print("/");
Serial.print(sim808.GPSdata.month);
Serial.print("/");
Serial.print(sim808.GPSdata.day);
Serial.print(" ");
Serial.print(sim808.GPSdata.hour);
Serial.print(":");
Serial.print(sim808.GPSdata.minute);
Serial.print(":");
Serial.print(sim808.GPSdata.second);
Serial.print(":");
Serial.println(sim808.GPSdata.centisecond);
Serial.print("latitude :");
Serial.println(sim808.GPSdata.lat);
Serial.print("longitude :");
Serial.println(sim808.GPSdata.lon);
Serial.print("speed_kph :");
Serial.println(sim808.GPSdata.speed_kph);
Serial.print("heading :");
Serial.println(sim808.GPSdata.heading);
Serial.println();
float la = sim808.GPSdata.lat;
float lo = sim808.GPSdata.lon;
float ws = sim808.GPSdata.speed_kph;
dtostrf(la, 4, 6, lat); //put float value of la into char array of lat. 4 = number of digits before decimal sign. 6 = number of digits after the decimal sign.
dtostrf(lo, 4, 6, lon); //put float value of lo into char array of lon
dtostrf(ws, 6, 2, wspeed);  //put float value of ws into char array of wspeed
sprintf(MESSAGE, "Latitude : %s\nLongitude : %s\nWind Speed : %s kph\nMy Module Is Working. Mewan Indula Pathirage. Try With This Link.\nhttp://www.latlong.net/Show-Latitude-Longitude.html\nhttp://maps.google.com/maps?q=%s,%s\n", lat, lon, wspeed, lat, lon);
}
void sendSMS()
{
Serial.println("Start to send message ...");
Serial.println(MESSAGE);
Serial.println(phone);
sim808.sendSMS(phone,MESSAGE);
}`

I recommend you to use AT command ..then using some kind of library. You need to dig into library for better information.
https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/
Go through this link....this will give you a rough idea.


Knowing if ESP32 wakes up itself or manually I have a project where I put an ESP32 to deep sleep for a certain amount of time, eg: 1h
To be able to self-awaken a cable must be connected from GPIO 16 to the reset pin, so basically the ESP pulls down pin 16 and causes itself to reset.
I also need the possibility to manually waken up the ESP, so in parallel to this cable I connect a button to GND, so I can manually reset the ESP and waken it up.
However I need to be able to tell if the ESP has awaken itself because one hour has passed or if it has been manually awaken.
I cannot connect the ESP to a internet time provider to check the time, so my first though wasto connect the button also to an input and read it when the ESP starts.
However the ESP won't start until the button forcing RST low is released and then it's too late to read it and see if it was pressed.
Is there a way that I can tell if the ESP was manually reset or if it woke up by itself?

I think you're getting confused between the ESP32 and the ESP8266. There is no need to connect GPIO16 to reset on the ESP32.
Instead the ESP32 has the "ULP" - Ultra Low-power Processor in it (essentially the RTC processor) which is what sends wakeup signals to the ESP32 cores. It is this which wakes the system up after an hour.
The ULP can also trigger a wakeup from other sources - most often used to wake up from an external signal, such as your button. But this only works if that signal is connected to one of the RTC input pins (GPIOs 34 to 39), or certain interrupt enabled pins (you can read more about what can wake the system up here).
Once a wakeup has happened you can then query the ULP to find out why it woke the ESP32 up using the esp_sleep_get_wakeup_cause() function.


STM32 ST LINK not working on Linux I have a STM32 that I programm in Windows, I connected them like this:
https://electronics.stackexchange.com/questions/515810/ftdi-and-st-link-devices-together-to-stm32
Now, I moved to Linux (Ubuntu 18.04) but the Arduino IDE cannot find the ST LINK, I got the following
      -------------------------------------------------------------------
                    STM32CubeProgrammer v2.5.0
  -------------------------------------------------------------------

libusb:warning [libusb_open] internal signalling write failed
ST-LINK error (DEV_USB_COMM_ERR)
libusb:warning [libusb_close] internal signalling write failed, closing anyway
the selected serial port libusb:warning [libusb_close] internal signalling write failed, closing anyway
does not exist or your board is not connected

Am I missing some configuration?

These are my personal notes I wrote to myself a while back. See if they work for you too. Some of the filenames and versions may be slightly more up-to-date now, but I think this should be what you need. I look forward to hearing back from you to hear if this works for you.
STM32CubeProgrammer Linux install instructions:
Help manual: UM2237, here: https://www.st.com/en/development-tools/stm32cubeprog.html --> download link at bottom; direct link.

Download & install STM32CubeProgrammer: https://www.st.com/en/development-tools/stm32cubeprog.html#get-software --> click "Get Software" download button.

Download STSW-LINK007 (ST-LINK, ST-LINK/V2, ST-LINK/V2-1 firmware upgrade) tool: https://www.st.com/en/development-tools/stsw-link007.html.

Extract the zip file, but do not install it. There is no need to install it, as this tool comes built-in to the STM32CubeProgrammer tool above too, and all we really need from this STSW-LINK007 zip file is the readme and some udev rules.

Reference the readme here: stsw-link007_2.32.22/readme.txt, or even better, the readme here: stsw-link007_2.32.22/AllPlatforms/StlinkRulesFilesForLinux/Readme.txt

Install the udev rules:
cd stsw-link007_2.32.22/AllPlatforms/StlinkRulesFilesForLinux
sudo cp *.* /etc/udev/rules.d

Referencing section 1.2.1 of UM2237 (download link above):
sudo apt-get install libusb-1.0.0-dev

Reload udev rules (source: https://unix.stackexchange.com/a/39371/114401):
sudo udevadm control --reload-rules && udevadm trigger

Unplug and plug in the STLink programmer.

Open and Run STM32CubeProgrammer GUI to verify things.

Make a symbolic link to the programmer CLI executable so we can run it as STM32_Programmer_CLI:
mkdir -p ~/bin
sudo ln -s ~/STMicroelectronics/STM32Cube/STM32CubeProgrammer/bin/STM32_Programmer_CLI \
~/bin/STM32_Programmer_CLI

If this is the first time ever creating and using your ~/bin directory, where we just placed the executable symbolic link above, log out and log back in to have Ubuntu automatically place this folder into your PATH.

Now flash your chip with the programmer. Example flash command:
(Refer to UM2237--link above--for more info on commands.)
# connect, erase all, write, and verify; Note: the `-e all` option
# to "erase all" is NOT necessary, as erasing the sectors to be
# flashed is automatic when you do the write (`-w`) command!
# The `0x8000000` part specifies the starting address in the chip to
# start programming. Leave this off to use the chip's default
# programming start address, or, adjust this address to your specific
# needs for your chip.
STM32_Programmer_CLI -c port=SWD -w my_hex_file.hex 0x8000000 -v


Mega 2560 pin output power and control question I am trying to determine the total pin power requirements for my Mega 2560 project; it will connect to 3 1m Neopixel strips and 5 RGB laser fiberoptic lights, and control them via PWM. Each strip and light will have its own external power supply. The laser lights will be controlled by an Adafruit TLC5947 LED Breakout board with 3 (R,G,B) inputs. Further, each laser light is turned on by a logic high command.

My questions are:
How can I determine the total pin outputs? Can all this be controlled safely from the Mega, or will I need to add transistors? I have read 200mA is the maximum for the Mega, however I have found a seemingly definitive post on Arduino.cc that states 800mA is the maximum.
https://forum.arduino.cc/index.php?topic=327742.0

here's my rough schematic:

Thank you in advance!

Neopixels only need a control signal and Gnd when powered externally - connect the external power supply Gnd to the Mega Gnd as well.

The 2560 chip can definitely work with 800mA (200mA per VCC & Gnd pin, and there are 4 of each). The onboard supply can't cope with that - you get a max of 500mA from USB (due the 500mA PTC fuse, the big gold or green part next to the USB connector), or something under an 1000mA depending on how 5V is created. 12V into the barrel jack and high current will over heat the 5V regulator. 7.5V into the barrel will give you a better shot at high current. Then there is 1V rated reverse polarity protection diode between the barrel jack and the regulator.  You can't put 5V into the barrel and get 5V out, you need to overcome the diode and the regulator. 7.5V wallwarts work well for that. www.dipmicro.com used to carry 7.5V/1A wallwarts, I don't know if they still do.  If you decide to use an external 5V source via the power header, then the power headers are only rated for 1A current as well.
I use this one for 5V projects, 4A to power the Arduino, make yourself a power cord splitter and have 5V for other stuff as well direct from the wallwart, and not off the Mega board.

Are the lasers controlled by current into the R,G,B pins, or are they externally powered and R,G,B are just control signals? If their power comes from RGB, then you'll also want to power the TLC5947 seperately and just connect control signals and Gnd to the Mega.


Send ECG signal with NRF24L01 from Arduino to Raspberry Pi 3 I'm using nRF24L01 to send ECG samples from an Arduino to Raspberry Pi, the type of sample is double after denoising, and I stock them in a byte[8] to send 8 by 8 sample. When I print the sample before stockage that show the good results, but if I print data stored in the byte the signal show a lot of fluctuations. In Raspberry Pi, I can read correctly byte data like transmitted, but if I send them in a vector of double or int in reception (python) don't give the same frame transmitted.

#include <IIRFilter.h>
#include <FIRFilter.h>

#include <SPI.h> // Call SPI Library
#include <nRF24L01.h> // Call NRE Version Library
#include <RF24.h> // RF24 Header File

#define CE_PIN  9
#define CSN_PIN 10
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN);

const int ECG_samplefreq  = 200;//sampling frequcy
const int DC_offset = 511;

const double b_lp[] = {0.0026, 0.0155, 0.0388, 0.0517, 0.0388, 0.0155, 0.0026};
const double a_lp[] = {1.0000, -2.3797, 2.9104, -2.0551, 0.8779, -0.2099, 0.0218};

IIRFilter lp(b_lp, a_lp);
unsigned int i = 0;

void setup() {
  Serial.begin(9600);
  radio.begin();//Intializing NRF24L01 Module
  radio.setPALevel(RF24_PA_MAX);
  radio.setChannel(0x76);
  radio.openWritingPipe(pipe);// For Transmitting Operation, Must OpenWritingPipe
  radio.enableDynamicPayloads();
  radio.powerUp();
  pinMode(7, INPUT); // Setup for leads off detection LO +
  pinMode(8, INPUT); // Setup for leads off detection LO -

}
void loop() {
  const static unsigned long ECG_interval  = round(1e6 / ECG_samplefreq);  //sampling period = 5000 ms => 200 sample by 1 seconde
  static unsigned long ECG_prevmicros = micros();
  byte  s[8] = {0};

  if ((digitalRead(7) == 1) || (digitalRead(8) == 1)) {
    Serial.println('!');
  }

  else {
    for (int i = 0; i < 8; i++)
    {

      if (!Serial) {
        ECG_prevmicros = micros();
      }
      else if (micros() - ECG_prevmicros >= ECG_interval)
      {
        int value = analogRead(A5);
        double filtered = lp.filter( value - DC_offset);

        filtered = round( filtered + DC_offset);
        s[i] =  filtered
        Serial.println( s[i]);
        ECG_prevmicros += ECG_interval;

      }
    }
    radio.write(&s, sizeof(s) ); // sending in real time ECG sample. 8 sample by transmission . 8 => 4 oct of one sampe = 32 oct by transmission.

  }
}

the problem thant i put in s[i] a double of four octs. im searching how can i send them whithout byte array, and receive the correctly. So thankful for your help

I see multiple flaws in your code:

radio.write(&s, sizeof(s)); does not what you think it would. The correct statement would be radio.write(s, sizeof(s)); without the ampersand.
You are using double. Not using floating point numbers at all would be preferable.
Your s is of type byte. Thus it only holds 8 bytes. So your floating point calculations are being truncated to the range [0, 255]. From your problem description this is not what you are trying to achieve, I think.


How to convert byte array to float How can I convert a byte array to float?

Code:

void send_data() {
    CCPACKET data;
    data.length=2;

    float lon=26.533255;
    float lat=27.533463;

    data.data[0]=lon;
    data.data[1]=lat;

    if(cc1101.sendData(data)){
    Serial.println(data.data[0]);
    Serial.println(data.data[1]);

    Serial.println(" sent ok ");
    return true;
    }else{
    Serial.println("sent failed ");
    return false;
    }

 }

The problem is when I print those two variables it just prints lon 26.00 and lat 27.00 but not lon 26.533255 lat 27.533463 as I expected.

Here is the header file for CCPACKET I use:

#ifndef _CCPACKET_H
#define _CCPACKET_H

#include "Arduino.h"

/**
 * Buffer and data lengths
 */
#define CC1101_BUFFER_LEN        64
#define CC1101_DATA_LEN          CC1101_BUFFER_LEN - 3

/**
 * Class: CCPACKET
 *
 * Description:
 * CC1101 data packet class
 */
class CCPACKET
{
  public:
    /**
     * Data length
     */
    byte length;

    /**
     * Data buffer
     */
    byte data[CC1101_DATA_LEN];

    /**
     * CRC OK flag
     */
    boolean crc_ok;

    /**
     * Received Strength Signal Indication
     */
    byte rssi;

    /**
     * Link Quality Index
     */
    byte lqi;
};

#endif

I was trying to fix it by this part of code, but without success:

float lon=26.533543;

*((float *)data.data[0]) = lon;

Can someone help me to convert the byte array to float?

You can choose to treat the byte array as a float array by typecasting. Your attempt isn't far from a solution:

((float *)data.data)[0] = lon; // uses data.data[0] ... data.data[3]
((float *)data.data)[1] = lat; // uses data.data[4] ... data.data[7]

When printing you should also treat the data array as float array:

Serial.println(((float *)data.data)[0]);

It looks like you are sending the data over some interface. Then of course you need to typecast the binary data back into a  float at the receiving end (if you want to do something useful with it) - similar to what is done above when it is passed to Serial.println.


Triggering a soft reset (Arduino Leonardo) I want to trigger a soft reset on my Arduino Leonardo, and after some searching settled on using the watchdog timer, as it seemed to be the easiest and cleanest way to do it.

However, I don't think it works as it should. It seems to work fine on the following example:

#include <avr/wdt.h>

int outputPin = LED_BUILTIN;

void setup() {
  MCUSR = 0;
  wdt_disable();
  pinMode(outputPin, OUTPUT);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(500);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(1000);
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

The LED blinks continuously,.

But for the following example:

#include <avr/wdt.h>

void setup() {
  MCUSR = 0;
  wdt_disable();
  Serial.begin(9600);
  while (!Serial);
  Serial.println("Hello");
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

"Hello" only gets printed once (where I would expect it to arrive continuously).

I tried increasing the watchdog timeout to 2 seconds, but that didn't solve the issue.

So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.


Multiple node network communication over I²C I am working on a project where I want to send data from and to different Arduinos on a network. At the moment I²C seems the best option for my needs since I can specify where to send the data. But using this method I have a bit of an issue I can't seem to find a solution for :(.

I will try to explain my problem using the following image:

In the backend all the nodes are connected like in the first image (above the example network). But the nodes may be connected in a different sequence by a user. See the example network.

In this example network, the node with ID 1 needs to send data to ID 10 and not to any other node on the network. Node ID 12 also needs to send data to node ID 10, but no other nodes. Etc. Etc. Etc. But the node that needs to send data to the next node doesn't know the id of the node it needs to send to.

So at first the nodes need to find out what nodes they are connected to and where they need to send their data.

I thought of doing this by connecting a wire between each node (blue wire in possible solution) and when a node gets added to the network the nodes send a high signal over the blue wire and sends its ID to all nodes on the network and then all nodes on the network check if they receive a high signal and an ID.

If this is true they will send its id to the node that has been added. This works fine if you add a node one by one to the network. But it fails when you replace a node in the middle of the network or disconnect power from the network.

What would be the best way to do this (I am also open to use different data transfer protocols)?

It sounds (after discussion) like what you are after is actually a mesh of multiple peer to peer devices.  That is, lots of devices, each one has multiple dedicated communication links each directly going to another device.

If you had enough UART ports you could create individual UART links between nodes. The bets Arduinos only have a handful of those, and the UNO only one.  So that's not really practical.

You could possibly do it with SPI if you wanted to put a lot of work in to developing a decent control protocol to go along with it.  Something along the lines of BUSRQ/BUSACK signalling:

BUSRQ: Signalling line pulled HIGH by resistor. All nodes INPUT.
BUSACK: Signalling line pulled HIGH by resistor. All nodes OPEN-DRAIN & LOW.
SS: Direct 1:1 GPIO links between nodes - all pulled HIGH. All nodes INPUT.

Node 1                   Node 2                  Node X
RELEASE BUSACK
DRIVE BUSRQ (OD Low)     Sees BUSRQ fall         Sees BUSRQ fall
                         RELEASE BUSACK          (could be busy...)
                                                 RELEASE BUSACK
Sees BUSACK rise
DRIVE BUSACK
SS Node 2 LOW            Sees SS go LOW
Send SPI data            Receives SPI data
SS Node 2 INPUT          Sees SS go HIGH
RELEASE BUSRQ                                    Sees BUSRQ rise
                         Sees BUSRQ rise         Drive BUSACK
                         Drive BUSACK

Only once all nodes have released BUSACK will the requesting node be able to send any data, and once a node has released BUSACK it knows that it must never send any data.  The requesting node has basically locked the bus from other nodes accessing it.

It's not perfect, and doesn't handle multiple devices requesting the bus at the same moment, but it does prevent one device trying to send while another is actively sending.


I am running 1.6.5, but the folder says 1.6.3? I just downloaded the latest version of the Arduino software (1.6.5). However, when I look into the Application Support folder under Library (I have a mac), I find that I have a folder named 1.6.3:

Library ▸ Arduino15 ▸ packages ▸ arduino ▸ hardware ▸ sam ▸ 1.6.3

Does this mean there is a hidden 1.6.5 folder that I am not seeing?

BTW, this issue surfaced, because I am trying to fiddle around with the ADC clock speed, but it seems that nothing is happening:

void setup() {
  #define ADC_FREQ_MAX = 1;
  Serial.begin(9600);
  Serial.println(ADC_FREQ_MAX);
}

void loop() {
}

gives me:

opamp.ino: In function 'void setup()':
opamp:2: error: expected primary-expression before '=' token
opamp.ino:4:18: note: in expansion of macro 'ADC_FREQ_MAX'
opamp:4: error: expected primary-expression before ')' token
opamp:4: error: expected ';' before ')' token
expected primary-expression before '=' token

1.6.5 is the version of the Arduino IDE.

1.6.3 is the version of the Arduino SAM Boards package that you have installed.

  Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via Tools > Board > Boards Manager are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

Tools > Examples > 01.Basics > BareMinimum
Sketch > Show Sketch Folder - this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

  BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.


What happens when I exceed amp limit on Arduino 5v pin? I'm using an Arduino Uno to power some rgb LEDs.

Each LED takes 20mA (on average).
I have a strand of 400 LEDs.
This should be drawing ~8,000mA.

Arduino Uno has a limit on its 5v pin of 500mA.

**So how many amps is my Arduino outputting? My 8A worth of LEDs are illuminated, just dimly.

Edit:
My Arduino still runs, and the 8,000mA LEDs illuminate, just dimly. I’ve left the setup on for 12 hours, and it all still works.

So it appears the behavior of the Arduino Uno is to limit the amp output of its 5v pin. It does not burn out.

Any explanations for this observed behavior?

Edit 2:
I know how to wire up this setup correctly using power injection. I’m just curious why my Arduino is not burning out as we all expect it to.

If you exceed the amp limit, that can be drawn through (!) the Arduino, some components on the Arduino will be fried (As for most electronic devices. For the Arduino this is practically a short). There is no current limitation there. Which components are fried depends on how you provide the power. If you provide power through the power jack or VIN, the voltage regulator will burn out. If you provide power through USB a diode or the MOSFET will be fried (You can look this up in the Arduino UNOs schematic at this site).

The setup might output a current, that is a bit higher than 500mA, for a short time. But the mentioned components, that are in the currents path, will heat up very quickly and be destroyed. In this short time the LEDs will be very dim, since the Arduino cannot provide a current as big as 8A, not even for a short time.

All great loads have to be powered separately from the Arduino, so that their supply current will not flow through the Arduino. If you are using a powerful USB supply, you have to split the power lines, before giving the voltage to the Arduino. You can connect the USBs 5V pin to the 5V pin of the Arduino and to the LEDs. If you are using a power supply with a higher voltage than possible for your LEDs, you have to buy an extra regulator, that also capable of providing the needed current.

Important note: Since you didn't specify, how you are connecting the RGB LEDs, you also have to take care about the current limit of a single pin. It should not exceed 20mA, 40mA at the absolute maximum. So you cannot drive the LEDs directly. You will need a driver for then anyway. The simplest way is a MOSFET, that is capable of sourcing the corresponding current. It is then controlled by the Arduino, which needs very little current for it.


What happens to serial output when no-one is listening? This question probably needs a better title but I'm having trouble thinking of one! Please feel free to edit or suggest one.

My target system is a pair of Arduino Leonardos linked by XBee radios. One is the coordinator and is expected to communicate with a host PC over the USB connection (virtual serial port). The coordinator parses commands and potentially forwards them on to the endpoint by radio. The endpoint replies to commands and can also generate output spontaneously. Both devices can also send diagnostic output to the USB/Serial port. The endpoint sends "heartbeat" messages every 8 seconds. If the coordinator misses 2 consecutive heartbeats then it'll reinitialize. If the endpoint sends a heartbeat and doesn't get a response within a couple of seconds, then it will also reinitialize.

This all seems to work pretty well, but I've noticed something odd. If I connect to both devices with a terminal emulator and just watch the output, everything is good and the system is stable for at least 14 hours (the longest I've tested it). I can see the heartbeat messages happening and the diagnostic output coming out. However, as soon as I disconnect one of the serial ports, things begin to fail. The XBee comms state machine appears to time out at both sides and goes into an endless re-initialization loop.

I'm struggling to think why this might be, but disconnecting one of the serial ports reliably causes the issue within 10 to 20 seconds (I think the "no heartbeat" timeout is being hit).

It seems like if nothing is listening to the serial port, something is getting jammed up. My understanding is that its OK to read from and write to a port that nothing is connected to, and that data will just fall into the bitbucket. Is this not the case? Why should disconnecting the client from the serial port jam everything up?

UPDATE: I've tested with this modified "blink" sketch:

#include <Arduino.h>

auto& host = Serial;

void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  host.begin(115200);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  host.print("Time ");
  host.println(millis());
}

With something (PuTTY) connected to the USB/serial port, I get a nice even mark-space ratio on the LED. As soon as I disconnect PuTTY, the 'off' period of the LED becomes about twice as long as the 'on' period, i.e. there is upwards of a second delay each time I write to the serial port. Is that normal?

Theoretically, nothing should happen to serial data if nothing is listening.

For a traditional UART the data is just sent regardless. It doesn't need someone listening for that to happen.  Like a light doesn't need someone to see it for it to be on.
For USB CDC/ACM the data should be discarded even before it's attempted to be sent.

The latter, though, does rely on the host computer "playing ball" and cleanly closing the port properly.  On most operating systems that is handled by the OS and happens automatically. However on Windows it is handed off to the driver, and I guess the driver may even hand it off to the terminal software.

So in Windows there is a chance that when you disconnect your serial port it's not cleanly closing the connection and the USB thinks it's still connected, thus blocking waiting for the serial data to be collected.


Writing to partially reserved registers of sensors I'm trying to change the range of a gyroscope I'm using and there is the following guideline:

it is recommended to mask out
(logical and with zero) reserved bits of registers which are partially marked as reserved.

I tried reading about bit masking with the bitwise operators and I feel I understand it for trying to read only certain bits, but not for writing.
For example, how would I write to the following register, masking out the 2 bits which are reserved?

You always write a whole byte when you set the register. You only need to "mask out" those bits if there's a danger that you may inadvertently set them to 1, for instance through some value over flow from other bits when combining values together to form that byte.
If you're not doing that then there's nothing to mask out.  For instance if you just want to set a specific set of bits then just set that value - 0b00101001 is going to be 0b00101001 whether you mask it or not.
If you decide you really want to mask a value, for instance if you are writing a library and you have no control over what an end user may decide to pass to a function, then & (or &=) is your friend:
uint8_t val = 0x55; // 0b01010101 in binary
val &= 0b00111111; // or 0x3F if you want to use HEX
// val is now 0x15 since bit 6 has been "masked" to 0.


Servo Keeps Trying to Turn I currently have a servo wired to my Arduino and have imported the Servo.h.  Here is my sketch:

#include <Servo.h>

Servo s1;
Servo s2;

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

  s1.attach(8);
  s2.attach(9);
}
int pos = 0;
void loop()
{
  pos = 0;
  if(s1.read() != pos)
    s1.write(pos);
  if(s2.read() != pos)
    s2.write(pos);

  delay(1000);
}

The problem is that even when my servos are at the position 0 it still tries to turn and I hear it trying.  What do I have to do to tell it to stop turning once it is already at the desired position?

So this is my second bit of code:

s1.write(0);
  delay(5000);
  s1.write(100);
  delay(5000);
  s1.write(180);
  delay(5000);

When I write them to 100/180 (or any number) they are silent after the turn, but when I write them to 0 I hear them keep trying to turn...

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.


Dead reckoning with an accelerometer Is it possible to use an Arduino, connected to a 3 axis accelerometer, to estimate a platform's continuous change in position and orientation? I have a small mobile robot, and given an initial position and velocity vector and sequence of acceleration changes, I'd like to calculate the current position and velocity vector.

From this question, it sounds possible, but I can't find any reference to projects or code to accomplish it with an Arduino. I understand the main problem will be the build-up of errors over time, but that's ok, as a rough estimate is acceptable. I'm also using wheel encoders to calculate the same values, and I want to use the accelerometer to account for errors in the encoders, like slippage. e.g. If the encoders say we're accelerating at 1cm/sec but the accelerometer says we're at a constant speed, then I know to ignore the encoders because the wheels are probably slipping.

I understand the math behind this, so the problem is how to write it in C to run on an Arduino. Is anyone aware of existing open source code for something like this? I'd like to avoid reinventing the wheel in-case anyone's implemented a similar system.

for each accelerometer:
   sample the accelerometer;
   low-pass filter its values (current and recent history) to remove noise;
   multiply by the sample interval to get the velocity increment;
   add the increment to a running sum to get velocity;

   sample the velocity (the running sum you just updated);
   maybe low-pass filter, as above;
   multiply by the sample interval, as above, to get the position increment;
   add the increment to a running sum to get position;
end;

Noise, the artifacts created by filtering, and the double summation all work against your accuracy. That said, if your problem is to sense traction or loss of it, how about sensing real velocity more directly such as by dragging an encoded but otherwise free fifth wheel? Or if circumstances allow, optically sense the velocity of the surface underneath you as an optical mouse does?


How to identify Adafruit Feather 32u4 via mac id/UUID/etc I'm working with a couple Feather 32u4 devices and I've had success so far in setting them up as transmitters and receivers as well as hooking up one of them to a Featherwing Ethernet and talking over MQTT. My problem is that I'm trying to find out how I can implement some sort of identification system among them so that I can send packets to a specific radio. The approach I'd like to avoid is that of writing different versions of the code with different IDs hardcoded in each and uploading them to a radio (so ideally I'm wondering if there's a way to access an inherent mac ID/UUID of each radio). Each radio did come with what appears to be a mac ID printed on a piece of paper but I don't know how to access that directly from the device.

Thanks!

I'm quite sure the reason they print a mac address on a sticker and put it in the package is that they have no way of storing the address in the the feather wing, or at least don't bother to do so if there is a place to store it.

It's up to you to get that address to your Ethernet.begin() call.

FYI, I have been trying to use EEPROM to store the mac address, but the bootloader appears to blow away EEPROM with every reboot.  If I figure that one out I'll update.


Switched from 3ft to 10ft connection wires. My setup doesnt run correctly now. Timing issues? Running a DC motor(6.5A max input), motor driver (MD10C 7Amp peak output), and Arduino Mega. I am stabilizing an object with an accelerometer as my sensor. I switched to longer wires so I can have my board next to me and the stabilized object far away. Now I believe there are timing issues because of this. How would I fix this? How would i test to see how long it takes to travel through my wires?
I can add my code if that helps.

The pins of logic chips and processors are not line drivers and will not operate properly when used as such. Sometimes you may get lucky but that generally would be intermittent in operation. They make drivers to drive wires off board from the controller and other chips that are receivers on the other end. This needs to be done with each digital line. There are some specialty drivers such as I2C repeater chips, RS485 etc. Remember the wires are antennas and the system is operating at a high enough frequency to be a great radio transmitter. The main thing is to isolate the controller wires from the world.


updating firmware on arduino wifi shield I'm trying to upgrade firmware on my wifi shield by following the upgrade instructions for Mac. I was wondering what this means?:

  Connect a jumper on the J3 connector, that put the shield in the programming mode. Then connect the USB cable to the shield USB mini socket

How can I do this?

A "jumper" is a little piece of metal (or a 0-ohm resistor) that connects two pads or pins together. So, create an electrical connection across J3 ("DFU programming jumper" in all the pictures). You will then be able to program the shield via USB.


Arduino SSCANF stop on comma delimiter I have the following problem, the arduino is receiving a command like

LCD,Display line text one, Display line text two

I use an strcmp to match the beginning of the string that works but now I would like to ignore the beginning of the string (LCD) and scan in the next 2 variables until the comma to 2 new variables.

                sscanf(Command, "%[^,]%[^,]%[^,]", &dummy, &lcd_display_l1, &lcd_display_l2);

I don't know if it's possible to ignore the first variable (which would be the LCD) but I setup a dummy variable for it anyway what I not going to use.

All I get with this is the LCD in the dummy the other 2 does not fill up.
I have tried this syntax:

https://support.microsoft.com/en-us/kb/38335

Doesn't work either. Any ideas?

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).


ISP with 115200 baud I have a serial ISP programmer of protocol type "stk500v1" which expects 115200 baud data rate. I have used it successfully with Atmel Studio by calling avrdude manually (custom tool) in the past. This just involves the avrdude option

  -b 115200

But recently I wanted to do use the Arduino software instead of Atmel Studio for a quick mockup. But everytime I try to "Upload with Programmer", the avrdude commandline includes the option

  -b 19200

and so the programming fails.

I can make it work by changing the hard wired serial rate in the programmer from 115200 to 19200, but then of course the programming is dead slow, which I don't want.

I have also looked for a baudrate entry for stk500v1 in "avrdude.conf", but didn't find any. How can I change the baud rate for "Upload with programmer" in the Arduino software?

You have to edit the programmers.txt file. (The one in ~/.arduino15/packages/arduino/hardware/avr/1.6.21/, not the one in arduino-1.8.x/hardware/arduino/avr/)

avrisp.name=AVR ISP
avrisp.communication=serial
avrisp.protocol=stk500v1
avrisp.program.protocol=stk500v1
avrisp.program.speed=115200
avrisp.program.tool=avrdude
avrisp.program.extra_params=-P{serial.port} -b{program.speed}

Add a avrisp.program.speed option, and pass this option as one of the extra_params to the command line call of avrdude.
It is then used on line 112 of platform.txt:

tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} {program.verify} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

You could of course also make a copy of that avrisp entry, and add your own programmer, just give it a different name.


How does this code line detect if a serial interface is connected? I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.

The code is on Github here. Line 111 is the line of interest:

if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P.

So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.

Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:

boolean debug;

const int toggle = 6;

void setup()
{
  if (Serial) debug = 1; else debug = 0;

  pinMode(toggle, OUTPUT);
  digitalWrite(toggle, LOW);

  if (debug)
  {
    Serial.begin(9600);
    Serial.println("Setup");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
  }
}

void loop()
{
  if (debug)
  {
    Serial.println("Loop");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
    delay(1000);
  }
}

You're right -- it doesn't work in most cases, and will almost always return true. The one board where it's actually functional is the Leonardo. According to the official documentation:

  On the Leonardo, if (Serial) indicates wether or not the USB CDC serial connection is open. For all other instances, including if (Serial1) on the Leonardo, this will always returns true.

Basic serial connections (used by most Arduinos) usually don't care if anything is actually listening. It's not uncommon for embedded devices to send debug info by serial even when nothing is receiving it. This has the advantage that the code's timing and behaviour won't change when debugging, which could cause all sorts of problems if you're trying to diagnose a problem reported in the field.


ADC register always returning high Regardless of whatever voltage at A0, the software is always returning high (1023)

volatile unsigned char* ADmux = (unsigned char*) 0x7C;
volatile unsigned char* ADCSRa = (unsigned char*) 0x7A;
volatile unsigned char* ADCSRb = (unsigned char*) 0x7B;
volatile unsigned char* ADCh = (unsigned char*) 0x79;
volatile unsigned char* ADCl = (unsigned char*) 0x78;
int Voltage;

void adc_init()
{
  *ADmux = 0x00; // setting entire register to 0's notably setting Refs1 and refs0 to 0's meaning reference voltage is AREF
  *ADCSRa = 0b10000111; //Sets most significant bit to 1, which is the ADC enable bit, and the 3 least signifcant bits are the prescalar, which is 128

}

unsigned int adc_read( unsigned char adc_channel)
{
  *ADmux = *ADmux | 0b00000000;// set mux bits to 0 to test A0 regardless of whatever adc_channel is
  *ADCSRa = *ADCSRa | 0b01000000; // set ADSC bit high to start conversion

  while(*ADCSRa & 0b01000000);//wait until ADSC goes low, indicated conversion is complete

  return ADC; //return bits in the adc registers
}

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

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

  Voltage = adc_read(0b00000); // calls on adc_read

  Serial.print(Voltage); // prints voltage reading
  Serial.write("\n");

}

And here is a schematic of the circuit:

simulate this circuit – Schematic created using CircuitLab

I have combed over chapter 26 of the atmega2560 document and the descriptions of each register, but I am at a loss. Why is the contents of the adc registers always filled with 1's regardless of the voltage at a0?

First, let me give a couple of suggestions on the programming style.
There is no point in defining your own variables for accessing the
hardware registers: the avr-libc does that for you, you just have to
#include <avr/io.h>. Actually, you don't have to #include anything:
the Arduino IDE automatically #includes Arduino.h, which in turn
#includes avr/io.h.

Next, the same avr-libc also defines macros for the bit names, so you
don't have to explicitly write binary numbers in your own code (which is
error-prone). And a couple of utility macros that you can use to make
the code a little bit more readable. For example:

void adc_init()
{
    ADMUX  = _BV(REFS0);  // ADC reference = AVCC
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADPS2)   // set prescaler to 128
           | _BV(ADPS1)   // ditto
           | _BV(ADPS0);  // ditto
}

unsigned int adc_read(unsigned char adc_channel)
{
    ADMUX   = _BV(REFS0) | (adc_channel & 7);  // select channel
    ADCSRA |= _BV(ADSC);  // start conversion

    // Conversion is complete when ADSC goes low.
    loop_until_bit_is_clear(ADCSRA, ADSC);

    return ADC;  // return the adc data register
}

Now, let's answer your actual question. When you set both REFS0 and
REFS1 to 0, the voltage reference is stated to be “AREF, internal V
REF turned off”. The implication is that you are supposed to bring your
own voltage reference and connect it to the AREF pin. Otherwise AREF is
left as a floating input. This is illustrated in the schematic of the
ADC. Here is the relevant part:

As you see here, REFS0 is used to connect AREF to one of the other
possible references: either AVCC or the internal bandgap. If REFS0 is
zero, the transistor depicted above is off, and AREF is left floating.


New to Arduino building I am new to Arduino an working with the Uno.  My dream is to activate servos in a perticular order once some type of sensor recognizes a live person near it.  Is their a perticular easy to understand book out there I can read?  There are lots and lots of books but they all get very complex rather quickly.  I'd be curious as to fellow inventors in here telling me how they mastered the Arduino?  Maybe it was not a book but rather a complete course.  Will others please respond to help me.  ps... I do have an electronics degree so I don't need soldering or component understanding.  I know what Vcc is.  I need please some type of course book which will take me now beyond the self blinking light into robotic control if that easy to understand book or course is out there.
Thank you.  Michael in Palm Beach, FL

There are lots of examples on the official Arduino website.

My advice is you follow them, not only by reading, but buy the components you need (they are cheap) and practice and see how to handle them within the Arduino environment.

Do one component at a time (led, switch, Servo, Sensor), and focus on the servo/sensors you want to use.

Than try to combine multiple components, step by step until you have your dream project ready.

Also, try not to just copy sketches (programs), but understand them. And than adapt them a bit, make variations on the component 'tests'.

I have a whole folder where I test each component with Arduino (and for some complicated components multiple sketches). Save them, and add links etc, so you can easily reference back to it.

You can use books, but there is so much information for the Arduino that this forum, the official web site and google should be enough to get you going.

(note: for the Arduino I did not use books, since as above said, there is so much information. I'm now diving in to STM32 which is more complex and a book/PDF is more convenient).


Programming Leonardo with TTL to USB cable I have wired my Arduino as seen in the picture, with the RX of the cable plugged into the TX (D1) of the Leonardo and the TX of the cable plugged into the RX(D0) of the Leonardo. I then have the ground plugged into GND and the power into 5V. The driver is installed correctly and the IDE recognizes the port, however, whenever I try and upload any sketch, I get the error:

Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

I can upload sketches fine via usb, is it just unable to do so via a USB to TTL cable?

Thanks in advance

The bootloader on the Leonardo operates through the native USB port of the ATMega32U2 chip, not the UART.

You cannot treat it like an Uno because it isn't an Uno.

You can only program it through the USB port or through the ICSP connector.

If you want to use UART to upload you will need to replace the bootloader with a suitable UART based alternative. (Before you ask, no I don't know if one even exists or where to get it if it does).


Can i supply the AREF pin with an Analog pin from the same board? I guess its a dumb question but couldnt find anything about it online. I know its possible to supply the AREF pin with 3.3 V to increase the ADC resolution.

For the project i am working on the analog voltage i will be reading will be between 0 and 2.2 and the increased resolution is a must.

I know i can use another board that has a 12 bit resolution but i really would like to make do with Uno. So i wonder if i can set an analog pin to output 2.3 V and feed it to the Aref pin.

If thats not possible please let me know why, so i can increase my knowledge

With an input voltage between 0 and 2.2 V, you can use a 2:1 voltage divider to cut the voltage in half.  In your code, use analogReference(INTERNAL) to set the analog reference voltage to 1.1 V.  The 1.1 V internal reference voltage is created by a bandgap circuit so is reasonably accurate.

To make the voltage divider, put two equal resistors (eg 10KΩ each) in series; connect one end of the series to your input voltage, the other end to ground, and the mid-point to an analog input pin.


how to read all line except the first line? is there a way to read only 2nd up to the last line except for the first line?

here's my sample code

File myFile;
char cr;
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());

    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

Why don't you do reads for the first line, ignore them and start the while thus:

while (myFile.available() && (myFile.read() != '\n') {}; // Empty while body
while (myFile.available()) {
  Serial.write(myFile.read());
}