How to access multiple SPI interfaces on Arduino I have worked on SPI devices connected with an Arduino one at a time. How do I work with two different SPI devices at the same time?

Assuming you just want to connect two SPI slave devices to the SPI bus and use them in a mutually exclusive way under software control, with the Arduino as the master, then you just need to make sure you use a different pin for the slave select (SS) on each SPI device.

When you want to talk to one slave, you hold its SS low and drive the other high. Do the opposite to talk to the other slave.

There are some devils in the detail using multiple slaves, and these are explained in more depth here, but in general, it's quite common and OK to use more than one SPI device as a slave.

This blog post will give you more information and is a good place to start reading.


Sequencing air pistons proble - Help please? I am a beginner trying to activate 2 sets of 3 air pistons sequentially by going through the YouTube Tutorials... Help, please, pretty please?? :-)
There are 3 sets of 2 pistons, each set working in opposition.
So I have P1/P2, P3/P4, and P5/P6, each set working in opposition to squeeze at the center sequentially -
Initial state at turn-on/Reset must be:
// Step 1 Run Once:
P1 Down/P2 Up  // Move simultaneously (joining at the center) and HOLD in position -
P2 Up/P3 Down  // Move simultaneously and HOLD -
P5 Up/P6 Down  // Move simultaneously and HOLD -
// Wait for Start button -

I need to start/stop the sequencing with a toggle push-button -
I have reed-switch sensors that will give me a set of two TRANSIENT contact closure for each piston moving to the Up and Down positions -
Once started, the sequence needs to be as follows:
// Loop until Reset button is pushed -
// STEP 2: -
P1 Down/P2 Up (HOLD) // Old Initial State, unchanged -
P3 Down/P4 Up (MOVE) // Piston 3 moves Down/Piston 4 moves Up and HOLDS -
P5 Up/P6 Down (HOLD) // Still Old Initial State, unchanged -

// PROBLEM:  P3 Down AND P4 Sensors only give me a TRANSIENT closure:  These two transients MUST occur to initiate Step 3, but  they are not always exactly synched together, so my initial try by putting them in series fails... -
// I need to use that set of contact closures to trigger the next command: -
// Step 3: -
// The transient closures of P3 Down/P4 Up Sensors is the trigger needed for -
P5 Down/P6 Up (MOVE) // P5 moves Down/P6 moves Up and HOLD -
P1 Up/P2 Down (MOVE) // P1 moves Up/P2 moves Down and HOLD -
P3 Down/P4 Up (HOLD)  // P3/P4 HOLD -

// Back to Step 2 until the Reset button is pushed -

I can send you my attempt at coding for this, but it does not work unless the two sensors close simultaneously, which only happens in simulation...  ARGH..  :-(
Can someone send me a piece of code that will work for this, please?
I would really, really appreciate that...  Very frustrated right now!
You can email me at XXXXXXX.XXXX@XXXXX.XXX or text/call at (XXX)XXX-XXXX
Thanks either way.
Sincerely,
Michael
PS:  I tried to wire for a separate toggle switching for each sensor, but I run out of pins on my Arduino UNO R3... Looking into it via YouTube https://www.youtube.com/watch?v=cAT07gy4DII "Increase the digital outputs on an Arduino (PART 1 & 2)" but that is way more complex...  Trying to wade my way through that now...

it does not work unless the two sensors close simultaneously

If I understand correctly, the problem is that when your Arduino detects
the second transient signal, the first one is not active anymore, and
your program doesn't remember it has already seen that first signal.
Your Arduino has memory. Thousands of bits of memory! So it can remember
quite a few things. The solution to your problem is to simply make use
of that memory. When you detect a signal that should be useful for a
future decision, take note, store it in a variable. In order for the
variable to be remembered across calls of the function where you set it,
it has to be global. Or, better yet, static local.
Here is how that could look like in code:
// A `static' variable is a variable that remembers its state across
// calls of the function. A global variable would do the same, but
// code is usually clearer when variables are defined close to where
// they are used. A `bool' (for "boolean") is a variable that can only
// be either `true' or `false'.
static bool P5_is_up, P6_is_down;

// If the sensor tells us that the P5 piston went all the way up, take
// note of the fact and remember it.
if (digitalRead(P5_up_sensor) == LOW)
    P5_is_up = true;

// Same for P6 going down.
if (digitalRead(P6_down_sensor) == LOW)
    P6_is_down = true;

// If both pistons finished their travel, we can move to the next
// step. `&&' means "and".
if (P5_is_up && P6_is_down)
    goto_step_3();

You will need to reset those variables to false at the appropriate
time. The example code above doesn't show that as it only deals with the
logic for deciding when it is time to start step 3.
You will probably end up with many of these variables, and lots of
repetitive code. So you will need to structure your program in order to
avoid excessive repetition. But that is not your immediate problem. For
now, try to make the logic work for a single step transition. Once you
get the logic right, you can worry about generalizing the logic to any
transition.


4-20 milliamp to volts to pressure maths I am measuring pressure in bars from OsiSense™ XMLP pressure sensor (4-20 milliamp) on a arduino uno.  When the machine im measuring pressure on is switched off the reading is 0v as expected.
When the machine is on (the sensor is on) the reading is 1v as expected.
When the machine is on and hydraulics are active the voltage fluctuates as expected.

The problem I have is I don't know the maths to translate the voltage to bar pressure.

From a previus question i've asked from 0v to 5v the equation is:

// This is for the DEFAULT 5V analog reference.
// v = the voltage at the pin in Volts.
// p = the pressure in bar.
// Note that 'bar' is the pressure relative to the
// normal atmospheric pressure at that moment.
float v = (float) analogRead(A0) / 1024.0 * 5.0;
float p = v / 5.0 * 100.0;"

Is it just a matter of changing the equation to take into account the 1v when the sensor has power and then dividing by 4 instead of 5:

RawVoltage = (float) analogRead(A0) - 1;
float v = RawVoltage / 1024.0 * 4.0;
float p = v / 5.0 * 100.0;"

If I understand your question correctly, when the sensor is on,

4 mA (1 V on the Arduino) means 0 bar
20 mA (5 V on the Arduino) means 100 bar.

Is that correct?

If that is correct, there you just have to linearly map the voltage
range to the pressure range. The equation is

P = (v − 1 V) / 4 V × 100 bar

or, in C++:

float v = analogRead(A0) / 1024.0 * 5.0;  // in volts
float p = (v - 1) / 4 * 100;              // in bars


Need help with converting Celsius to Fahrenheit in the code I'm new to Arduino and trying to figure out how to convert Celsius to Fahrenheit with the parameters listed below. Do I need to create a separate file for the calculations? If so, can someone help me on how I can go about doing that?

#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  TEMPERATURE = dht.readTemperature();
  HUMIDITY = dht.readHumidity();
  Serial.print("Temp: ");
  Serial.print(TEMPERATURE);
  Serial.println(" celsius ");
  Serial.println(" ");
  Serial.print("Humidity: ");
  Serial.println(HUMIDITY);
  delay(2000);

  //Built In LED
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(250); // wait for a second
  digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
  delay(250);
}

If you are using the Adafruit DHT sensor library, then you can get a
Fahrenheit reading by passing true as an argument to
readTemperature(). C.f. the comment in the source code. For
example:

Serial.print("Temp: ");
Serial.print(dht.readTemperature(true));  // true -> Fahrenheit
Serial.println(" deg. F");

Note that this library offers also the conversion functions
convertCtoF() and convertFtoC().


How to create objects with their own variables? So i created a class and when i created objects and use them, they seem to share their variables between each other ( the currentReading, previousReading and the time variable). how can i create objects that have their own variables so that type of conflict cant happen?

code : ( read the buttons and print them in the lcd screen)

#include <LiquidCrystal.h>

LiquidCrystal lcd(6, 5, 3, 2, 1, 0);

class button {
  public:
    void SetupButton(int pino);
    int Read();

  private:
    int _pin;
};

void button::SetupButton(int pin) {
  pinMode(pin, INPUT_PULLUP);
  _pin = pin;

}

int button::Read() {
  static boolean currentReading, previousReading = 1;
  static unsigned long time;

  currentReading = digitalRead(_pin);// reading
  if (previousReading - currentReading  == 1) { // when reading gos from 1 to 0
    time = millis();
  }

  if (currentReading - previousReading == 1 && (50 < (millis() - time) < 500)) {     // when reading gos back to 1 before 500ms
    previousReading = currentReading;
    return 1;
  }

  if (3000 > (millis() - time) && (millis() - time) > 500 && !currentReading) { // when reading keeps in 0 after 500ms
    previousReading = currentReading;
    return 2;
  }

  if ((millis() - time) > 3000 && !currentReading) { // // when reading keeps in 0 after 3000ms
    previousReading = currentReading;
    return  3;
  }

  previousReading = currentReading; // current reading becomes the previous

  return 0;
}

button up;
button down;

void setup() {
  lcd.begin(16, 2);
  up.SetupButton(A0);
  down.SetupButton(A1);

}
void loop() {

  lcd.setCursor(0, 0);
  lcd.print(up.Read());
  lcd.print(down.Read());

}

ps :  i already know how to do this without using classes but doing it with classes makes the code much cleaner so i am trying to achieve this

I was tempted to re-write your code (I am quite rusty on c++), but you may be better to start with an existing class.

There is a Button class on the Arduino site. See https://playground.arduino.cc/Code/Button

You could use this or study to see a more usual c++ implementation and adapt your code.

Virtually ALL c++ classes include a constructor. I would use instead of SetupButton

void button::button(int pin) {
  this->_pin=pin;
  pinMode(pin, INPUT_PULLUP);
}

and add uint8_t previousReading; and unsigned long time; to your class as private variables.


Using Serial.write() to send a uint32_t send one byte x4 or send 4 bytes x1 In the IRremote library, IR signals are decoded and held in results.value.  My project uses the NEC protocol which is 32 bits, so the IR code will always be 4 bytes.

uint32_t dCodedIR;
//
//  code exists here that we can ignore
//
dCodedIR = results.value

This decoded signal is then sent out the serial port to a second MCU which will be waiting for incoming data:

while (!Serial.available())  {
}

After this, there will ideally be a complete code of 4 bytes waiting in the FIFO. I will allow for times when < 4 bytes are ready (check for more, timed out? NO:loop   YES:reset), but this should rarely happen. So I want to optimize the sending code so that the receiver has the best chance of avoiding split groups. In theory, is it better to write as single bytes and repeat 4 times, or make a 4-byte array to send once?

Serial.write(dCodedIR & 255);
Serial.write((dCodedIR >> 8) & 255);
Serial.write((dCodedIR >> 16) & 255);
Serial.write((dCodedIR >> 24) & 255);

or

byte sendBuf[4];
//
//
sendBuf[3] = (byte) dCodedIR & 255;
sendBuf[2] = (byte) (dCodedIR >> 8) & 255;
sendBuf[1] = (byte) (dCodedIR >> 16) & 255;
sendBuf[0] = (byte) (dCodedIR >> 24) & 255;
Serial.write(sendBuf, 4);

(Since there will be plenty of storage space for the code, with performance being the priority, I decided against using for loops because updating an index, testing it, and looping would seem to add overhead.)

Unless you are using very high baud rates, (at least higher than
115.2 kb/s), it should make no difference.

The reason is that either version of your code should run faster than
the UART. Serial.write() doesn't wait for the bytes to be sent out the
wire. Instead, it just stores those bytes in a ring buffer that belongs
to the HardwareSerial library. When the UART is ready to accept an
outbound byte, it triggers an interrupt. The corresponding ISR takes one
byte from the ring buffer and handles it to the UART. Since the UART
itself is double-buffered, all this happens while the previous byte is
being sent.

The end result is that, with either version of your code, you end up
with a continuous byte stream. The start bit of the second byte comes
right after the stop bit of the first byte, and so on. The stream
doesn't pause until the full message is sent. That is, unless you have
somewhere in your program overly long critical sections that can impose
excessive latency to the whole process.

Side note: if your MCU is little endian (most Arduinos are), you
could also avoid one copy and just do

Serial.write((byte *) &dCodedIR, 4);

Addendum: The details may depend on the MCU you are using. On an
Uno, or similar AVR-based boards, the UART has no knowledge of the
software ring buffer. It rises the UDRE0 (data register empty) flag
whenever it is ready to accept an outbound byte in its sender data
register. When there is data in the buffer, the software enables the
data register empty interrupt, which is tied to the UDRE0 flag.


Waking up async the Arduino while it is sleeping periodically I´m using LowPower.h and PinChangeInt.h libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF) but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

Can anyone help me? Thanks

My aim was to attach multiple interrupts to my Arduino but my problem was that I didn´t know if when the board changed to sleep mode using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) then it could be awake using another interrupt instead of the timer.

The void loop() method must sleep the board every 8 seconds if no button is pressed. Aside there is a method that is called when a button is pressed, that´s because in the void setup () I´ve attached an interrupt using PCintPort::attachInterrupt(PIN_NUMBER, METHOD_TO_CALL,MODE);

OP (PinaGamer) posted this answer inside the question, hence the community wiki answer.


How do I isolate numbers in text? I need to separate numbers from the text where my string of numbers will always be of length 8:

string text = "77953505HELLO THIS IS A MESSAGE"; //my string of numbers will always be of length 8

My result

string number = "77953505"; //my string of numbers will always be of length 8
string message = "HELLO THIS IS A MESSAGE";

What operation should I use?

this is the job I'm doing

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

void loop() {
  if (Serial.available() > 0) {

    String Texto = String(Serial.read());

    String number = Texto.substring(0, 7);
    String message = Texto.substring(8);

    Serial.write(number);
    Serial.write(message);
  }
}

help me!

Depends, and probably better to use C strings:

If you know the number is always the same amount of characters, use the C function strncpy.
You can also split on a delimiter (char), with strtok, but in your case this is not possible since you don't know the delimiter character.
If the number has a variable length, start copying character by character through the string, until you find a character that gives false for the isdigit condition and copy the remainder (with strncpy) to the other string.

Update after the question's edit

Since the number of text to be copied is know, strncpy can be used with the following prototype:

char *strncpy(char *dest, const char *src, size_t n)

In your case put the text in a normal text string:

char text[80]; /* Assuming max length of text */

Copy it where needed:

strcpy(text, "77953505HELLO THIS IS A MESSAGE");

Note: it can be done in once like this:

char text[] = "77953505HELLO THIS IS A MESSAGE";

Than you can copy the items by:

char number[9]; // Add 1 for \0
char message[81]; // Assuming max length of message;

strncpy(number, text, 8);
strncpy(message, &(text[8]), strlen(text) - 8);

(Note not checked with compiler).

Improvements: use instead of 8 a define e.g.

#define NUMBER_LENGTH 8

char number[NUMBER_LENGTH + 1];

strncpy(number, text, NUMBER_LENGTH);
strncpy(message, &(text[8]), strlen(text) - NUMBER_LENGTH);

You can do similar for MESSAGE LENGTH

#define MESSAGE_LENGTH 80

Also, another improvement is not to copy the message, but just set the pointer to the correct place:

char* message = &(text[8]);

message will point to "HELLO THIS IS A MESSAGE"

like below

"77953505HELLO THIS IS A MESSAGE"
|        |
+-- text |
         +-- message

In an Arduino 80 bytes can be a lot of memory, using two buffers cost 160 bytes, and this way you save at least one buffer.


Zigbee Relay board communication with Arduino I have bought this wireless ZigBee relay board.

I was wandering about an arduino sketch to get started, I have searched for 2 days now but with no results.

What I was thinking of is to have an Arduino with ZigBee module to send signal to another ZigBee device on top of the relay, to be able to open/close relay.

So, can anyone share a sample sketch for that board?

Take a look at this library : https://code.google.com/p/xbee-arduino/

This is the XBee Library for Arduino, you will find simple sketch that are perfect bases for the application you're trying to do.


Problem assign float to an embed class within the Linked-list libary I have successfully implemented some code which uses a linked-list.  Everything is working, except assigning a value to a float within the embeded class.  When I run the code below, I get the expected behavior, a flashing LED for 10 secs then LED turns continuously ON, and I also get the debug messages I expect.  However, when I comment the marked line to assign a value to the float, it still compiles, but the LED does not flash as expected and I get complete rubbish from debug.  I am using codebender on Chrome, and I have tried Firefox (both given same results).

Main Sketch https://codebender.cc/sketch:175995

Example of library working https://codebender.cc/sketch:176008

Can anyone help?

typedef void(*GF)(void);

#include "LinkedList.h"

class CsC {
    public:
        float PerS;
        GF FunctionToCall;
};

LinkedList<CsC*> TaskList = LinkedList<CsC*>();

void LEDON()
{
    digitalWrite(13,HIGH);
}
void after(float interval, String intervalDescription, GF func);

void after(float interval, String intervalDescription, GF func)
{
    float multi = 1;
    if(intervalDescription == "mins") multi *= 60;
    float delayMS = multi * interval;
    CsC *c;
    //Error if either of these lines uncommented
    //c->PerS=10000;
    //c->PerS=delayMS;
    c->FunctionToCall=func;
    TaskList.add(c);
    Serial.print(".");
}

void setup()
{
    Serial.begin(9600);
    pinMode(13, OUTPUT);
    Serial.println("Start write task list");

    after(35,"secs",LEDON);

    Serial.println("Done");
    Serial.println("Start prog");
}
void loop()
{
    Serial.print("List=");
    Serial.print(TaskList.size());
    while(TaskList.size()>0){
        CsC *c=TaskList.shift();
        long timeout=millis()+10000;
        //long timeout=millis()+((long)(c->PerS*1000.0));
        while(millis()<timeout){
            //To indicate it is running, and to save time, I have used a delay here
            digitalWrite(13,HIGH);
            delay(250);
            digitalWrite(13,LOW);
            delay(250);
        }
        c->FunctionToCall();
    }
    Serial.print(".");
    Serial.println("complete");
    while(1){}
}

One possible error is a memory leak as you did not allocate the memory to the class
Try

CsC *c=new CsC();


When using an Arduino as an ISP, is the capacitor required or not? Looking at Arduino as ISP and Arduino Bootloaders, it is stated

  The 10 µF electrolytic capacitor connected to RESET and
  GND of the programming board is needed only for the boards that have
  an interface between the microcontroller and the computer's USB, like
  Mega, Uno, Mini, Nano. Boards like Leonardo, Esplora and Micro, with
  the USB directly managed by the microcontroller, don't need the
  capacitor.

Some of the Fritzing diagrams show the electrolytic capacitor connected between the RESET and GND pins:

But it is not shown in all of the images on that page.

Nor it is shown in this image from Nick Gammon's Atmega bootloader programmer (see original image):

So, is the capacitor really needed, when using a Mega or Uno as an ISP, and if so, why exactly?

I was wondering after having written this answer to the question How to install new ATMEGA firmware via the ISP pins? for a 3D Printer control board.

The purpose of the capacitor is to prevent the "master" Arduino (the Mega in the first image above) from resetting when the serial port is opened.  If that board resets, then programming fails.
There are many ways of preventing that reset - some more permanent than others - but the capacitor trick is one of the simplest.
So yes, you do need the capacitor unless you have made other modifications to prevent the reset.
I think the purpose of the second image is more to illustrate how to use the ICSP headers and where to connect the target's reset pin on the master. It is to be seen as complementary to the first image.

Edit:
It seems what you are using is not Arduino As ISP, but instead something written by Nick Gammon that acts as a standalone programmer.  The rules for Arduino As ISP do not apply in this case. Since you are not programming via the master Arduino (as you would with Arduino As ISP) there is no need to prevent the master from resetting.

Here's a little history about the auto-reset system:
Originally, when the Arduino used the FT232, the DRT signal would reliably reset it automatically. The operating system (all operating systems) would automatically assert DTR when the port was opened, and all was well.
Then, out of the blue, and without telling anyone, Future Tech removed that auto-DTR asserting from the FT232 driver for Windows. Since Windows doesn't control DTR for you, but leaves it up to the driver or the software (and all other operating systems automatically control DTR for you - Windows has to do the opposite of everyone else - it's in their remit...!) all of a sudden the boards stopped resetting properly for programming.
So Arduino added specific reset code into the IDE to get around the problem (interestingly enough: if you watch the DTR pin on Linux you see it being asserted multiple times when programming - both the OS and the IDE are toggling it).
But then Arduino moved to the ATmega8U2 (and later the ATmega16U2) chip which uses the standard CDC/ACM instead of the custom FT232 driver. Now the auto DTR assertion was working again, but they kept the manual assertion in the IDE to cope with older boards in Windows.
I guess they didn't put the DTR assertion workaround in the bootloader programming code since you don't really want DTR asserted at that point anyway.
So if you have an FT232-based Arduino and are running Windows I guess there is no need for the capacitor, since DTR won't be asserted by the OS.
However in Linux and OS X, regardless of the USB chip, you will need the capacitor, since it will always assert DTR.
But then along came China and threw the CH340G into the works.  Now we have a third option, with dodgy drivers from who knows where. And who has the slightest clue what they do? Do they assert DTR for you? Your guess is as good as mine.  If it doesn't, then you won't need the capacitor. If it does, then you will.
It's all such a mess now thanks to too many options and combinations.  It's simpler just to have the capacitor regardless, since it won't stop it working if it's not actually needed in your specific configuration.


NodeMCU minimum supply voltage) I have read several articles an datasheets, but I couldn't find an affordable answer...

This is my problem: I need to power a NodeMCU (on Vin pin) with 3xAA batteries. Which is the minimum operating voltage at Vin accepted by NodeMCU? In other words, which voltage drop from 4.5 will let NodeMCU still working?
thanks.

The NodeMCU uses the SPX3819 3.3v voltage regulator.

That regulator, according to the datasheet has a dropout of maximum 700mV, but much less at lower currents.

Taking the maximum, that means that you need to supply 3.3 + 0.7 = 4V to the board for the regulator to regulate properly. However, it is doubtful you will be using that much current, so probably nearer a 350mA dropout - which means 3.3 + 0.35 = 3.65V.

However, the ESP8266 itself will work down to 2.5V - so if you operate the board with the regulator out of regulation (not recommended, but it should work fine), you could probably go as low as 2.8 to 3V without problems.


Does the Node MCU v3 (LoLin) not have a builtin led? Trying a simple led blinking program I could not get the builtin led on a LoLin Node MCU v3 working. The LED_BUILTIN constant is set to pin 16 / GPIO16 / D0.

Reading several articles and QA I think that the Node MCU boards are supposed to have a the on-board led on pin 16. However, if I address this port nothing happens.

With the same code I can blink the data led which is on a RX pin, pin 2.

Is the builtin led missing on the LoLin Node MCU v3, or could it be that the led on my board is broken?

the ESP8266 has a builtin led that is attached to D4 as labeled on LoLin boards which maps to GPIO2. One thing to Note is that the led is active low. In other words ... setting PIN 2 to '0' will turn the LED ON and setting PIN 2 to '1' will turn the LED OFF

Lolin Builtin_Led Picture

This is the only LED on the LoLin boards and differs from other devkits that have an LED on GPIO16.


Improvement security in a domotic project I recently started with a domotic project, I began creating a lock opening with a RFID
currently I'm trying improving the code (I took from http://forum.arduino.cc/index.php?topic=256260)

but I have some question about the security of this system (or any in the domotic way).

First, I know any system is 100% secure. starting from there, I was thinking, what happens if someone known that the system is built in the arduino platform and has some knowlege about it, that person can create a sketch, upload to the board and make "opening" all the pings?, they will have access to that room or thing I'm protecting (or trying). This is just a excercise, I don't want to go in depth about the external security that the board/system must have.

So, searching topics about it, I didn't find anything to help in the solution of this theoretical problem. I read some articles about the bootloader and I think, the solution can be there, I know Arduino is a openSource solution, but I think it doesn't mean insecure, so I think some kind of system who check a key before to load a sketch can help. It can have a default key, who can be used to the developing process, and other key (any) who must be verified, in the current sketch.

I'll try to explain it a little better:

Developing Mode
Bootloader [No Key] -----> can upload any sketch

Production Mode
Bootloader[check mode] -----> [Sketch with the secure key]
[Upload New sketch] -----> Bootloader[check the key in the new sketch with the key in the current sketch] (allow or block access, according as appropriate)

I don't have deep knowledge in criptography or bootloading, so I don't know if it's corret solution. I saw there are some way to "download" the code of the board (in a bin), I don't know if with this way the key will be exposed.

can someone tell me if this basic security would be helpful?
if it's, can be possible to implement? how?
Will the key be exposed in the bin (in case of download)?

First of all, a quick rule that you should follow... It is called Kerckhoffs's principle. Wikipedia states it as this:

  A cryptosystem should be secure even if everything about the system, except the key, is public knowledge.

So, you're never going to reach "full security."

If the attacker can physically access your Arduino, all bets are off. They can upload new code, replace the Arduino, or just simply rewire your circuit so the door opens.

Also, they may be able to remove the RFID module and replace it with another Arduino board that sends random data in the right format hundreds or thousands of times a second. If they find the key code, they can make a new RFID tag with that ID. Thus, it is essential to keep that ID private.

So here's what you should do (in this scenario, password = RFID key's ID):

Make sure they can touch or access as little as possible. If you can, embed the RFID receiver inside a wall so they don't know where the receiver is and would have to break the wall to access it. If they break the wall, they could break the door, so this isn't necessarily a major security flaw. Of course, remember the sensitivity of your receiver.
Obfuscate your code: If you do something where you combine only certain bits/bytes of a few different strings to get a passcode to be compared to the sensor value. Of course, the compiler will remove most of this in an attempt to optimize your code. Note that this isn't actual security, just making the intruder having to do more work. A lot of people discourage this since it gives you a false sense of security, but I encourage it because it will take a little bit longer to hack into your application if they get your code. Remember that at any time they can use Serial.println(finalPasswordHere);.
If you're really worried, hash it. AVR chips probably don't have enough power to do advanced hashes like SHA-512. There seems to be a few MD5 hash algorithms for Arduino. MD5 isn't really secure with only a few digits, but if you have a 30 character hash that would take a long time to brute-force it. Add a salt with a ton of random characters (ex: lsjJK399!$%^&flk2) that aren't normally found in lookup tables. You'd combine the salt and the ID for the tag into one hash and put that in the code. Then, you'd hard code that hash into the main code. When you want to check if the ID being scanned is correct, you'd hash it with the salt and then compare that to the known hash. If you have more than one ID in the system, it's a good idea to have a different salt for each.


How to restart void loop if condition is met This should be a quick question.

I'm trying to figure out how I can restart void loop() if a certain condition is met. In this instance, if (s>10), I want the loop to restart. Any help will be appreciated.

 void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    while (getDistance(0) == true && getDistance(1) == false);
    unsigned long currentMillis = millis(); //time when the passed the first sensor

    while (getDistance(1) == true && getDistance(0) == true); //wating car to pass the second sensor

    unsigned long endMillis = millis(); //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0; //because 1000ms = 1s

    float s = sensorDistance / timeSeconds; //speed = distance / time

    if(s>=7 && s<=10) // for red to turn on
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[2] = {'h','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 2); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low

    }
    else if (s<7)
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[4] = {'h','e','l','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 4); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low
    }

    delay(2000);
  }
}

When programming with arduino IDE, you declare 2 functions, setup() and loop().

Before compilation, arduino IDE basically expands to :

int main(void)
{
    /* run the Arduino setup */
    setup();
    /* and the event loop */
    while (1) {
        loop();
    }
    /* never reached */
    return 0;
}

So, from here you can see that setup() is called once at startup and then, loop() is called in an infinite loop.
Il you return from within your loop function, it will be called again.


I can't receive string that I have sent through nrf correctly I'm using arduino uno and nrf24l01. to monitor sensor data.
But this is the message that master receives:

  ⸮

this is my slave code.

void monitoring() {
    delay(10);
    radio.stopListening();
    int soilMoisture = analogRead(A5);
    int light = analogRead(A4);
    float temp = analogRead(A3);
    temp = temp * 0.48828125;
    int ltemp = int(temp);
    String message = String(soilMoisture) + "," + String(light) + "," +    String(ltemp);
    Serial.println(message);
    delay(200);
    radio.write(&message, sizeof(message));
    delay(50);
    radio.startListening();
    delay(10);
}

and here is my master code.

while (1) {
    if (radio.available()) {
      char message[32] = "";
      radio.read(&message, sizeof(message));
      delay(500);
      Serial.println(message);
}

Remove the & in the master code line, change

 radio.read(message, sizeof(message));

to

radio.read(message, sizeof(message));

message is an array, so either you should pass the address of the first character (&message[0]), or simply pass message.

Another problem is sending a String in the slave code (using type String). It's better not to use this type anyway, but you probably have to convert it to a character array of the same type as in the master code.

You can use the function StringToCharArray for that, see StringToCharArray.


Arduino Leonardo bugs and lack of removable microcontroller Following one of the article from 2013 :

  Before you start hammering that “add to shopping cart” button, note
  that the general impression around the web seems to be that the
  Leonardo still has a few bugs that need ironing out, and isn’t quite
  as beginner friendly as the Uno. For builders already familiar with
  Arduino, this is the better deal.

The question is if Leonardo is still buggy and may cause any confusion to newbie Arduino programmers. Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

The question is if Leonardo is still buggy

Probably.

  and may cause any confusion to newbie Arduino programmers.

Definitely.  The whole way the Leonardo works is very different to the likes of the Uno. Transitioning from one to the other, if you don't know what the differences really mean, can be confusing.

  Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

You build your circuit on a PCB and you provide an ICSP header.  ICSP stands for In Circuit Serial Programming.  You then use a hardware programmer to install either the Leonardo bootloader, which can then be used to install sketches through USB, or install a sketch direct without the bootloader.

Or, if you're making thousands of them you send your code to Atmel and they burn it to the chip in the factory for you - at a price of course.


Can you create an array for functions? Let's say I want to create 10 functions, named Function1, Function2 until 10. Each function is used if a certain variable is equal to its number. Rather than using individual functions, I was wondering if its possible to use some sort of array concept for functions when it comes to naming? I tried reading about it and saw pointers but I honestly didn't understand what I saw about it because I'm not that adept to the language yet.

Here's an example of how to do it:
jump_table.ino
int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5,
                               func6, func7, func8, func9, func10 };

void setup() {
}

void loop() {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

All functions stored in the array must have the same signature.  This simply means that they must return the same type (e.g. int) and have the same arguments (a single int in the example above).

You can do the same with static class methods (but not instance methods).  For example you could use MyClass::myStaticMethod in the array above but not MyClass::myInstanceMethod nor instance.myInstanceMethod:
class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

There's a similar question over on stackoverflow.


Unexpected results and hard crash when modifying and addressing arrays & variables within a struct I'm trying to use a 2D array inside a struct on my arduino to store sensor readings. I'm having two main problems:

1: My Arduino is crashing and resetting when I try to access certain directories in my Array

2: My arraysize variable doesn't seem to be incrementing the way I'm expecting it to.

I've attached snippets of my code that I think are relevant.

struct calibration
{
  float NTU[];
  unsigned int readings[][28];
  unsigned int arraysize = 0;
};

//Main
void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Waiting...");
  if (digitalRead(inputPin) == HIGH)
    TakeReadings();
  delay(50);
}

//after taking many readings from a sensor and averaging...

Calibration.readings[Calibration.arraysize][0] = average;
Calibration.arraysize++;
PrintMatrixToSerial();

//serial print function

void PrintMatrixToSerial() {
  Serial.print("1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1");
  Serial.println();
  for (int i=0; i<Calibration.arraysize; i++) {
    for (int j=0; j<7; j++) {
      Serial.print(Calibration.readings[i][j]); Serial.print("   ");
    }
    Serial.print('\n');
  }
}

When trying to assign values to my Calibration.readings array in certain directories, the Arduino hard crashes. For instance, a crash happens when the arduino tries to execute:

Calibration.readings[Calibration.arraysize][2] = average;

Secondly, after running my TakeReadings() function only once, I expect Calibration.arraysize to be equal to 1, therefore the PrintMatrixToSerial() function should only print one row of data; however, the serial monitor prints many rows. The following is an example of the output:

1.9,1  3.8,1  7.5,1  15,1   30,1   60,1   120,1

11   298   0   65292   779   1284   6
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
167   167   167   167   167   167   167
0   167   167   167   167   4245   40853
167   167   167   167   167   167   167
319   167   167   167   167   167   167

Is there an issue with my struct, or array declaration? I'm stumped at the moment, so any help would be appreciated.

You are not specifying a size for your readings array:

unsigned int readings[][28];

That is not saying "Give me an array of an unknown number of chunks, each of 28 values", it is actually saying "Give me a pointer to a block of memory (which I will provide later) which is arranged in rows of 28 values".

In C you must either provide a size for an array, in which case the memory is statically allocated for you, or manually allocate the memory at a later date.

unsigned int readings[16][28]; // 16 rows of 28 int values

Or, for dynamic allocation:

unsigned int readings[][28];

// allocate the memory ...
blah.readings = malloc(16 * 28 * sizeof(int));
// do things with your array ...
// and free up the memory when finished:
free(blah.readings);

On an embedded system it is generally to know how many readings you will be taking beforehand. That way you can allocate the correct number of rows to the array before you compile the program, which makes many things more efficient.


Standalone Atmega 2560 ISP program First I need to say, I'm a complete electrics newbie, so I need your help.

I have got a standalone Atmega 2560, which I want to program. I connected MISO, MOSI, SCK, RESET, 5V and GND to an Arduino Uno.
In addition a 16MHZ oscillator is connected to XTAL1 and XTAL2 plus I pull all VINs of the Atmega with a 100nF to GND. Plus I connected a separate VIN and GND to the 2560.

I programmed the Arduino Uno as an "Arduino as ISP". Afterwards I connected the 2560 as mentioned above, changed the board to "Mega 2560" and tried to upload a sketch through the Arduino and I get the error message:
avrdude: stk500v2_getsync(): timeout communicating with programmer

Is there something I missed?

Cheers
jb

I have a sketch that programs bootloaders. A side-effect of that sketch is it fixes up the "divide clock by 8" fuse.

It looks like the wiring will be the same, but cross-check on that page (scroll down to the part about programming the Mega2560).

Once a bootloader is installed you could use it, if you get an FTDI cable, or simply go back to using the ArduinoISP now that the fuse is fixed.


What should the frequency reading of the SPI clock be with this code? My Extech EX330 multimeter is reading 3.439Mhz on the pin 13 on my Arduino Uno running the following code. Is the reading correct? If the divider is 2, shouldn't I get 8 Mhz (16Mhz / 2)?

    #include <SPI.h>
void setup()
{
  pinMode(13, OUTPUT);

  digitalWrite(13, HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV2);

}
void loop()
{

  byte pot = B0;
  SPI.transfer(pot);                        //  Do SPI transfer of variable pot
}

Yes, the clock speed should be (and most probably is) 8 MHz.  However, you're not generating an 8 MHz clock.

What you are in fact generating is 8 clock pulses of 8 MHz, then you have a delay while it deals with the rest of your code, and then it generates another 8 clock cycles of 8MHz.

The overall frequency is evidently sensed as 3.439 MHz.

To generate a pure 8 MHz clock you would have to use a different transfer method. I don't know if the 328P has DMA available, but if it does, that would give you much faster transfers.  Also, you could write a more non-blocking version of SPI.transfer().

The normal SPI.transfer() first starts the transfer, then waits for the transfer to finish, and returns the results of the transfer.  If you're only interested in transmitting, and not receiving, or the transmitted and received data don't need to c correlate completely, you can instead change the order of how it works:

Wait for there to be no transfer in operation
Store the result of the last transfer
Start the new transfer
Return the results of the last transfer.

That way it runs much smoother as it's doing the current transfer at the same time as running your other code.


Make arduino board controler for watering system with power bank I am trying to build an off-grid automatic watering system, and I was thinking of many options and the most reliable one that I found is to use a power bank which is charged by a solar panel.

So, I have a solar panel that outputs 5V, and I can charge a standard power bank with it. In addition to this, I bought a USB pump which I can also power with the power bank and controlled using an Arduino board. The problem is that the power bank doesn't support charging and discharging at the same time, and I thought that I could use an Arduino board to control this, but I have no knowledge on this. Therefore, I need help.

Is it possible to have a system like the one sketched below, where the Arduino board controls the input/output of the power bank?

The black path is my current path, but I was wondering if I could do the red path so that I can have both chargings from the solar panel and discharge due to the pump and Arduino board.

Is it possible? Yes.
Is it easy? Maybe.

A relay shield or similar would allow you to break the power connection from the solar panel to the power bank input, wait 5 seconds and then connect the power bank output to the pump.
Once you are done with the pump you could disconnect power from it and reconnect the charging power.

That is all fairly straight forward, maybe a dozen lines of code and some very simple wiring.

The issue is where does the arduino get power from? Or more accurately how does the arduino maintain power during the transitions between different power sources. How much of an issue this is depends a lot on how quickly the power pack transitions from charging to outputting and back and how you want the system to behave overnight or other times when there pump is idle but there isn't much sun light.

Also have you done a power budget? How much power does your pump take and how much power does your solar panel output under normal usage? Based on those two how long per day can you run the pump for assuming an ~80% efficient battery pack.


Good tips for how to connect cables into Mux Shield II? I just got a Mux Shield 2 and got it working as I expected. Now I started to find out how to actually connect the I/O cables to the board. Doesn't seem to be as simple as I thought. I don't want to solder cables into the board for maintenance reasons. So, does anyone have any good tips on how to do this?

Solder 100-mil male headers onto the board, then use 100-mil crimp terminals to connect the wires.


How do I send data to an Arduino via light flashes I want to send a very small amount of data to an Arduino via visible light ( blinking lights on a screen ). The data is no more than settings and the rate does not have to be fast. Does anyone have a method for doing this?

I can't yet make a comment, too much a newbie yet, so am submitting this as an answer.

I have been using this Instructable as my entry point into All Things Arduino and there is src code you may be able to use.

http://www.instructables.com/id/Programmable-LED/

This uses an ATTiny to detect and record changes in a photoresistor, and use the result to play back the same flash sequence that was received.

Other than the pin mapping being different, and lack of reliance on higher-level Arduino core functions : ) it could be useful to you.

the big thing I see is that we and you may not know the delta in resistance a photoresistor might see from your screen flash.  However, the src available from the link does contain a configurable delta in measured resistance (so even a dim flash could work, if you change the threshold in the code).

There are also code snips in the comments that help measure the "background" light level, before enabling the sensor to "record".
This could be useful for low- or high- background light levels as you may find in a lit (or poorly lit) room.


If I try to pause my loop function my output screen starts printing trash I am working of on a Wemos R1 D2 board with VL53L0X Laser Sensor. I need to stop my program after calculating an average of 50 readings but as soon as I try while(1) { } or any other method my output produces garbage.

void loop()
{
  float initial=0,inside=0,outside=0,sum=0,x;
  for (int i = 0; i < 10; i++) {
    x = sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
    sum = sum + x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
  while(1) {};
  Serial.flush();
}

ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.

Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.

The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.

I would suggest adding a delay() or yield() to your while block will fix the problem.


Arduino as ISP without a computer Has anyone seen or know of a method of preloading (using a computer or whatever) a firmware as data onto one arduino set up to operate as an isp and then using that arduino plug the isp interface into another and upload the firmware.

To be clear - i'm looking for a way to make uploading arduino sketches possible without a direct connection to a full blown computer.

Ideally the steps involved would be:

Write new sketch/firmware
Compile firmware
Write a copy firmware onto Arduino A as data (Arduino A is set up to work as ISP)
Detach Arduino A from the computer
In a seperate location attach Arduino A to Arduino B using ISP headers
Using some method (maybe a pushbutton) trigger Arduino A to upload the preloaded firmware onto Arduino B.

I'm assuming that theoretically it could work because uploading firmware is just an exchange of bytes across the SPI interface but i'm not sure about the reality.

The scenario for which I'm considering is if I were to install an arduino (permanently) in a location that is remote from my computer (I don't have a laptop nor do I want to get one) it would be troublesome to reprogram it.

The other method I have considered is using the DIL packaged ATMEGA which I can then remove from the board and program at the computer and return to the board - however I would much prefer not to risk bending of pins and the hassle of having to remove the chip each time I want to reprogram.

I think µProg – tiny, fast, portable AVR programmer with SD does what you want. You can store multiple files in the SD card (hex, eep etc) and select from the device menu which one to write to the target MCU without any need for a PC.
The best part is that it's available for free (PCB, schematic, firmware etc).

One of a kind, portable AVR programmer! Helps wherever you need to
update the device firmware, where target device is in a hard-to-reach
location and you can’t (or don’t want to) bring your laptop with a
bunch of wires with you. Trivially easy to use, super cheap to make,
super small, super fast, uses SD cards…
Features:

super small – dimensions 44 x 39 x 5,5 mm
super fast – write up to 12,5kB/s, read up to 14,5kB/s
uses cheap storage medium – small MICRO SD cards
supports FAT16 and FAT32 file systems
can read, write, verify flash and eeprom memory
can read, write, verify fusebits and lockbits
write and read to BIN, HEX, and TXT files
can set default values of fusebits, erase memories
cheap, easy to obtain, LPH7779 graphic display
shows funny animations after every operation
standard programming header – Atmel 6-PIN ISP
has a function of auto-update its own firmware (from SD)
very simple to use, 4 buttons navigation
user-setting menu
programming speed auto-selection (up to 4MHz)
Operates at 3V, programs chips supplied from 3V to 5V

Supported chip list


Button that increments a counter #include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);

}

void loop() {
  uint8_t buttons = lcd.readButtons();
  int a;
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      lcd.setCursor(0,0);
      lcd.print(a);
    }
  }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

Your code, simplified, is:

void loop()
    int a;
    a += 1;
}

The problem here is that, by putting the declaration of your counter variable within the loop() function, you've made it local to that function. Every time loop() is called, a new variable a is created, initialized to zero, and then incremented.

You want to move the declaration outside of loop(), creating a global variable that will remain in existence and maintain its value after loop() exits, so that the value is still there when loop() is called again:

int a = 0;
void loop() {
    a += 1;
}

(This could also be done with a static variable, but that's probably beyond the scope of this question.)


Setting serial number on CH340 USB-Serial device Reading http://playground.arduino.cc/Linux/Udev there appears to be a way to write out to a FTDI USB-Serial EEPROM to set a given SerialNumber, allowing you to identify a given nano/other arduino to handle it specifically in UDEV.

I have a nano-style boad with a QinHeng Electronics HL-340 USB-Serial adapter, which clearly isn't an FTDI chip, and the FTDI programmer therefore doesn't work. Does anyone know of an alternative utility/where I can find information to do the same with this chip?

Currently the device identifies itself with:

[ 6850.608080] usb 2-1.2: new full-speed USB device number 7 using ehci-pci
[ 6850.701496] usb 2-1.2: New USB device found, idVendor=1a86, idProduct=7523
[ 6850.701505] usb 2-1.2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
[ 6850.701510] usb 2-1.2: Product: USB2.0-Serial
[ 6850.702201] ch341 2-1.2:1.0: ch341-uart converter detected
[ 6850.704210] usb 2-1.2: ch341-uart converter now attached to ttyUSB0

Which is essentially useless, as I can't identify the given board attached (when I attach two, their details are the same).

There is no storage on the CH340 and family of UARTs where you could put a unique ID. This is also a problem for the PL2303 type. I have been trying to find solutions for this problem. First and easiest is the position of the device on the USB bus. It will be unique for each device. If you're using linux you can find each device under /dev/serial/by-path . There is also a /dev/serial/by-id but there will only be one entry there for this device because it shows the last one connected. FTDI chips will each have unique entries here. Cheap chips won't, but they each have an entry under /dev/serial/by-path.
This position, and the device names, should persist across reboots. If you have a lot of changes to your USB devices, plug all the CH340 devices into the same hub, then plug that in. The devices will enumerate in the order that they are plugged in to the hub. This one-hub trick should work for MacOS and windows too, they should come up in the same order.

Harder method- udev rules.
For devices with a unique ID such as FTDI you can set a udev rule that sees it's serial number and then creates a symlink to that device, it's straightforward.

For devices with the same or no Serial number, it's a lot more complex. I created a udev rule that looks like this:

SUBSYSTEM=="tty", ATTRS{product}=="USB2.0-Serial", RUN+="/usr/local/bin/cheapduino.py %k", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", ENV{ID_MM_DEVICE_IGNORE}="1"

when the device matches the product and vendor of the cheap arduino, it runs the script 'cheapduino.py' with the device as argument, for instance

cheapduino.py ttyUSB0

Then the cheapduino script connects by serial to the device and sends the string 'ID' and the software on the device responds DEVID=THX1138 or whatever. The script then creates a symlink /dev/THX1138 that points to /dev/ttyUSB0

There are a lot of drawbacks to this method. The script must time out if the software on the cheapduino doesn't answer. Also this is not using the SYMLINK function of udev so it won't clean up dead links on disconnect, but it will overwrite them on reconnect. All of your cheapduinos must have this functionality in their software, with different device IDs set. They all must use the same baud rate as the script unless you want to write a very complex script that takes a long time. Finally, this method works much better at low baud rate than at high baud rate, which for timing reasons may not succeed every time. (cheapduinos are cheap!) 9600 works much better than 115200 which works after several tries. But since all your CH340 arduinos must be the same speed with this method, you can only go as slow as your fastest device.

This method DOES work though, and it's what I'm using because I bought way too many of these cheap things.

In the end, buy genuine Arduinos or at least ones with FTDI chips or something else that sends a unique device ID.

=Rich


Possibility of installing custom firmware from Arduino Uno R3? I've been messing around with installing keyboard firmware onto my Arduino UNO R3 (I used this tutorial) and had an interesting idea: would it be possible to have this install custom firmware, automatically? If so, how would it be done via a DFU programmer?

Yes, if your Uno (or other Arduino) uses an Atmega8U2 or 16U2 for its USB interface, you can use dfu-programmer or dfutool within a script to automate downloading of new firmware into the USB interface chip(s).  In general, that new firmware should support USB communication with a host, plus whatever new capabilities you want to provide.


Controlling an MCP41HV31 Digital Potentiometer I need to control a 10kOhm digital potentiometer in rheostat mode in 256 steps. I found an Arduino tutorial, which works with an MCP41010 (I added a viper resistance according to the datasheet). This works fine - I can send values from 0 to 255 to the CS pin an the resistance between output pin A and B changes from 0 to 10kOhm.
The problem is, that my application requires 16V to go through this resistance, which the MCP41010 can't handle.

I tried to go with a MCP41HVX1 high voltage digital potentiometer (which I soldered on a TSSOP-to-DIP Breakout board) and assumed it would work the same way. Turns out it doesn't... My connections are:

Arduino nano -> MCP41HVX1

10 -> CS
11 -> SDI
13 -> SCK
5V -> VL
GND -> DGND

With the MCP41010 I connect a 115Ohm viper resistor between output pin A and wiper terminal and measure resistance between output pin A and B (pink connectors). I noticed, that the MCP41HVX1 has a different description for the rheostat modus but I can't get that to work either.

This is my circuit that works with the MCP41010

And here is the respective code (which sets the MCP41010 to 255 i.e. 10kOhm)

#include <SPI.h>
byte address = 0x11;
int CS= 10;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
  digitalPotWrite(255, CS);

}

int digitalPotWrite(int value, char Port)
{
  digitalWrite(Port, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(Port, HIGH);
}

Has anyone ever done this or has a clue what's going on?

I realize that this thread is old. I am providing an answer for anyone else who may end up here like I did a while back looking to solve this.
I have created an Arduino library on Github (https://github.com/gregsrabian/MCP41HVX1) which allows for control of this family of chips. The README.md within the github project documents all of the APIs and also provides the wiring diagram. There are also example sketches included.
I have created an article on Instructables (https://www.instructables.com/id/MCP41HVX1-Digital-Potentiometer-for-Arduino/) that provides a step by step on how to control this family of chips. There is also an explanation on how to solder the TSSOP chip.


(very new to C) I'm trying to use irsend with what I think is char* but it won't take it. How can I convert it to what it needs? I'm attempting to use a raspberry pi to send ir codes directly to my arduino to have as simple as a C program as possible. Here's my code I've been tinkering with that leads to errors or not working if I don't specifically hardcode the hex ir signal.
#include <IRremote.h>

char buf[80];

String code = "empty";

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

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

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

IRsend irsend;

void loop() {
  if (readline(Serial.read(), buf, 80) > 0) {
    Serial.print("You entered: >");
    //Serial.print(buf);
    //Serial.println("<");
    //irsend.sendNEC((uint32_t) buf, 32);
    String str(buf);
    //irsend.sendNEC((uint32_t) code, 32);
    //irsend.sendNEC(0x210704FB, 32);
    code = buf;
    delay(600);
    //Serial.print((uint32_t) buf, 32);
    Serial.print(code);
    irsend.sendNEC(buf, 32);

  }

I've left my mess on the bottom to illustrate how little I know and what I've tried. I've been trying to figure out what I'm sending it but it doesn't help that serial.print doesn't work like irsend. I'm intending to send hex codes directly and have the arduino blindly plug them into irsend.sendNEC(0x210704FB, 32); which works but when I try to put my own variable in it won't.
Very much appreciate any help! I know it'd be easy for anybody who knows a little C.
irsend.sendNEC(buf, 32); returns:
initializing argument 1 of 'void IRsend::sendNEC(uint32_t, uint8_t, bool)'
void sendNEC(uint32_t data, uint8_t nbits, bool repeat = false);
and irsend.sendNEC((uint32_t) buf, 32); doesn't throw any errors but also does not seem to do anything

If you are sending HEX values like 0x1234abcd from the Pi to the Arduino to send those as an IR code you first have to interpret that string data as a hexadecimal number.
That's not as simple as just casting the string since, as @timemage says, all you're doing there is casting the address of the character array.
Instead you should use strtoul() to parse the string and give you the equivalent number to what it contains.
strtoul() can convert numbers in a number of different bases, and can even work automatically.  From the Linux man page:

SYNOPSIS
unsigned long int strtoul(const char *nptr, char **endptr, int base);

And later on:

If base is zero or 16, the  string  may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal).

That means it can automatically parse 0x1234abcd as a hexadecimal number, 12345678 as a decimal number, and 052714 as an octal number (it's important to remember that one so you don't accidentally add a leading zero to a decimal number and have it parsed wrong).
So knowing all that you can now:
uint32_t code = strtoul(buffer, NULL, 0);

and code will contain the contents of buffer represented as an actual numeric variable (assuming the content can be parsed as a number).


Using Arduino to pass data from a coin collector to android app Okay. Basically I want the android app to be able to recognize that a coin was inserted into the coin collector before it allows the user to use certain functions of the app.

However I am unsure what would be the best way to pass the data from the coin collector to the Android app.  My currently train of thought is to have the coin collector connect to an Arduino board which would then connect to the android app and send the input through that connection.

I was wondering if anyone knows of a better way to achieve this, or whether this is an acceptable/standard solution.

Thank you in advance!

Here are a couple of opitions for you:

1- Bluetooth - if in close range, an HC-05 will work great.

2- Wifi - wifi can work good. It is a little more complex then bluetooth but its range can get further. For example, a Tweet can be sent each time a coin is detected.

3- GSM - it is pretty much texting. You can make it so the coin collector texts you or someone there is a coin.

All of these solutions work great with the MIT app creator. It makes the data you receive much easier to process.


Serial Port fails with speeds greater than 19200 In Arduino Mega 2560 R3, properly selecting the Serial Monitor bauds, this code works with #define R 38400, but for some reason, not with #define R 19200 (?),

#define R 38400
int rate=R;
HardwareSerial* hwSerial[]={&Serial,&Serial1,&Serial2,&Serial3};
void setup() {
    for (int i=0;i<=3;i++){
        hwSerial[i]->begin(rate);
        while (!hwSerial[i]);
    }
    hwSerial[0]->print("Hello World");
}

void loop() {
}

Both speeds should be not problematic for Arduino, what is happening?

It seems the int rate R; is problematic when changing speeds (??).

Answer is simple. You assign 38400 to a variable of type int. The signed range of integer values that can be stored in 16 bits is −32,768 through 32,767;


3.3 V Pro Micro clones flashing LEDs after 1200 bit/s touch I have several Pro Micro clones.

This morning I uploaded a sketch into one of them (that was previously unprogrammed, so it stayed in bootloader mode) and when I wanted to upload the sketch a second time, the problem began:

When I now run the reset procedure for Arduinos with integrated USB (open the COM port of the Pro Micro for example in PuTTY at 1200 bit/s and close it again), the LEDs start flashing rapidly and the Arduino disappears from the Windows Device Manager.

Hover for a (slightly annoying) image:

So then I grabbed a second, identical Pro Micro and uploaded the Blink sketch into it. It was also previously unprogrammed. The sketch executed, but when I now do the reset procedure, it exhibits the same behavior now (flashing LEDs).

I can still upload sketches just fine, by setting the COM port to a different (arbitrary) COM port to prevent the reset procedure from reaching the Pro Micro and resetting the Pro Micro manually after starting the upload procedure.

This only happens with the 3.3 V/8 MHz variant, not with the 5 V/16 MHz variant. I have selected the appropriate variant in the IDE.

How can I repair the automatic reset function?

I was finally able to solve this by using one of the Pro Micros to re-burn the bootloader of the other one.

For reference, the process is like this:

Flash the example sketch "ArduinoISP" into the first Pro Micro
Connect the two Pro Micros like this:

Programmer (on USB)   Target
GND ----------------- GND
VCC ----------------- VCC
15 ------------------ 15
14 ------------------ 14
16 ------------------ 16
10 ------------------ RST

Choose "Arduino as ISP" as Programmer
Because both are Pro Micros, selecting a different board is not necessary.
Click "Burn Bootloader"


LCD Identification FPC-JG00467-01B SR36 I salvaged an old LCD from a calculator (Texas Instruments) and I want to interface it with a microcontroller (preferably an Arduino). I‘ve searched the whole internet but I simply can‘t find any information about this display and its driver. I am looking for a specialist who can identify this:

It's most likely a custom part for which there is no public data sheet. LCDs are almost always custom-designed, and require special driver circuitry. This is especially true for such mass-produced items as calculators.


Opening .h and .cpp files from folders other than the sketch folder My team has a C++ program from another microcontroller that we are moving to Arduino, which is currently divided into two main folders, the sketch and libraries. We want to be able to open some of the library files in the Arduino IDE along with the sketch, something it will do automatically if they are in the same folder, but not allow otherwise. The files in question are referenced from the other libraries though, which means moving just a few of them results in compilation errors. We don't want to move them all to the sketch folder, since that defeats the purpose, but a few of my teammates are vehemently opposed to having to edit them using another IDE.

So is there a way to have these files open in the Arduino IDE with the sketch? Or do I have to tell my teammates to suck it up and use a second editor if they want to make changes?

Alternatively, a way to get the libraries able to reference files in the sketch folder would also work.

I don't recommend this

A) Because the arduino editor is pretty bad for serious coding

B) Because you will need to have a header guard on all library code that doesn't have one already (even in .cpp's)

But, if you really have to, the only way I can think of is to make a symbolic link to the library file in the sketch directory. It works, but the file gets compiled twice, so you need those header guards on everything.


Can I have two separated serial monitor for the same arduino board connected to PC? I'd like to split serial communication into the two channels: 1) debug info, 2) application data.

There's only one Serial object to use.

However, maybe, there is an alternative way to print data separately, is there?

P.S. I use Nano and UNO.

If you want to have two Serial Monitors, start the IDE twice. Use your desktop shortcut or start menu entry to start the second instance of the IDE. In the second instance you can select a different port. It will not work for Upload of course, but when you open the Serial Monitor, it will work at the selected port.

Other option is to use some terminal program to see the output of the com port.

The other answers cover the fact that you need an USB to TTL Serial adapter to connect to USB and in sketch SoftwareSerial as your second serial interface or use some board with two or more hardware serial ports like the Mega on the picture.


how to use mouse.h library for arduino uno I want to use mouse.h library with arduino but mouse.h library only for Leonardo not UNO . How to use mouse.h for UNO if not
can we convert arduino UNO to Leonardo ?

The only way to use Mouse.h on an Arduino is to use it on a compatible Arduino. You cannot "convert" an Uno into a Leonardo, since you would have to not only replace the MCU on the board (with one that is SMD only), you would have to replace the PCB itself as well. I.e., throw away the Uno and replace it with a Leonardo.

The Mouse.h (and Keyboard.h) requires an MCU with a built-in USB interface, such as the ATMega32U4 that the Leonardo has. The ATMega328p does not have such an interface (note: the "U" in the name kind of gives it away...).

However, all is not lost.  The Uno does have a chip on it with a "U" in the name (as long as it's a genuine Arduino board and not a cheap Chinese clone with a CH340G chip).  That chip, used to interface the ATMega328p to the PC through USB, can be reprogrammed to look like different devices, however doing so can break your ability to then program the Arduino itself.

You can read more about hacking your Arduino to be a mouse here.


How can I connect nodemcu with laptop wifi Question is odd, but I want to know that how I connect nodmcu with a laptop wifi without using any router. Is it possible if yes then how?

Configure and activate the access point mode on NodeMCU. It creates a WiFi network and you can connect to this network with your computer.


Issue with Indenting the Serial Print data in the Serial Monitor I have a question with Serial Print. I want the Sensor reading values to fall under 3 columns, and each column should have the readings from the same sensor.

Raw Value |    Sensor 1 |   Sensor 2  |   Sensor 3

how can I modify this code do this?

Below I have posted my code and what I currently see using the Serial Monitor

    void loop(){

  RawValue0 = analogRead(analogIn0);
  Voltage0 = (RawValue0 / 1023.0) * 5000; // 5000 to get millivots.
  tempC0 = (Voltage0-500) * 0.1; // 500 is the offset
  tempF0 = (tempC0 * 1.8) + 32; // conver to F
  Serial.print("Raw Value = " );  // shows pre-scaled value
  Serial.print(RawValue0);
  Serial.print("\t milli volts = "); // shows the voltage measured
  Serial.print(Voltage0,0); //
  Serial.print("\t Sensor 1: Temperature in C = ");
  Serial.print(tempC0,1);
  Serial.print("\t Sensor 1: Temperature in F = ");
  Serial.println(tempF0,1);
  delay(500);

Columns with lines?

The sprintf function can fill data with spaces to align them. However, the Arduino sprintf function does not support floating point variables. The dtostrf function has already a fixed output width by itself.
The sketch below is a combination of UTF-8 characters and the dtostrf and sprintf functions.

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

  Serial.println();
  Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
  Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
  Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
}

void loop() {
  int raw = random(0, 1024);
  float c = random(-1000, 1000) / 10.0;
  float f = random(-500, 1500) / 10.0;

  char buffer_c[20];
  char buffer_f[20];

  dtostrf(c, 6, 1, buffer_c);
  dtostrf(f, 6, 1, buffer_f);

  char buffer[80];
  sprintf(buffer, "┃ %4d ┃ %s ┃ %s ┃", raw, buffer_c, buffer_f);
  Serial.println(buffer);

  delay(500);
}

The strlen() function can not be used before printing a floating point number to the serial port, since its length is determined while printing characters to the serial port. The final number of bytes that is written is the return value.
There is a way to use that return value, by using a dummy write to a dummy serial port. After that the number of spaces to align the floating point number can be calculated.

That reduces the code size from 6160 to 4708 for an Arduino Uno.

class DummyClass : public Stream
{
  int available() {return 0;}
  int read() {return 0;}
  int peek() {return 0;}
  void flush() {return;}
  size_t write(uint8_t) {return 1;}
  using Print::write;
};

DummyClass Dummy;

const int width_r = 4;
const int width_c = 6;
const int width_f = 6;

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

  Serial.println();
  Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
  Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
  Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
}

void loop() {
  int raw = random(0, 1024);
  float c = random(-1000, 1000) / 10.0;
  float f = random(-500, 1500) / 10.0;

  int i;
  Serial.print("┃ ");
  Spaces(width_r - Dummy.print(raw));
  Serial.print(raw);
  Serial.print(" ┃ ");
  Spaces(width_c - Dummy.print(c,1));
  Serial.print(c,1);
  Serial.print(" ┃ ");
  Spaces(width_f - Dummy.print(f,1));
  Serial.print(f,1);
  Serial.print(" ┃");
  Serial.println();

  delay(500);
}

void Spaces(int n)
{
  for(int i=0; i<n; i++) {
    Serial.print(' ');
  }
}

I advise not to use this "Dummy" trick. It is mere a coding exercise. I can not find a problem with this trick, but I'm not 100% sure that it is okay.


Funduino Joystick Shield with Bluetooth I have a Funduino Joystick Shield (See here Funduino on Gearbeast store) which has some Bluetooth pins.

Does anyone know what pins they are connected to, and has anyone successfully connected to a BT HC-05 device using SoftwareSerial?

Well, it turns out that the tx/rx for the board are connected to the standard pins 0 and 1 on the Arduino.
To use this, you can simply use Serial.write.
Of course, remember to take of the module when trying to upload your code.....


Optical Rotary Encoder Index issue I have the following code working correctly except for the Index portion.
I am not sure if I have the syntax correct for the hardware.  The end result I am looking for is to have the encoder reset to 0 degrees every time the index comes around (360 degrees).
I am also looking for any comments on the code as I would like the encoder output to be as accurate and efficient as possible.

Here is the code:

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

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts
#define CLOCKWISE            1       // direction constant
#define COUNTER_CLOCKWISE    2       // direction constant

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

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

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT_PULLUP);
  pinMode(ENCODER0PINB, INPUT_PULLUP);
  pinMode(ENCODER0PINI, INPUT_PULLUP);

  // interrupts
  attachInterrupt(3, onInterrupt, RISING);
  attachInterrupt(4, onReset, CHANGE);

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

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

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible
void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

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

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);

  if (i = 1)
  {
  encoder0Position = 0;
  }
}

In your onReset() function you have an assignment instead of a comparison:

if (i = 1) // This is always true
{
encoder0Position = 0;
}

i = 1 should be i == 1


appending string to char and vice versa Some days ago i started a thread.
concatenation of non constant character array with a sting

I have a different question but on the same nature (string and chars)

what i want is one variable (string or char) that will hold a standard text and the value of gps coordinates latitude and longitude

The format is this: "latitude/longitude: 30.111111 20.111111"

What i have is a char that holds the standard text and the latitude: "Latitude/Longitude: 30.111111"

I also have another char that holds the second value (longitude)

The chars were generated with dtostrf():

char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);

I can also make the chars strings:

string1 = String(clat);

What have i tried:
1.Assigning clng to clat directly via dtostrf()

char clat[10 + 20 + 10 + 1] = "Latitude/Longitude: ";
dtostrf(gps.location.lng(), 10, 6, clng+31);

It didnt work and got unexpected output

making clat a string and assign clng via for loop

string1 = String(clat);
    for (int i=0; i<10; i++)
    string1[i+32]=clng[i];

This doesnt append it

I run out of ideas here.
Any help from more experienced guys?

solved it. was simple actually. dont know how to do it with chars, but with strings there is the addition operator.
So i converted both to string and used the + operator.

char clat[10 + 20 + 1] = "Latitude/Longitude: ";
char clng[10 + 1];
String string1, string2, finalstr;

and inside the loop:

dtostrf(gps.location.lat(), 10, 6, clat+20);
dtostrf(gps.location.lng(), 10, 6, clng);
string1 = String(clat);
string2 = String(clng);
finalstr = string1 + string2;

Maybe that was too much work?
If you have any smarter alternatives, please provide!


Arduino Pro Micro - switch off LEDs I am using a Arduino Pro Micro as a keyboard (USB HID device). Each time I press a key, the RX LED and TX LED light up. Can I switch them off in software?

Kind of.

You don't have to change pins_arduino.h.
Try the LED_BUILTIN_TX and the LED_BUILTIN_RX.
The pins are turned on and off by the code for the SerialUSB port. That can not be changed without changing the Arduino libraries. Setting that pin to INPUT in your sketch in the setup() function will turn them off:

pinMode(LED_BUILTIN_TX,INPUT);
pinMode(LED_BUILTIN_RX,INPUT);

If you have troubles with the LED_BUILTIN_TX and the LED_BUILTIN_RX, then you can use this as well:

bitClear(DDRD,5);
bitClear(DDRB,0);

The code for the SerialUSB port still writes to that pin, but once they are set as INPUT, that code will turn on and off the pullup resistor. That is no problem since those leds are connected to VCC.

To turn them on is also possible, but then those pins needs to be OUTPUT and LOW. They will not stay on when the SerialUSB port is used.


Arduino UNO USB not recognized I've just received my Uno today and already I think I may have broken it :(

I was able to connect to usb and upload a sketch (the blink). However, I then tried to connect a circuit to do the Hello World LCD example. After trying this a few times, I noticed the LCD chip get very hot...and I had mis-wired it. In any case, after a few more tries, the USB connection to my Arduino UNO stopped working.

I tried swapping the cable, connecting it to another mac and to a windows with no luck. I'm worried I may have shorted the USB bus chip when trying Hello World.

I also tried connecting a 12V DC power supply.

I still get the green power light and the amber L light...
Did I break my Uno?
How do I troubleshoot this one?
thanks

When the LCD pulled enough current to overheat, the Arduino's power supply (which I gather was the Uno's USB interface, at the time) was probably stressed to the point of failure. One fortunate result is that the Arduino took the hit instead of the computer's USB port that was supplying it. It's not clear which part was involved but here's a discussion on another forum concerning a similar failure and replacing the ATMegaxU2 which does USB-interface duty on the Uno (x = 8, if it's a rev 2 Uno, x = 16, if rev 3). It may be possible to replace the failed chip - regulator or USB interface (though with LEDs working, it's probably not the regulator). Otherwise, you can probably still program it with an ISP (In System Programmer). But the easiest way to do that is probably involves another Uno.


Which sensor bus best to use? I am working on a project which requires a dozen VL53l0X I2C-TOF sensors to be polled by one master MCU over a few meters of cable.
Thus, I decided to accompany each TOF by an Atmega8 acting as a gateway between the TOF and a Modbus (using a MAX485), which is managed by an ESP32 (the master). Since I require fairly low latency (~10 reads / sensor / second) I am a bit disappointed by the Modbus RTU performance (mostly caused by the forced 1.75ms delay between frames).
My question: Is there any quicker, more suitable, Atmega-bearable bus protocol for long distances? Ethernet is sadly not an option due to the limited slaves computing power and cost...

CAN for the Phy (physical) layer would be good for several thousand feet. You can use whatever baud and protocol on the CAN layer you like within reason. I am assuming (maybe in error) that they all communicate on the same bus. This CAN Phy was designed for this. It would be possible for you to write your own protocol and simply address each by a unique number or whatever. There is also the option of using a CAN controller but I think that would be a lot of time not needed to design your solution. By placing a Atmega8 at each sensor opens up a lot of possibilities for you.


Arduino Mega 2560 ADC sampling instant and other timings Hello Everyone (I might be making some mistake in asking this "question", bear with me as I am new to these sites... I honestly think this is the best way to frame my inquiry because it's rather elaborate)

I'd like some help in understanding the "timings" of Arduino MEGA 2560's ADC module, especially with respect to the command analogRead.

I read ATmega2560 microcontroller Datasheet

Let's assume, for now, that our conversions are normal ones ( the other type being a "first" conversion, which takes 25 ADC clock cycles instead of 13, due to the time required for the initialization of analog components )

From what I understood, on a normal single conversion, the sample and hold happens after 1.5 ADC clock cycles from the start of the conversion.

Let's say that I set the prescaler to 32 with the following commands:

const unsigned char PS_32 = (1 << ADPS2) | (1 << ADPS0);
const unsigned char PS_128 = (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);

ADCSRA &= ~PS_128;  // remove bits set by Arduino library
ADCSRA |= PS_32;  // set our own prescaler to 32

hence 16MHz / 32 = 500 kHz should be the new ADC clock frequency
( or 2 microseconds ADC clock period )

since a normal single conversion takes 13 ADC cycles, the entire conversion should take about 26 microseconds

If I'm not mistaken, (2 microseconds * 1,5)  = 3 microseconds after the ADC conversion starts, my analog pin value is set on hold, right?

I measured the elapsed time using the micros() function and, like I'd expect,
I found out that there's a little overhead introduced with analogRead function
because it takes about 28 \ 32 \ 36 microseconds (these are empirical measures).

analyzing the code in wiring_analog.c
( which is located in the folder [...]/arduino/hardware/arduino/cores/arduino/ )
the actual conversion seems to happen at line 77

// start the conversion
sbi(ADCSRA, ADSC);

does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?

how can I know how much time passed before that sbi function call is issued?

I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)

Now, considering the so called "first" conversion, which take 25 ADC clock cycles

does this conversion happen just the first time I call analogRead since I powered on Arduino?
or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)

Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?

does that mean that this is the instant from which the actual ADC
  conversion start, and so 1.5 ADC clock cycles from here, my analog pin
  value is set on hold?

Yes. After between 3μs and 5μs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.

  how can I know how much time passed before that sbi function call is
  issued?

You could copy the original code and create your own analogRead2 function that measures the time before setting ADSC.

  I saw that a single instruction on arduino won't take more than 4
  microseconds (but micros() function has that resolution so I don't
  exactly know!)

A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms

  Now, considering the so called "first" conversion, which take 25 ADC
  clock cycles

  does this conversion happen just the first time I call analogRead
  since I powered on Arduino? or does it happen even after some time ,
  because the ADC module gets powered off? (of course, I consider the
  case when Arduino remains powered on all the time)

  Judging by the timings I measured it seems like that the former is the
  one really happening, even if I don't use ADC for some time, but can
  anyone confirm?

This first conversion is after the ADEN bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.

PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.

PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.


Arduino Mega 2560 interrupt pins and port mapping with rotary encoder I am trying to use port manipulation in interrupts to read a rotary encoder. I found code for a Uno, so the port call for pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively. My code is not working. Do I have my ports wrong? I've tried reading up on this and I'm not fully understanding the Bxxxxxxxx part. I think that might be what's incorrect. Here is part of my code with one of the interrupts.

static int pinA = 2;
// Our first hardware interrupt pin is digital pin 2
static int pinB = 3;
// Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0;
// let us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0;
// let us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0;
//this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0;
//stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0;

void setup () {
  pinMode(pinA, INPUT);
  // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  pinMode(pinB, INPUT);
  attachInterrupt(0, PinA, RISING);
  // set an interrupt on PinA,
  //looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
  attachInterrupt(1, PinB, RISING);
  // set an interrupt on PinB,
  //looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
}

void PinA() {
  //CCW
  cli();
  //stop interrupts happening before we read pin values
  reading = PORTH & 0xC;
  // read all eight pin values then strip away all but pinA and pinB's values
  if (reading == B00001100 && aFlag) {
    //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos --; //decrement the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  } else if (reading == B00000100) bFlag = 1;
  //signal that we're expecting pinB to signal the transition to detent from free rotation
  sei(); //restart interrupts
}

Re “pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively”, it's true that Arduino digital pins 2 and 3 belong to different ports on Uno vs Mega2560 boards.

Mega2560's have six INTx pins, vs two such on Uno's.  On the Mega, INT0...INT3 are PD0...PD3, and INT4,INT5 are PE4,PE5.  On the Uno, INT0,INT1 are PD2,PD3.  Note, in an answer at Can external interrupts be OR'd together on the '328 (Uno)? I show a couple of routines that will display appropriate masks for pins on different Arduinos.  See the sections “Using other pins for PCIs” and “ISR-framework-generating Sketch”.

Here are a few problems with the code shown in the question:

aFlag is initialized to zero, and is never set nonzero in the code shown.  So the first if condition in PinA() is never met.
PinA() is an interrupt handler, connected to interrupts by your attachInterrupt() calls.  Because hardware disables interrupts before it enters an interrupt handler, there is no need for the interrupt handler to turn off interrupts.  That is, delete cli() in PinA().  Similarly, delete the sei() at the end of PinA() because hardware restores interrupt status when a RETI instruction executes.
The Arduino software environment defines constants like B00001100 with binary values that match the name.  That is, in the Arduino software environment, constant B00001100 has the value 0B00001100.  In my opinion, that's a stupid and unnecessary feature; I suggest that in your code you use standard C notation like 0B00001100 when you want to use binary constant values.
I regard writing encoderPos -- instead of encoderPos-- as a perversion and suggest deleting that unnecessary space.
As you haven't shown the PinB() interrupt handler, I don't know how you were going to handle the encoderPos++ case.  Judging from the code shown, you are using a method that won't correctly handle bounce and intermittent errors.  I suggest using pin-change interrupts and a state-machine method, as illustrated in answers to:
• Reading from a KY-040 rotary encoder with Digispark
• How to read RPS for fast rotation with status change method in Arduino?
• Read RC receiver channels using Interrupt instead of PulseIn
• Can external interrupts be OR'd together on the '328 (Uno)?


How do you figure out an efficient battery setup for a project? I have a project where I need an Arduino Uno and 4 DC motors to run on batteries. My first thought was that I'll just hook up 3 or 4 AAs to the Arduino and a 9V to the motor drivers.

I googled to be safe and the internet consensus seemed like that method would be very inefficient. Voltage wasn't the problem, but apparently 9V have very low current and I'd be wasting money, and the Arduino wastes current like a madman. Most solutions involved buying additional hardware.

Is there a way I can efficiently power my project without buying more chips?

Our beloved admin Nick Gammon has made a very neat articile on this subject, I suggest you read it and apply as many of the methods he described.

Also, it can be worth to check the requirements of your project, how long should it work on battery to be acceptable? Set some realistic boundarys to avoid getting lost in (trying to) optimizing beyond all practical purposes.

There are two places where you can save power:

In software

The Atmega328P has a few tricks to save power.
Most notably is powering down peripheral devices and/or using sleep modes.
I believe the P version of the Atmega328 also has more power saving modes/ is more efficient overall.

Also take a look at this.

In hardware

An Arduino board has a lot of chips that may not even be neccesary on your battery project.
Most notably the USB interface chip, if you're going to run off battery, you most likely won't need this chip.
But also, the voltage regulator on the Arduino is, I believe, a linear regulator and is likely to be inefficient.
Also power/status LED's will some current.

You can choose to put a ATMega328P on a breadboard, and power it directly with a source that will be between the min/max voltage of the ATMega328P. This way you don't get the losses that a regulator will have.
If you want to use a regulator (for a higher voltage source) you should use a switching regulator, they're typically more efficient.

Mind that on low voltages, the ATMega328P can't do a 16Mhz, but it's actually a pretty interesting point, since it will consume less power on 8Mhz, or even less on 1Mhz.