Join Serial Data Seperated by Newlines? I have two Arduinos connected through Bluetooth. One sends a string of data similar to 506:507:1\r\n. The data can vary similar to 0:1000:0\r\n. I already have functions to break that string down into three variables. I send it from one Arduino over Bluetooth and the second Arduino receives it through Serial. The only problem is that the second Arduino receives this:

5
0
6
:
5
0
7
:
1
"\n"

At the end it adds a space at the end ("\n") How can I parse this data back into a string similar to 506:507:1\r\n that can still vary in length?

Simply reverse the steps you took on the sending side.

Create a char array of sufficient size as well as an index variable to keep track of your position within the array. An Arduino String may be more convenient, though they can cause a lot of problems.
In a loop, use available() to wait for incoming chars and add them to the array you've created, using your index variable.
Keep going in the loop, while checking for that unique character (\n, perhaps) that signals the end of a packet. Add this last byte to the array and then terminate the string with null or \0.

If you want to re-use the array for another packet, simply set the index variable to 0 and continue.


problem with reading PS3 controller buttons I'm working on a camera slider mount with an X stepper (to move along slider), Y stepper (pan left right) and Z stepper (tilt up down). All of this is being controlled by a PS3 controller (PS3BT library).

I've implemented a feature in which all three steppers move from one saved position to other and then back again.. this keeps repeating infinitely. It works fine - except I can't stop it - it's more of a programming issue I think. Here's the code in question

// MultiStepper instance - at the top somewhere
MultiStepper StepperControl;

void loop(){
    if(PS3.getButtonClick(START)){ // START to start movement between two POS's.
        Serial.print("\n Starting Movement between POS1 and POS2");
        while(!PS3.getButtonClick(CROSS)){
          StepperControl.moveTo(POS1); // go to POS1
          StepperControl.runSpeedToPosition();
          delay(200);
          StepperControl.moveTo(POS2); // go to POS2
          StepperControl.runSpeedToPosition();
          delay(200);
        }
      }
}

My issue is that pressed X (cross) on the keypad, doesn't quit out of the loop. What I feel is happening is that the loop is running too fast and all the moveTo() commands are stacking on top of each other. And so, even if I do press X, too many moveTo() commands have already happened and it just keeps running those "queued" commands.

I've also tried putting an if statement inside the while loop that breaks out of the loop when CROSS is pressed - no luck.

// This isn't the entire code, just the parts I think are relevant.

The while(!PS3.getButtonClick(CROSS)) is only checked once per loop, so your system will complete a move to POS1, wait 200ms, complete a move to POS2, and wait another 200ms before it can check the controller for another button press.

runSpeedToPosition() is "blocking", which means NOTHING else can happen while it is doing it's task.

Instead, you probably want to avoid blocking functions and set up a finite state machine and use the run() function of AccelStepper, which you should call as often as you can and it will move the stepper one step toward the target position, if it's not yet at the target position.

The following rewrite is not tested, but the general structure should show you how you can change the way the program is written. You should think of the loop() function running and completing a million times a second, and each time through, you check the state (that is, on what step is the system currently on) and act accordingly. Change to a new state when appropriate.

In the example, there are 5 states, corresponding to all possible combinations of what your program could be doing:

STOPPED: the initial state, the stepper has no target
RUNTO1: the stepper is moving toward POS1, but hasn't reached it yet
WAIT1: the stepper has reached POS1 and is now waiting for a specified delay before moving to the next state. This state uses the process shown in the BlinkWithoutDelay standard Arduino example sketch for delaying without blocking.
RUNTO2: the stepper is moving toward POS2, but hasn't reached it yet
WAIT2: the stepper has reached POS2 and is now waiting for the next state

You can also see the situations where a state is changed:

When START is pressed, set a new target position and enter the
RUNTO1 state
When CROSS is pressed, stop all stepper action and enter the STOPPED state
When in RUNTO1 or RUNTO2, and the distanceToGo() is zero, enter to the corresponding WAITn state
When in the WAITn state and the specified time has elapsed, enter the corresponding next RUNTOn state.

Example:

#define POS1 80
#define POS2 0

const uint16_t DELAY = 200;
enum stepperstates {STOPPED, RUNTO1, WAIT1, RUNTO2, WAIT2};

[...]

void loop() {
  static uint16_t last_millis;
  static stepperstates xStepState;
  if (PS3.getButtonClick(START)){
    xStepState = RUNTO1;
    StepperControl.moveTo(POS1); // go to POS1
    Serial.print("\n Starting Movement between POS1 and POS2");
  }
  if (PS3.getButtonClick(CROSS)) {
    xStepState = STOPPED;
  }

  StepperControl.run();

  switch (xStepState) {
    case STOPPED:
      StepperControl.stop();
      break;
    case RUNTO1:
      if (StepperControl.distanceToGo()==0) {
        xStepState = WAIT1;
        last_millis = millis();
      }
      break;
    case WAIT1:
      if (millis() - last_millis >= DELAY) {
        xStepState = RUNTO2;
        StepperControl.moveTo(POS2);
      }
      break;
    case RUNTO2:
      if (StepperControl.distanceToGo()==0) {
        xStepState = WAIT2;
        last_millis = millis();
      }
      break;
    case WAIT2:
      if (millis() - last_millis >= DELAY) {
        xStepState = RUNTO1;
        StepperControl.moveTo(POS1);
      }
      break;
  }
}


Arduino Due's clock frequency I want to change the clock frequency of the Arduino Due. The default value of the main clock, according to the SAM micro-controller, is 4 Mhz. But I found in some forums that it is 84 Mhz. But I need to work with it at 16 Mhz. Hence, I need to access to the low-level clocks of the Due and change its operating clock frequency.

How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?
Is it possible to write code for the Arduino Due via Atmel Studio 7? When I tried compiling code in AS7, Chip.h was not found. How to avoid this? Is it possible with "micro" IDE in AS7? Can I access registers of the Due via AS7 and change its clocking?
I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?

Read the datasheet / programming manuals for the chip. The Arduino Due is arranged to run at 84MHz.

  I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

Install it. The IDE is (fairly) modular these days.

But I have to ask... why do you want to run at 16MHz?


How do I avoid this error trying to connect arduino to pc with linux fedora 20 I used Arduino successfully on my old Linux Fedora 12 system. Now I have a brand new PC with Fedora 20, and have today installed Arduino on it. In my first attempt to use it I typed Arduino as follows at the root prompt, after the "yum install arduino" gave me "Complete!", as follows:

Complete!
[1344][root@localhost:/home/Harry]# arduino
WARNING:  RXTX Version mismatch
    Jar version = RXTX-2.2
    native lib Version = RXTX-2.2pre2

Subsequently I have loaded the "Blink" sketch, and that is running nicely, whether I start the IDE from the command line, which still gives me the same WARNING, or from the desktop icon, which does not give it.

So my question is: please, does this WARNING matter? If so, what should I do about it?

The warning, as I'm sure you can tell, is about a mismatch in version of RXTX arduino is expecting, and what is installed on your system. If everything is functioning, I would not worry about it at all. The versions seem to only be slightly different, maybe just a few bug fixes are missing from the older one.

RXTX is a library for java to communicate with serial devices, but it is not under development anymore and only available from mirrors, not the original developer site. Arduino has moved on to a library called jSSC, which is currently being maintained, and a much better library IMHO. The change to jSSC is still only in the arduino beta version, 1.5.6r2 at time of writing, but it works very well. Anyway, if RXTX ever actually gives you trouble, you can download the beta version of arduino and not have to deal with it.


Using a DFRobot Voltage Divider I'm reading on the DFRobot website to implement this Voltage divider: Analog Voltage Divider SKU: DFR0051

void setup()
{
  Serial.begin(9600);
}
void loop()
{
      float val;
      float temp;
      val=analogRead(2);//This divider module will divide the measured voltage by 5, the maximum voltage it can measure is 25V.
      temp= val/40.92;
      val=(float)temp;
      Serial.println(val);
      delay(1000);
}

Where does 40.92 come from? And even when printing only VAL it's something like 210 and I'm not sure what this is supposed to be. I don't get how to get the actual voltage of the battery etc. being measured? If it's divided by 5, why do you not multiply by 5 anywhere?

The unit measures a maximum voltage of 25v. When the measured voltage is 25v it divides it by 5 to present a maximum of 5v to the Arduino.  That is measured as a value of 1023 by analogRead(). If you divide 1023 by 40.92 you get 25.


What minimum equipment is needed to program the Freematics Vehicle Data Logger? I was looking for a GPS/OBD2 data logger that logs data to an SD card and eventually arrived at the Arduino powered Freematics Vehicle Data Logger. It's great that it's programmable, but I have no experience with Arduino.

Reading the documentation, it says that I program the device either by USBasp or Arduino as ISP. The USBasp is a dongle programmer, but I don't know what is meant by Arduino as ISP.

My goal is to use this device to log data. I don't plan to extensive write programs for it. What is the minimum equipment that I need to have in order to be able to write a bit of code and flash it to the device?

"Arduino as ISP" refers to using an Arduino board in place of a USBasp.  It involves loading a specific sketch onto the Arduino then using the SPI port (and a few other pins) as the programming interface to the target.

It is most often used to program blank chips for use in breadboards by people who don't have a USBasp.  Great for moving your project from the Arduino board to a breadboard without having to buy a hardware programmer.


Turning a motor on and a led at the same time for a given time period I need help with this code, I want to have a motor turn on for a given time and at the same time have an led light up to indicate it is on which will also turn of once the motor has stopped. It is controlled by A TECT5000 SENSOR, which acts like a switch to transfer a signal to the motor and LED.

At the moment, I can get the motor to turn on and off for a given time but not the LED. Every time I activate the circuit with the sensor it turns on and stays on or turns of and stays of. Here is the current code I am using.

// Program: Led drive using reflective optical sensor
// Author: Arduino e Cia

int outgoingsignal = 8 ; // Pin of led
int pinsensor = 7 ;   // Connected to the "collector" pin of the optical sensor
int reading;      // Stores information about sensor reading
int statusled = 0 ;
int motorPin = 9;  // define the pin the motor is connected to
                   // (if you use pin 9,10,11 or 3you can also control speed)
                   // Stores led status (on / off)

void setup ()
{
  pinMode (outgoingsignal, OUTPUT); // Defines the led pin as
  pinMode (pinsensor, INPUT);   // Defines the sensor pin as input
   pinMode(motorPin, OUTPUT);
}

void loop ()
{
  // Le the sensor pin information
  reading = digitalRead (pinsensor);
  if (reading != 1 ) // Checks if the object was detected
  {
    while (digitalRead (pinsensor)!= 1)
    {
     delay (100);
    }

    statusled =! statusled;
    // Reverses the status of the led (on / off)

    // Turns on or off the led as "statusled"
    digitalWrite (outgoingsignal, statusled);
  motorOnThenOffWithSpeed(); }

}
void motorOnThenOffWithSpeed(){

  int onSpeed = 255;  // a number between 0 (stopped) and 255 (full speed)
  int onTime = 2500;  //the number of milliseconds for the motor to turn on for

  int offSpeed = 0;  // a number between 0 (stopped) and 255 (full speed)
  //int offTime = 1000; //the number of milliseconds for the motor to turn off for

  analogWrite(motorPin, onSpeed);   // turns the motor On
  delay(onTime);                    // waits for onTime milliseconds
  analogWrite(motorPin, offSpeed);  // turns the motor Off
 // delay(offTime);                   // waits for offTime milliseconds
}

If you just want the led on with the motor then put a couple of digitalWrite statements in your motorOnThenOffWithSpeed function to turn the led on and off at the same time you turn the motor on and off.


Calibrate Watchdog Timer Is there any good way to calibrate the watchdog timer? I'm trying to use it as a time source, even when asleep, but it's woefully inaccurate. Some simple testing showed it loosing 2 minutes every hour!

Not only is it uncalibrateable, but it's actually pretty rubbish (as you've discovered). If you check the datasheet you'll see that it can vary between about 109kHz and 119kHz, even though its nominal frequency is 128kHz.

With the ATmegaXX8(A/P) you can reconfigure the system to run its CPU off the internal RC oscillator and timer 2 from a crystal across TOSC1/TOSC2 (pins 9/10 [DIP] or 7/8 [TQFP]) by setting ASSR[6:5] to 0b01 and changing the CKSEL[3:0] fuse bits to 0b0010. Take careful note of the warning on AS2 in the datasheet though. If you want to use a watch crystal instead of prescaling the existing crystal on an Arduino board then you'll need some soldering skill as well.

If you need crystal accuracy for the CPU as well then you'll need to move up to an AVR family that has a separate asynchronous timer that can be supplied with a watch crystal, such as the ATmegaXX4(P) (Sanguino) or ATmegaXXX0 (Mega/Mega 2560).


Arduino Uno - Variables randomly changing So I have a circuit for a timer (I don't think it is the problem)

Sorry for it being a little messy.

And I have this code (probably the problem):

// LiquidCrystal - Version: Latest
#include <LiquidCrystal.h>

/*

*/

const int switchUnitButton = 9;
const int selectButton = 10;
const int startButton = 8;
const int stopButton = 7;
const int d4 = 5;
const int d5 = 4;
const int d6 = 3;
const int d7 = 2;
const int rs = 12;
const int en = 11;
String unit = "sec";
int unitCycle = 1;
int secCount = 0;
int minCount = 0;
int hourCount = 0;
int dayCount = 0;
int switchUnitState;
int prevUnitState;
int selectState;
int prevSelectState;
int startState;
int prevStartState;
int stopState;
int prevStopState;
LiquidCrystal lcd = LiquidCrystal(rs, en, d4, d5, d6, d7);

void setup() {
  Serial.begin(9600);
  pinMode(switchUnitButton, INPUT);
  pinMode(selectButton, INPUT);
  pinMode(startButton, INPUT);
  pinMode(stopButton, INPUT);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {

  switchUnitState = digitalRead(switchUnitButton);
  selectState = digitalRead(selectButton);
  startState = digitalRead(startButton);
  stopState = digitalRead(stopButton);

  if (switchUnitState == HIGH) {
    if (prevUnitState != switchUnitState) {
      if (unitCycle < 4) {
       unitCycle++;
      } else if (unitCycle == 4) {
       unitCycle = 1;
      }
    }
  }

  Serial.print(unitCycle + "\n");

  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

  lcd.setCursor(0, 0);
  lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));
  lcd.setCursor(0, 1);
  lcd.print("Hr: " + String(hourCount) + " Day: " + String(dayCount));

  prevUnitState = switchUnitState;
  prevSelectState = selectState;
  prevStartState = startState;
  prevStopState = stopState;
}

And sometimes without me clicking a button the unit value changes or sometimes when I click the selectButton for the amount to go up it changes which unit it is adding to. And sometimes the string has parts before it from other units like "inhour" what is happening?

You are seriously abusing the String class.  There is absolutely no need to use any Strings at all in your program.

For example:

  if (unitCycle == 1) {
    unit = "sec";
  } else if (unitCycle == 2) {
    unit = "min";
  } else if (unitCycle == 3) {
    unit = "hour";
  } else {
    unit = "day";
  }

  Serial.print(unit + "\n");

would be better written as:

  if (unitCycle == 1) {
    Serial.println(F("sec"));
  } else if (unitCycle == 2) {
    Serial.println(F("min"));
  } else if (unitCycle == 3) {
    Serial.println(F("hour"));
  } else {
    Serial.println(F("day"));
  }

And:

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unit == "day") {
        dayCount++;
      } else if (unit == "sec") {
        secCount++;
      } else if (unit == "hour") {
        hourCount++;
      } else if (unit == "min") {
        minCount++;
      }
    }
  }

as:

  if (selectState == HIGH) {
    if (prevSelectState != selectState) {
      if (unitCycle == 1) {
        secCount++;
      } else if (unitCycle == 2) {
        minCount++;
      } else if (unitCycle == 3) {
        hourCount++;
      } else {
        dayCount++;
      }
    }
  }

And then the cardinal sin:

lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));

All that string creation, concatenation, and destruction is just evil.  Instead, use:

lcd.print(F("Sec: "));
lcd.print(secCount);
lcd.print(F(" Min: "));
lcd.print(minCount);


What is difference between ATMEGA32 and ATMEGA328? I'm new in electronics. Just playing with Arduino boards.I just wanted to program ATMEGA328 micro-controller and use it without Arduino for compact design for my personal hobby project. I found there are ATMEGA32 and ATMEGA328 micro controllers in my local store. So, I wanted to know can I use ATMEGA32 instead of ATMEGA328 ? Which one is latest and whats are benefits. Thanks in advance.

I can't post comments.
One difference is that the ATmega32 has JTAG; ATmega328P has not.


How to connect the INT pin of a MPU 6050? I am using an Arduino Leonardo together with a GY-521 breakout board (like this one, schematic) for an MPU 6050.

I am currently trying to get the DMP Version of the examples from Mr Rowberg to work.

For all my tests, I use these connections:

GY-521 ->  Leonardo
VCC -> 5V (3.3V has the same behaviour)
SDA -> SDA
SCL -> SCL
GND -> GND

The "raw" sketch works fine, I can read out the sensor data. For the DMP version I think I need to connect the INT pin to pin 3 on the leonardo, to allow the MPU6050 to trigger an interrupt.

But as soon as I connect INT to anything (pins 0 through 3), the sketches do not find the MPU6050 any more. (They report ""MPU6050 connection failed").

Is my wiring off, or is my chip defective, and even more important, how could I figure that out on my own in the future? =)

Edit:
The example source code says

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

The example does nothing (that I can see) to configure this pin.

Edit again:

I've borrowed an oscilloscope. SDA and SCL sit on 3.3V during normal communication, and I can see packets being exchanged. As soon as I connect the INT pin to any input pin on my Leonardo, both SDA and SCL go to ground. This means nothing to me, but maybe to someone else.

Possible problem: pin interference

  But as soon as I connect INT to anything (pins 0 through 3), the
  sketches do not find the MPU6050 any more. (They report ""MPU6050
  connection failed").

  Is my wiring off, or is my chip defective, and even more important,
  how could I figure that out on my own in the future? =)

If I'm reading the Arduino Leonardo schematic correctly,
Arduino D0 is Rx, Arduino D1 is Tx,
Arduino D2 is the I2C_SDA, and Arduino D3 is the I2C_SCL.

You're already using the I2C_SDA and I2C_SCL as bidirectional I2C communication;
connecting some other output pin (such as the MPU6050 INT pin) to either of those pins is going to disrupt that communication and then things won't work.

On most Arduinos, Serial.println() and Serial.read() and the reprogramming process use the Rx and Tx pins.
Perhaps connecting the MPU6050 INT pin to either of those pins also causes some sort of problem leading to things that don't work.
(Although the Arduino Leonardo actually uses its USB_D- and USB_D+ pins for both Serial.println() and reprogramming, so maybe it isn't really a problem for the Leonardo?).
I would avoid using those pins for anything other than serial communication, even though I'm not at all sure that would actually cause a problem on the Arduino Leonardo.

  The example source code says
  ... this sketch depends on the MPU-6050's INT pin being connected to
  the Arduino's external interrupt #0 pin. ...
  The example does nothing (that I can see) to configure this pin.

I assume you're using https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_DMP6/MPU6050_DMP6.ino , right?

Interrupts are configured a little differently than I/O.
(In particular, "volatile" is critical to getting interrupts working right).

The part that configures that interrupt is in the setup() function:

void setup() {
    // ...

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
    // ...
}

The "attachInterrupt(0, dmpDataReady, RISING)" line
configures the interrupt vector table and the configuration bits so that when something drives Arduino pin D2 (i.e., external interrupt source 0) from a low to a high, no matter what the Arduino is in the middle of doing, the Arduino puts that on hold, executes the dmpDataReady() function, and then the Arduino resumes where it left off.

I don't see how that ever worked, since "external interrupt 0" comes from pin D2, which on the Arduino Leonardo is connected to I2C_SDA, which we're using for I2C communication, so we can't use it for watching the gyro interrupt pin.

However, since the "attachInterrupt()" gets run long after the "MPU6050 connection failed" message gets printed out on your screen, a software bug in how the example code uses attachInterrupt() doesn't explain why you get that "fail" message printed on your screen.

what to do about pin interference

I would try either using some other pin, or try getting it to work without hooking that pin to the Arduino at all.

Using some other pin

I would try to assign a dedicated pin on the Arduino to the MPU6050 INT pin.
Maybe D9 would work?

I'm guessing on the Arduino Leonardo, the interrupt should be set up something more like:

// warning: untested code.
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// connect MPU6050 interrupt to Arduino D9
#define MPU6050_INT D9

void setup(){
    // ...
    // pin change interrupt
    pinMode(MPU6050_INT, INPUT);
    PCintPort::attachInterrupt(MPU6050_INT, dmpDataReady, RISING);
    // ...
}

Getting it to work without hooking INT to the Arduino

It's not at all clear that the Arduino really needs to be connected to the MPU6050 INT pin.
It appears that another option is for the Arduino to occasionally use the I2C communication to read the status of the MPU6050, which includes the current state of that pin.
That simplifies the hardware -- simply leave the MPU6050 INT pin unconnected.


How to select arduino 101 in ubuntu? How to I select arduino 101? I  have ubuntu.

In that ancient version of the IDE? You don't.

You download and install the latest version of the IDE from the Arduino website, then use the Boards Manager to install the packages that include the Ardiuno 101.


Can I run 3 devices on Arduino Uno with different power sources? I'm pretty new to these types of projects I'd like to work on a greenhouse project with an Arduino Uno. The goal is to be able to sense temperature and control a heating lamp, detect humidity and control a humidifier, and connect a soil hydration sensor and connect a small water pump for irrigation.
Could the Uno support all of this power that could theoretically run at the same time? How would controlling the 3 isolated functions look in the Sketch?

Your question is 2 fold:

Power requirements: The actual power requirement depends on the devices, but the Arduino will certainly not be able to provide power for a heating lamp. It just cannot provide that much current (you would fry the Arduino). But the Arduino is also only powered from outside. I guess you have a power source, that can provide enough power for all the devices. Then you can connect these devices in parallel to the power source (meaning + and - of the heating lamp power goes directly to the power supply). That way the current for the devices doesn't flow through the Arduino. The Arduino will only use control signals, which don't have high current. Sensors are normally either analog sensors (which connect to the analog pins with only neglectable currents) or use communication interfaces, which are also ok. The current hungry output devices (humidifier and heat lamp) either have a digital control pin, a communication interface, or they must be controlled via a relay (depends on the actual devices).
Controlling all the devices: The Arduino can only do 1 thing at a time. But that is no problem, since you can do things sequentially very fast. For example write one function for every device, that you want to control. In that function you communicate with/control the device according to some variables (like the measured temperature). The loop() function can then look as simple as:

void loop(){
    measure_temperature();
    measure_humidity();
    measure_soil_hydration();
    control_humidifier();
    control_headlamp();
}

If you want to only do this periodically (not all the time), you can either add a delay() or - better - use millis() like in the BlinkWithoutDelay example (there are also many tutorials about millis() on the web). Make sure, that the individual functions are not blocking. They should do, what they need to do, and exit quickly. No long staying in loops or waiting for an event there.


Assign string to an array value I need to assign a string to an array value:

char mystr[3] = "Hello";

But when I run this code on arduino simulator: tinkercad.com, I get this error:

1:17: error: initializer-string for array of chars is too long [-fpermissive]

Why I'm getting this error?

You have asked the compiler to allocate 3 char of memory, and then you ask it to fill that memory with 6 bytes of data (5 characters, plus null-char for termination.)


Long Distance Shift Register I am using a Mega to control some relay boards. I have a 16 relay board near the mega, and I want to put an 8 relay board about 40 ft. away. So I figured I could use a shift register - instead of running 9 wires (8 relays and gnd) I could just run 4 (gnd, latch, clock, and data). I had some cat5e cable so I ran that from the Mega to the shift register. (I have an external 5V power supply so that does not come from the mega).

Problem is that is works, but inconsistently. I wrote a test program to turn on the relays in sequence. Sometimes it goes in order as it should but other times it skips relays or goes out of order.

I think there might be 4 sources of the problem:

1  The cat5e cable is too thin. Would a bigger wire help? Will twisting one pair together and using it like it was one wire help?

2 The shift_out code timing is off. I tried inserting some delay statments and that seemed to help a little. But I'm not sure where to insert them.

 void shift_out() {
     DigitalWrite(latch_pin, LOW);
     for (i = 0; i < 8; i++)  {
         DigitalWrite(data_pin, !!(bits & (1 << i)));
         DigitalWrite(clock_pin, HIGH);
         DigitalWrite(clock_pin, LOW);
     }
     DigitalWrite(latch_pin, HIGH);
 }

DigitalWrite is my own function that manipulates the PORTn bits instead of using Arduino's digitalWrite().

3 The shift register is very close to some 110V wires. Maybe interference?

4 The 5V power supply isn't powerful enough to power the relay board and the shift register?

Any suggestions welcome.

Edit: here's a pic of what I've built. The Cat5 cable runs directly back to the Arduino.

SPI is supposed to be used for things in close proximity to each other. See Wikipedia - Serial Peripheral Interface Bus.

  The Serial Peripheral Interface (SPI) bus is a synchronous serial communication interface specification used for short distance communication, primarily in embedded systems.

(My emphasis).

At that distance, and at standard SPI speeds you are probably losing signal integrity. The default SPI speed is system clock divided by 4 (that is, 4 MHz). It's not surprising some bits go missing after 40 feet.

See my page about SPI - you can use SPI to transfer to a 595 register (as described here).

(I'm assuming you are talking about a 74HC595 shift register)

I suggest running at a somewhat lower speed - insert delays after toggling the clock pin (each way). Or use the SPI hardware at (say) SPI_CLOCK_DIV128.

  The shift register is very close to some 110V wires. Maybe interference

You might also want to look at a balanced line driver (eg. RS485) - I have a page describing that.

  The 5V power supply isn't powerful enough to power the relay board and the shift register?

The register won't take much power. I trust the relays are solid-state ones and not coils that you are directly driving from the 595 chip?

Also see How do you use SPI on an Arduino?


Plant irrigation system I'm very new to the Arduino game I wanted to make a small auto watering system for my plants. I bought these items

5V 1 CHANNEL RELAY MODULE FOR ARDUINO PIC AVR DSP ARMB
9 VOLT BATTERY SNAP CONNECTOR B
ARDUINO UNO R3
CAMELION 9V BATTERY SUPER HEAVY DUTY
PIN TO HOLE DUPONT 40 PIN 30CM ARDUINO JUMPER WIRE 12 INCH
SOIL MOISTURE METER FOR ARDUINO.

I followed a video on youtube I attached the guys circuit diagram as well. After following instructions my pump wont turn on I also programmed it as well. Please help if anyone can show me how to rewire the device and codes or if I'm doing something wrong. Please help.

int Relay = 13;
int sensor = 8;
int val;
void setup() {
  pinMode(13,OUTPUT); //Set pin 13 as OUTPUT pin, to send signal to relay
  pinMode(8,INPUT); //Set pin 8 as input pin, to receive data from Soil moisture sensor.
}

void loop() {
  val = digitalRead(8);
  if(val == LOW)
  {
    digitalWrite(13,LOW); //if soil moisture sensor provides LOW value send LOW value to relay
  }
  else
  {
    digitalWrite(13,HIGH); //if soil moisture sensor provides HIGH value send HIGH value to relay
  }
  delay(400);
}

I've seen so much fake projects from "Viral science". I'm not sure whether he/she simply don't know what he/she does or if he/she simply tries to trap people. This project is a race condition itself ;-).

Besides your battery is empty. I don't think it is a big problem to use a 9V block battery, but Gerben is right, it won't do its job for very long. Have you thought about using a LiPo or LiOn Accu and a Solar loader?

There are worse things I see:

The sensor is powered by 3.3V but you read the ON/OFF signal with a 5-Volt Pin. That could be a problem, if there are other voltage drops that lead to a signal the PIN can not recognize as HIGH. Check the documentation of the moisture sensor and if it allows 5V use 5V to power it. All sensors I have found on Google have at least a range from 3.3 Volt to 5 Volt.

Check the current consumption of the relay. It must not draw more current than the Arduino PIN can provide (40mA for the UNO). And, don't use PIN13 to switch the relay. There are so many others and PIN 13 is connected to the onboard LED, which draws 10 - 20 mA on its own.


Yikes! Invalid device signature. Fail to burn bootloader and read fuses I know this problem is kinda common but I had to post it anyway.

Before anything, I would like to inform you guys that I changed the fuse of my Arduino Pro 3v3 @ 8MHz to allow 1.8 V brownout and also programmed CKDIV8 AND CLKOUT. In other words, the fuse configuration is this: E:FE, H:DA, L:3F.

The programmer is the Arduino 2009 running as ISP programmer. The target is Arduino Pro Mini 3V3 @ 8Mhz.

I also used a 0.1uF cap between reset and ground in the Arduino programmer.

After a good time using the Arduino Pro without problems, some random problems began to appear when I tried to upload a program with the programmer (Arduino as ISP). So I tried to burn the bootloader again and the following message appeared ""avrdude: Yikes! Invalid device signature."

The same occurs when I try to communicate with avrdude using this command "avrdude -c arduino -p m328p -P COM3 -b 19200 -v".

Some tests I did:

Continuity test directly at uC pins between those signals: SCK, MISO, MOSI, (/SS - /RESET). No problem good connection.
Verified the clock in XTAL1 and XTAL2. No problem 8MHz.
Verified the clock in CKOUT (Arduino Pro pin 2) and measured 1MHz.
I also tried to delay the avrdude using -B5, B10 and another values. With a quick search on Google some people are saying that those delays don't work with the Arduino as ISP.
I used some sketches for slow clocks, which I don't remember, and no luck.
External power and no luck again.

What am I missing? Do I need to change something to communicate with Arduino Pro running at 1MHz?

If you are burning the bootloader through the IDE it won't expect the CKDIV8 fuse to be set.

I have a bootloader programmer which you could use to reprogram the bootloader. You just need another Arduino (eg. Uno, Mega) and connect 6 wires between each of them like this:

The sketch for programming the bootloader is available on Github:

https://github.com/nickgammon/arduino_sketches

You want the one in the "Atmega_Board_Programmer" subdirectory.


Is there an Arduino Simulator or Emulator that runs on OS X? Is there an Arduino Simulator or Emulator or cross-compiler to native Mac executable that runs directly under Mac OS X, and does NOT require a Windows or Linux VM or an active internet connection for running in the cloud?

There are previous questions here on similar topics, but they do not seem to address exactly this particular use case subset.

I am using the Wokwi Arduino simulator for a long time. It runs on all three platforms. Mobile, Windows OS, and macOS.
I have checked the working of the simulator in both Android and iPhone. Both give a good performance as well.


RGB Led strip pot control burned my arduino? I made this exact build on my Arduino, with the following differences:

I'm using Arduino Nano
Transistors I use are 2N2222A
I'm running everything on 12V except Arduino, I use LM317 to feed Arduino 6v

Here's the build:

Here's what happened. First, it started to get strange voltage, arduino would light up even when disconnected from power. After that, Arduino kind of got fried, when I connect it to USB, nothing happens. I can give it 6v to VIN and ground it with the rest, but turning potentiometers only dims the onboard LED of the Arduino and that's it.

Now I'm going to go and pick up a new nano, however, I'd prefer not to fry that one, so figuring out why this one burned would be nice.

PS. The image shows RGB LED instead of RGB LED Strip because 123d doesn't have strip component.

First, as Majenko said, you need resistors between the arduino output pins and the transistor bases. Start at something like 330 Ohm.
Second, what is the value of the potentiometers? If it is too low you would be drawing too much current from the 5V pin to the ground.
Third, you should power the arduino with at least 7V, assuming you power it through the Vin pin or the power jack. 6V is considered too low.
I assume the pins connected to the potentiometers are initialised as inputs. Otherwise, it would be possible to burn your arduino by having them source/sink too much current (i.e. by turning the potentiometers to one end or the other).


EEPROM: managing address mapping between firmware versions Is there a common way to handle changes in the mapping between eeprom addresses and variables between firmware versions? It's not about the eeprom memory to survive the update, but to be(come) compatible with future sketches with a possibly different set of variables.

To make it clearer consider the following fictional scenario:

A coffee machine has been programmed to measure water_temperature and the firmware is supposed to stop heating within a temperature_hysteresis
 below set_temperature. set_temperature is a persistent parameter that has been individually optimized be the user and must therefore survive any firmware update. As a configuration parameter also temperature_hysteresis is stored in the eeprom.
Now the manufacturer decides to update his machine with a PID-controller, making the parameter temperature_hysteresis obsolete while he introduces some new parameters for the controller's gains (pid_gains). How can he manage that the firmware keeps values that haven't been touched by the update (like set_temperature) while the additional parameter pid_gains is added.

I assume that obsolete parameters should be removed as there could be more updates with new parameters in the future. That's why simply incrementing the eeprom address and ignoring deprecated addresses probably won't work.

On the other hand, when re-using old addresses I wonder how a fragmentation of the eeprom can be avoided.
I came up with the idea of putting all configuration data into a json in the eeprom and to handle the problem a layer above by parsing the json for configuration data. But anyhow, that feels so wrong and might be too complicate.

Does anyone have experience with this kind of problem and knows how this routine is commonly implemented?

There's lots of ways you could handle this.

Two thoughts right off the top of my head:

Have a "Version" identifier in the EEPROM.

The firmware then needs to know the EEPROM layout of all versions up to the current one. It can then read the EEPROM from the old version and write back a new format for the current version.

Have each entry in the EEPROM tagged with a "meaning".

This is not too different to your JSON idea (which you are right is horrible), but instead of lots of words you just use a simple number to identify the meaning of the value it is associated with.  Assuming that each stored value is an 8-bit byte (though it doesn't have to be), you could allocate "1" as "set_temperature", "2" as "temperature_hysteresis", "3" as "pid_gains", etc, Then the EEPROM might contain the bytes 1,96,2,5 and the firmware would know that the second byte is the set_temperature because it has a 1 in the first byte.

You can think of it as a "key / value" pair, but both the key and the value are just numbers.

To find the temperature_hysteresis you just scan through all the even EEPROM entries until you find 2, then read the next entry. If you don't find a 2 then you use the default value.

Your firmware can then choose to either update an existing cell that is tagged with the right type (scan for type, update next cell), or it could erase all the values and replace them with just the ones it cares about - the choice is yours.

Any values that your firmware no longer cares about will be ignored, and potentially erased.


Using Servo on Timer3 on a Leonardo I would like to use the Radiohead library and control a servo from the same Leonardo board.

Now the Radiohead library occupies timer1 and therefore cant be used together with the servo library. (It does offer to use timer2 which the Leonardo does not have.)

Are there any other Servo libraries that use timer3 or timer4 which the Leonardo has?

I have already tried:

https://github.com/nabontra/ServoTimer2  does not compile
https://www.pjrc.com/teensy/td_libs_TimerOne.html does not work (calling function blocks)

In file ServoTimers.hin standard Arduino Servo library change the timer

#elif defined(__AVR_ATmega32U4__)
#define _useTimer3
typedef enum { _timer3, _Nbr_16timers } timer16_Sequence_t;

on Windows the file ServoTimers.h is located in C:\Program Files (x86)\Arduino\libraries\Servo\src\avr


Waterproofing Arduino the project i'm working on is a weather station out door and for that i need to to give arduino at least some sort of protection from moisture.

https://www.instructables.com/id/Arduino-Weather-Station-AWS/

putting arduino in a box might work but the humidity where i live is very high it's rain a lot but the cold is not much. looking for ideas to waterproof arduino board please.

also can arduino work everyday of year without problem?

You can just solder everything you need to the Arduino (I would recommend using an Arduino Mini since it has no communication port) and coat it with Silicon Conformal Coating. It creates a silicon layer on top of the PCB that would not let any moisture through. Or you can just put it in a case and cover it with epoxy, that will be even more protection, but there will be no more access to the board unless you foresee it.


Using Arduino Uno as ISP to program Mega 2560 I'm trying to use Arduino Uno as ISP to program Arduino Mega 2560 using this Pin connections (Uno->Mega):

slave reset: 10:       ->        RESET on target

MOSI:        11:      ->           51

MISO:        12:      ->         50

SCK:         13:      ->        52

It runs perfectly when I "Burn Bootloader" from Arduino IDE and LED starts blinking on target. So I assume my pin connections are correct.

However, when I open the Blink example and perform "Upload Using Programmer" in Sketch tab after choosing "Arduino as ISP" in Tools>Programmer it uploads the code but LED on Mega doesn't blink.

I'm afraid that I have problem in my Mega Bootloader hex file and think it's not configuring Pin 13 as a LED pin. But in this case I shouldn't have seen the led blinking after burning the bootloader.

What am I missing here? I appreciate your help.
-Bex

Find the file called "boards.txt" located in your Arduino installation directory. In my case, the path is "arduino-1.6.5/hardware/arduino/avr/boards.txt". Open it with your favourite text editor and locate the ATMEGA2560 section. (not in notepad, it breaks the file format, notepad++ my choice)

in boards.txt

back-up the file incase you break it,
find the line :
mega.menu.cpu.atmega2560.bootloader.high_fuses=0xD8
and change it with :
mega.menu.cpu.atmega2560.bootloader.high_fuses=0xD9

Source : http://soc.ninja/documentation/programming-atmega2560-with-arduino-uno-or-mega/#rating-74


Using Arduino to show images in Serial Monitor Some time ago I came across a Vedic in which a person has hacked an optical mouse's camera and displayed the image in the Serial Monitors.
My question:
How to use Serial Monitor to display an image captured by the Arduino

Based on this guide, he doesn't actually display the images on the serial monitor, only the image data for each pixel.

Then another program (Javascript and some HTML) on the PC side collects the data and converts it to a greyscale image.


Unexpected behavior of ++myCount I'm new to Arduino and C.
This behavior is not what I'd expect:

Serial.begin(9600);
while ( ! Serial );

int myCount = 0;

for (int i=0; i<10; i++) {
    myCount = min( ++myCount, 8 );
    Serial.print( myCount );
    Serial.print( "  " );
}

I would expect:

1  2  3  4  5  6  7  8  8  8

But I get:

2  4  6  8  8  8  8  8  8  8

Why is my code counting by 2?

Jaromanda X is indeed correct - min() is defined on line 92 of Arduino.h, thusly:

#define min(a,b) ((a)<(b)?(a):(b))

Therefore when the ++mycount is substituted for the a, it is in fact substituted twice, in both the (a)<(b) and the (a):(b), leading to the increment by 2, each time min(++mycount,8) is executed.

As VE7JRO mentions, as it is defined in this way, the reference for min(x,y) states:

  Warning

  Because of the way the min() function is implemented, avoid using
  other functions inside the brackets, it may lead to incorrect results

min(a++, 100);   // avoid this - yields incorrect results

min(a, 100);
a++;            // use this instead - keep other math outside the function

As the second example states, keep any incrementing outside of the min() macro.

Alternatively, I think that you could use the inline function to workaround this issue:

#undef min
inline int min(int a,int b) {return ((a)<(b)?(a):(b)); }

Because inline provides a real function call (with parameters) it avoids the use of macros and substitution, which gives rise to the issue that you encountered.

inline is a much better (safer) way to implement the functionality provided by macros, in many cases. For more information, see Inline functions in C++ or read a C++ reference.


Is my atmega2560 schematic correct? I'm designing a custom board with an atmega2560. It will be programmed using ArduinoISP. I want to be sure that i have made no mistakes on my schematic design before I order it. I folloud the schematic for the arduino mega 2560 from the arduino website. For the basic function of uploading a sketch is my design correct?

I can upload the full schematic on pdf if you need it but it just contains some ICs for the final board.

This is the pcb design as asked in the comments!

for the basic function of uploading a sketch your board schematics is indeed correct and going to work.
I can't say much on the PCB as what you have posted is a partial design, in particular it doesn't show the solder mask expansion and other details which might greatly influence the final result.

Please also note you don't need a reset button, a voltage regulator nor an external oscillator for the basic function of uploading a sketch, but I believe you also want to have the ability to run the sketch without the programmer being attached...


Dagu Mini Driver Board Issues I have the Dagu Mini Driver board which is based on the atmega8 and I uploaded the code here. It uploaded perfectly and I wired 4x AA pack to the battery terminals making sure to observe polarity.

I then attached two DC motors to the ML and MR pins just like it said in the picture. I turned the board on, making sure the switch was set to on also.

The red light lighted up and the blue light flickered for a second. The motors did not move. I tried different motors. To check if it was a corrupt bootloader I tried to upload the hello world blink sketch. That worked perfectly.

I got my multi-meter out and tested the wires I was using...all good! Tested the battery...6.31v! That's within specs. I have the jumpers correctly inserted on the D7 - 10 pins. Here's my setup:

What in the world could be wrong? The code is supposed to make it turn in a rough square. I checked it over and over and it looks right. Any ideas?

This is a generic debugging advice, but maybe it can still be of help:
have you tried driving the led from the loop, to check that it doesn't get stuck for some reason?

Other thing you could do is to get the datasheet of the motor driver, find out the inputs from the ATMega and see how they look like.
At least that would allow you to bisect the problem answering the question:
"Does the ATMega generate the expected signal?"


How to use analogWrite() on multiple pins at the same time? I would like to do,

analogWrite(100,3);
 analogWrite(200,6);

at the same time. But the problem is that only the led on pin 3 lights up. I want both to light up at the same time. I've heard about direct port manipulation, but I can only find an alternate for digitalWrite() but I couldn't find one for analogWrite(). Can someone please help me with just a simple example on just how to do the above operation?

I'm using arduino uno.

You have your parameters the wrong way round:

analogWrite(2, 100);
analogWrite(6, 200);

However: pin 2 on the Uno cannot do PWM, so you will have to pick a different pin. Look for the pins marked with ~ - they are the PWM pins. On the Uno that is pins 3, 5, 6, 9, 10 and 11.


What is the simplest way to "ask" the arduino which input pins are HIGH? I am trying to build a 36-line cable tester, using the Digistump DigiX (99 i/o pins). Digital pins 0-35 are outputs, connected via the cable in question, to (in a perfect world) digital input pins 36-72. The plan is to have 36 neopixels (to conserve DigiX pins), one corresponding to each line in the cable. Currently they light up green for connection and red for no connection.

It's easy to check if output 0 goes to input 36, but there are more potential problems in a cable than no connection...

What if there is a short and output 0 goes to 36 and 42? It will still show up as correct when it tests 0 to 36... I somehow need to "ask" it what, if any, inputs (pins 36-72) are HIGH when only output 0 is HIGH.

I'm not sure how I'm going to display this extra data yet (Lcd maybe? Or maybe any pins shorted together all use a unique led color...), but I want to make sure the idea will work before I move on to that. Here is what I have working so far, just using a 3-line cable for now. And yes, I'm new to this. Any advice would be greatly appreciated!

#include <FastLED.h>
#define NUM_LEDS 3
#define LED_PIN 6
CRGB leds[NUM_LEDS];
#define brightness 25
int var = 0;

void setup() {
  for (int sendPins=0; sendPins <= 2; sendPins++) {
    pinMode(sendPins, OUTPUT); }

  for (int recPins=3; recPins <= 5; recPins++) {
    pinMode(recPins, INPUT); }

    FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
    FastLED.clear();
}

void loop() {
  while (var < 3) {    //so it only runs once for each line in the cable.
    var++;
  for (int sendPins=0; sendPins < 3; sendPins++) {
    digitalWrite(sendPins, HIGH);

    int recPins = map(sendPins, 0, 2, 3, 5);  //made more sense to me than another for loop.

     int recPin = digitalRead(recPins);
     if (recPin == HIGH)
     {
      leds[sendPins].g = brightness;
      leds[sendPins].r = 0;
      FastLED.show();
     }
     else
     {
      leds[sendPins].r = brightness;
      leds[sendPins].g = 0;
      FastLED.show();
     }

      digitalWrite(sendPins, LOW);
      delay(250);      //just for testing so i know it's going through them all.
  }
 }
}

There is a technique, which I used some 40 years ago to test for changes on a set of input pins. This can easily be configured to test serially.

Put a 1 on an output pin say 5. Create an integer e.g. 010000 with a 1 in the appropriate position. Read ALL inputs and XOR with the created integer. If one and only one input is 1 the resultant value will be 0. This is easy to implement in a loop just by shifting the 1 left each time.

The technique works if you can read all inputs into a integer. This was OK for our 32 bits, but could be extended.

It is probably easier to code than explain, but depends on what you have to do to read all inputs.


Can I set the Arduino board type in code When I've come back to Arduino programming after a spell doing other things, I keep forgetting that I last experimented with a different type of board and get a "avrdude: stk500_getsync(): not in sync: resp=0x00" error.

I have one sketch which will always be compiled and uploaded against a specific piece of hardware. Therefore, I would like to specify the board type and preferably COM port as well, in my sketch.

Can it be done?

No, it cannot. Neither the compiler invocation nor the subsequent upload examine the code for the hardware in use, so there is no way of doing what you are asking.

What you can do is to create entries in a new boards.txt and programmers.txt using an existing core that specify all the parameters, and all you would have to do is select them in the IDE for everything to be set at once. See Google Code/Arduino/Platforms for more information.


Arduino Editor: Monitor menu show "Serial port unavailable" Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz)
I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".

$ dmesg | grep tty
[    0.000000] console [tty0] enabled

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command    dmesg | grep FTDI, but no any output returned.

$ ls -l /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?

type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.

Now remove (hmm. easier if you do that before typing the command above).  and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.

With a bit of luck you'll see something like:
   Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341
   Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0
What comes after "now attached to" is what you need to use for the serial port....


Continuous push button detection in for Stepper control Currently, I've worked on code for controlling stepper motor with pushbuttons. So, basically, I have to press two push button to run forward and backwards.
but the problem is when I press the 1st pushbutton it detects that pushbutton and run motor CW or CCW,  That means it cannot detect the press of another pushbutton to make it counterclockwise.
I realize that the program isn't detecting the second push button after pressing 1st one.
Tried different options to make it work. but failed.
any suggestions?
Here's my code for reference:-

#include <AccelStepper.h>

const int button1Pin = A2 ;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
   pinMode(button1Pin, INPUT);
   pinMode(button2Pin, INPUT);

   Serial.begin(9600);
}

void loop()
{

      int sensorReading = analogRead(A0);
      int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
      button1State = digitalRead(button1Pin);
      button2State = digitalRead(button2Pin);

     stepper.setMaxSpeed(2000);
     stepper.setSpeed(motorSpeed);

     if (button1State == HIGH)
       {

        stepper.setSpeed(motorSpeed);
        Serial.print("ok");
        stepper.runSpeed();

       }

  if (button2State == HIGH)
       {

        Serial.print("ok2");
        stepper.setSpeed(-motorSpeed);
        stepper.runSpeed();

      }
}

Another problem is in this current code, it cannot detect the potentiometer input inside the if ( button state ) {} loop.
it would be a great help pointing out my mistakes.

I implemented your code here on a UNO using 2 pushbuttons (with the stepper motor functions commented out) and it seems to work fine.  When I press button1 I get a lot of "ok" printouts for as long as the button is held down. When I press button2, the same thing happens except with "ok2" instead of "ok".
Here's the code I used:
/*
    Name:       TwoPushButtonTest.ino
    Created:    9/28/2020 2:36:07 PM
    Author:     FRANKNEWXPS15\Frank
*/

//#include <AccelStepper.h>

const int button1Pin = A2;
const int button2Pin = A1;

int button1State = 0;
int button2State = 0;

boolean flag1 = 0;
boolean flag2 = 0;

//AccelStepper stepper = AccelStepper(1, 8, 9);
void setup()
{
  pinMode(button1Pin, INPUT);
  pinMode(button2Pin, INPUT);

  Serial.begin(115200);
}

void loop()
{

  //int sensorReading = analogRead(A0);
  //int motorSpeed = map(sensorReading, 0, 1023, 500, 1000);
  button1State = digitalRead(button1Pin);
  button2State = digitalRead(button2Pin);

  //stepper.setMaxSpeed(2000);
  //stepper.setSpeed(motorSpeed);

  if (button1State == HIGH)
  {

    Serial.print("ok");
    //stepper.setSpeed(motorSpeed);
    //stepper.runSpeed();

  }

  if (button2State == HIGH)
  {

    Serial.print("ok2");
    //stepper.setSpeed(-motorSpeed);
    //stepper.runSpeed();

  }
}

and here's the wiring diagram:

Note the two 10K pull-down resistors.  If these are not present, then the A2/A3 inputs are indeterminate whenever the buttons are in the 'disconnected' state, and anything can happen.


Getting Push Button Logic To Stick? I'm trying to get a sensor to activate if a push button is clicked. And deactivate when a certain condition is met and reactivate when the push button is pressed again.

#include <SPI.h> // Included for SFE_LSM9DS0 library
#include <Wire.h>
#include <SFE_LSM9DS0.h>

#define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
#define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
// Create an instance of the LSM9DS0 library called `dof` the
// parameters for this constructor are:
// [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

const byte INT1XM = 4; // INT1XM tells us when accel data is ready
//const byte INT2XM = 8; // INT2XM tells us when mag data is ready
//const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
const int buttonPin = 15;     // the number of the pushbutton pin

int buttonState = 0;

double X;
double Y;
double Z;

void setup(){

  pinMode(INT1XM, INPUT);
  pinMode(buttonPin, INPUT);

  Serial.begin(9600);
  Serial1.begin(9600); // Start serial at 115200 bps
  // Use the begin() function to initialize the LSM9DS0 library.
  // You can either call it with no parameters (the easy way):

  uint16_t status = dof.begin();
  // Or call it with declarations for sensor scales and data rates:
  //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

  // begin() returns a 16-bit value which includes both the gyro and
  // accelerometers WHO_AM_I response. You can check this to make sure
  // communication was successful.
  // Serial.println(status, HEX);
  setODR();
}

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.

 // Serial.println(buttonState);

  if (buttonState == 1) {   //if push button is pressed

    printAccel(); //print sensor data

  }

}

void printAccel()
{
  // Only read from the accelerometer if the accel interrupts,
  // which means that new data is ready.
  if (digitalRead(INT1XM))
  {
    // Use the readAccel() function to get new data from the accel.
    // After calling this function, new values will be stored in
    // the ax, ay, and az variables.
    dof.readAccel();

    //Serial.print("A: ");

    // Using the calcAccel helper function, we can get the
    // accelerometer readings in g's.
    X=dof.calcAccel(dof.ax);
    Y=dof.calcAccel(dof.ay);
    Z=dof.calcAccel(dof.az);

    Serial.print(X);
    Serial.print(", ");
    Serial.print(Y);
    Serial.print(", ");
    Serial.println(Z);

    // Serial1.println(Z);

    fall(); //jump to check condition

  }
}

void setODR(){

  dof.setAccelODR(dof.A_ODR_25);
  dof.setAccelScale(dof.A_SCALE_16G);
}

void fall(){

  if(-0.08<X && X<0.08){
    if(-0.08<Y && Y<0.08){
      if(-0.08<Z && Z<0.08){

        Serial1.println("N");
        Serial.println("Fallen!");

        loop(); //if condition is met, jump to loop to wait for push button to be pressed again.

        }
      }
    }
  //else{

    printAccel(); //else continue printing sensor data

  //}
}

However I am having some trouble getting it to work, above is what I have worked out thus far.

You'll need to store whether the button has been pressed.

bool buttonActivated = false;

...

void loop(){

  buttonState = digitalRead(buttonPin); //Read push button logic.
  if (buttonState == 1 ) {
    buttonActivated = true;
  }

  if( buttonActivated ) {
    printAccel(); //print sensor data
  }

}

to deactivate, use:

buttonActivated = false;


LiPo + charge/boost circuit vs pre-built "power bank" - contrasting portable power sources Portable 5V power for my projects - I was about to get the necessary parts to wire up an OEM LiPo battery (3.7V battery, boost circuit, charging circuit) when I took a peak at pre-built "power banks".  From all the sources I see the LiPo batteries alone cost more than the power bank, at much lower capacity.  For reference:

a 10400 mAh power pack (max output 3A @ 5V) is 26$ on Amazon
a 10000 mAh power pack (max output 2.1A @ 5V) is 9$ on Hobby King
a 2500 mAh LiPo is 17$ on Amazon
a 5000 mAh Lipo is 8$ on Hobby King

The power packs already have charging and voltage regulation circuitry! The price difference makes me think I am missing something.

Reading around I notice issues with power packs auto-shutdown at low current draws. But other than this power packs seem cost optimal and technically equivalent - at least within the output amperage range of the power banks.

Questions:

Are there any technical differences in output voltage, lifetime, or otherwise I am missing here?
Are there any "surprises" I'm going to face by using a power pack?
Can you recommend a solid power pack that doesn't shut down at arduino level draws. (My app will draw 800mA @ 5V max, but during sleep, the draw of an Arduino Nano)

Thanks!

The thing to remember with power banks bought on places like eBay and Amazon is:

THEY LIE ABOUT THE CAPACITY

A typical power bank you would expect to get around 3600mAh from, even though it may say 10000mAh, 50000mAh, 1,000,000,000,000mAh, etc.

The only technical difference between rolling your own circuit and a power bank is the low-current switch-off that many (but not all) of them have.  That switch-off is fine if you are always drawing a good amount of current, but once your device goes to sleep and the current drops right down you'll find the power bank will switch off and your device will never wake up again.

However, with rolling your own system you know what you are getting. You know the capacity of your battery.

One further thing to consider: Do you really need 5V? The majority of electronics run from 3.3V nowadays, and the Arduino is no different. There are Arduino boards designed to run from 3.3V, and even 5V boards can be tweaked to run at 3.3V (albeit slower than normal).

So the ideal solution would be:

A single-cell Li-Poly / Li-Ion giving nominal 3.7V
A Li-Ion charger circuit
A low-dropout or switching regulator with max 400mV dropout.

And no boost circuit needed. Also, no logic level shifting when communicating with 3.3V devices.


Bad LCD? Bad microcontroller? Or what? So I recently bought an Arduino along with an LCD module and two extra ATmega328P-PU ICs. Yesterday it was working just fine then I disconnected everything and reconnected it and this happened.
What could possibly go wrong?
Setup:

with microcontroller that came with the board:

So i recently bought an arduino along with lcd module and 2 extra atmega328p-pu ,yesterday it was working just fine then i disconnect everything and reconnect it and this happen, what could possibly go wrong ?

I hope you understand how difficult it is for anyone to help with this type of question.

My quick answer is "follow the schematics and reconnect the wires correctly" and "double check all wires".

From the picture it looks like you need to adjust the LCD contrast and reduce the back-light. Please see typical schematics for this.

Another rule-of-thumb is to use wire colors in a meaningful way. For instance, black for GND, red for VCC, yellow for data, blue for control, green for clock, etc.

Cheers!


is using two UARTs wiser compared to I2C and UART with Arduino + Xbee + BNO055 Sensor Hardware

Arduino Nano
XBee Pro S1 (802.15.4) Modules
Adafruit BNO055 Absolute Orientation Sensor

Purpose

I want to send the Euler angles and Linear Acceleration angles to the a central XBee Coordinator (can be connected to a Computer or a Single Board Computer) every 100 ms

Since the BNO055 has SDA and SCL pins for I2C how will the performance of the Nano matter when sensor data is acquired from the BNO sensor and send to XBee module which will be connected to the Hardware Serial UART Port?

An interesting observation was that if one:

  Shorts the PS1 pin to 3.3V for the BNO055, the SDA and SCL will function as RX and TX pins for UART.
  source

In terms of interfacing, I can think of the Xbee now connected to the Hardware Serial Port and perhaps the BNO sensor will can be connected to the Nano via SoftwareSerial port. But will that serve any better purpose in terms of performance and data acquisition i.e. using two Asynchronous Serial Ports compared to one?

All software serial solutions are much less efficient than HardwareSerial (i.e., Serial).  SoftwareSerial is particularly bad, because it disables interrupts for long periods of time.  95% of the MCU time can be spent twiddling its thumbs, waiting for each bit to come in.

Using the I2C interface for the BNO055 means that the Arduino hardware will independently and concurrently handle each byte of data from the BNO055 and from Serial (i.e., the XBee).  Your sketch can continue to do other things while each byte arrives.  This is most efficient.

Software serial port libraries handle each bit of data, sometimes to the exclusion of all other activity.


Control speed of linear actuator servo I have a linear actuator that I want to be able to slow down. Right now, the shaft moves too quickly. I'm not sure how to do this. I was looking into varSpeedServo.h library but couldn't implement it.

//Includes
#include <Servo.h>

//Defines
#define LINEARACTUATORPIN 9        //Linear Actuator Digital Pin

const int button1Pin = 4;     // the number of the pushbutton pin

// variables will change:
int button1State = 0;         // variable for reading the pushbutton status

Servo LINEARACTUATOR;  // create servo objects to control the linear actuator

int linearValue = 10000;   //current positional value being sent to the linear actuator.

void setup()
{
  //initialize servo/linear actuator objects
  LINEARACTUATOR.attach(LINEARACTUATORPIN, 1050, 2000);      // attaches/activates the linear actuator as a servo object

  // initialize the pushbutton pin as an input:
  pinMode(button1Pin, INPUT);

  //use the writeMicroseconds to set the linear actuators to their default positions
  LINEARACTUATOR.writeMicroseconds(linearValue);

}

void loop()
{

  // if the pushbutton is pressed set the linear value
  button1State = digitalRead(button1Pin);
  if (button1State == HIGH) {
    // set the position value
    delay(2000);
    linearValue = 1050;

  }

    if (button1State == LOW) {
    // set the position value
    linearValue = 2000;
  }

  //use the writeMicroseconds to set the actuator to the new position
  LINEARACTUATOR.writeMicroseconds(linearValue);
delay(3000);
}

Have you tried something like the following?

#define STEP 50

void loop()
{

  // if the pushbutton is pressed set the linear value
  button1State = digitalRead(button1Pin);
  if (button1State == HIGH) {
    // set the position value
    if (linearValue > 1050)
       linearValue = max(linearValue-STEP,1050) ;

  }

    if (button1State == LOW) {
    // set the position value
    if (linearValue < 2000)
       linearValue = min(linearValue+50,2000) ;
  }

  //use the writeMicroseconds to set the actuator to the new position
  LINEARACTUATOR.writeMicroseconds(linearValue);
  delay(100);
}

By changing the STEP value (or the delay in the next-to-last line) you can change the speed of the servo.


How do I use the additional serial ports on an Arduino UNO R3 clone? I bought this Arduino clone over eBay. It seems to have an extra SPI and serial ports. How do I use these?

Those are not additional I2C and UART ports, those are additional connectors connected to the normal peripherals. They are used in exactly the same manner as the normal connector.


Serial.parseInt value always goes back to 0 I am trying to read a value between 1000 and 2000 from my Serial Monitor and use it to drive some motors through ESC.

The code works when I use a potentiometer mapped for 1000-2000. I am now trying to use a Serial Monitor, but the "val" keeps going from the value I enter (between 1000 and 2000) and quickly returns to 0.

Why is this?

Here is the code for reference:

#include <Servo.h>//Using servo library to control ESC
Servo esc1; //Creating a servo class with name as esc1
Servo esc2; //Creating a servo class with name as esc2
Servo esc3; //Creating a servo class with name as esc3
Servo esc4; //Creating a servo class with name as esc4
void setup()
{
  esc1.attach(7); //Specify the esc signal pin,Here as D10
  esc2.attach(6); //Specify the esc signal pin,Here as D9
  esc3.attach(5); //Specify the esc signal pin,Here as D8
  esc4.attach(4); //Specify the esc signal pin,Here as D7
  esc1.writeMicroseconds(1000); //initialize the signal to 1000
  esc2.writeMicroseconds(1000); //initialize the signal to 1000
  esc3.writeMicroseconds(1000); //initialize the signal to 1000
  esc4.writeMicroseconds(1000); //initialize the signal to 1000
  Serial.begin(9600);
}
void loop()
{
  int val; //Creating a variable val
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while (Serial.available() > 0) {
    val = Serial.parseInt();
    Serial.println(val);
  }//Checks for a character in the serial monitor
  Serial.println(val);
  esc1.writeMicroseconds(val); //using val as the signal to esc
  esc2.writeMicroseconds(val); //using val as the signal to esc
  esc3.writeMicroseconds(val); //using val as the signal to esc
  esc4.writeMicroseconds(val); //using val as the signal to esc
}

This code will work IF you set the Serial Monitor to "No Line Ending" (OSX 10.6.8. IDE Version 1.0.6.2). parseInt() doesn't like the NL + CR chars.

unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){
    val = Serial.parseInt();
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

There is another way to get the integer value using this code:

char inputBuffer[16];
unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){

    // A function that reads characters from the serial port into a buffer.
    Serial.readBytes(inputBuffer, sizeof(inputBuffer));

    // Convert string to integer
    // cplusplus.com/reference/cstdlib/atoi/
    val = atoi(inputBuffer);

    // memset clears buffer and updates string length so strlen(inputBuffer) is accurate.
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

The Binary sketch size is 94 bytes less than the first example using parseInt. The second sketch will work with ANY Serial Monitor Line Ending settings.


Macbook Pro CH340 Nano 14201 error I'm using a MacBook Pro Mojave 10.14.6 to code genuine Arduinos. Been working with multiple Uno R3s, no issue. Got a genuine Nano and get the following error: ser_open(): can't open device "/dev/cu.usbmodem14201": No such file or directory

The USB cable I'm using works fine with a cheap Chinese Uno clone, so there are data pins in the cable.

I followed instructions to delete the kext file, rebooted, installed CH341SER_MAC file and rebooted. Still getting the error message. I notice that others have asked this question; where are the answers? Thanks in advance.

Timekeeping isn't exact with any of the boards, though .05% - just over 7 minutes/day - doesn't sound like too high an expectation.

Restarting when you connect it to your computer is by design and doesn't indicate a fault. Opening the IDE's terminal or connecting another terminal program to a connected and running Arduino will - and is supposed to - reset it. Here is a forum discussion on how to disable the auto-reset function (Uno-specific) if you want to. Note that it involves modifying the board.

It's quite possible that this one board has a fault, though it still could be the cable. A couple of swaps should confirm it one way or the other.

I'm still not clear on where the error message,

  ser_open(): can't open device "/dev/cu.usbmodem14201"

came from, but I'm guess it's from AVRdude, the uploader application on your Mac, and still I'm wondering if the correct port is selected in the IDE's Tools | Port menu? For some reason, a USB device called "cu.usbmodem14201" is expected but not found. Since neither the Mac nor the IDE inherently knows this name - a USB device announces its name when you connect it - could this selection be left over from having previously used the genuine Arduino? Another reason to check the Ports menu. Also note that the Ports menu doesn't update its list spontaneously - only when you open it (and maybe only when you open the top-level, Tools, menu; I don't remember exactly).

Update:

  The regular Arduino at 0.5% is pretty crude, I'd pay more for a more
  accurate crystal, but I was able to develop a sketch that adjusts for
  the Arduino's inaccuracy.

You could try putting the Arduino in an "oven" - and I emphasize the quotes. This is not a heating chamber per-se but a temperature controlled chamber. If you're getting good results by adjusting the count, adding the oven should get you even better results, especially as the seasons change and if that makes enough difference where you are.


Using the physical serial port on a BSFrance LoRa32u4? I can use the serial-over-USB channel by simply using Serial in my code.

The LoRa32u4 has an RXD1 and TXD1 pair on pins 20/21 (Arduino 0/1).

https://docs.bsfrance.fr/documentation/11296_LORA32U4/LoRa32u4_pinout_diagram.pdf

How do I configure and use this serial port (for receiving NMEA GPS)?

[ATmega32U4-based boards use] Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX). Serial is reserved for USB CDC communication. For more information, refer to the Leonardo getting started page and hardware page.


create a interruption-proof power I need to create a interruption-proof power for a project of mine, very similar to the design of this link.

My problem is that I need to adjust the current delivered of the solar panel (21V, 1.2A) to 5V and simultaneously charge a battery 12V, 18Ah. If the solar panel does not supply power, the battery takes its place.

Does anyone know any circuit to do something? Or can someone give me a light as do something?

Rough block diagrams below show two ways this can be achieved - "Easiest" costs least but is inefficient. "Better" uses PV panel output more efficiently. Details of either can be discussed if of interest.

'Schottky diodes' should be used to minimise losses.

(1) "Easiest"

Connect PV panel to battery with diode.
Panel is clamped to battery voltage (+ diode drop).
This will not hurt the PV panel but wastes some of the available power.
[What is the formal PV panel specification. Is it 21V O/C or loaded or .... Do you have a datasheet link for it?].

Use 12V (nominal) to 5V converter to power load.
This could be

A linear regulator - only about 40% efficient - very wasteful.
A buck converter (build or buy from eg ebay)

(2) "Better"

Use a buck regulator to charge the battery - ideally an MPPT (maximum power point transfer) controller. Details can be discussed if you are interested.

Use a second buck regulator to power the load. This must be capable of (at least) 11V to 22V input. Power this from a Schottky diode from the PV panel AND a Schottky diode from the battery. When the panel voltage is > battery voltage the panel will power the load.


Custom board with ATMega32u4 having USB issues I built a custom arduino based board (speciffically based off of Sparkfun's Pro Micro 3.3V 8Mhz and their Qduino mini boards) that uses the ATMega32u4-RC.

The board I built integrated an acceleromter (LSM6DS3) and a micro-SD card holder, and eleminated any uneeded GPIO. (This is basically a datalogger board for the LSM6DS3 accelerometer). It also inlcudes a usb-powered LIPO charging circuit, which is copied from the qduino mini.

A picture of the board I built,  with power LED indicating life.

The problem I am experiencing is that, after apparently sucessfull upload of the bootloader (I've tried the bootloader for the qduino mini, promicro 3.3v 8Mhz, even the Leonardo), my computer will not reconize the board. I've exauhsted all the information about driver installation from the sources for the boards my board is based on, and still can't make windows recognize my custom board.

Specifically, I've tried using a multitude of signed and unsigned drivers (on Windows 10 and 7), and can not get windows to pick anything other than usbfilt.sys as the driver.

Any advice would be greatly appreciated!

Edit: Added Eagle Schematic below

As Chris Stratton pointed out, I neglected to include the 1uF capacitor on UCap. This is absolutely necessary on a 3.3v board for the board to communicate with USB properly.

Thanks!


Running sensor input for given time, stopping, then running seperate scheduled relay output I've set up an Arduino Uno to run a pretty basic garden watering schedule, with the delay function.

I've now built a solar thermal water heater with a pump and tried running it separately through a 555 timer using a thermistor (33k Ohm approx). I couldn't get this running as the change in resistance with a water temperature rise to 30 deg or so wasn't enough to trip and untrip the 555 timer (thermistor at about 20 k at 20 deg, maybe 50k at 30 deg). (Any pointers to circuits that achieve this would be appreciated by the way.)

I've decided to try to run the solar thermal motor with my arduino set up as I have 2 relays free in a relay shield. My question is how I can run the sensor to start the solar thermal pump, then stop operating the solar thermal system and return to the garden watering code, then restart the sensor input, and so on. The issue is that my power supply is only 1 Amp, and running both systems at once might overheat it.

Hope this makes sense,
Brian

If you are just running the relays off the 1 Amp supply, and there aren't more than 6 relays they shouldn't draw more than an amp.(I will edit this statement if need be)
What you can do in the way of coding you can is to do a classic spinoff of using the millis() function.

//monitors temperature and schedules its operations
//RSM
#define TimeBetweenHydration 10000  //10 seconds
#define TimeBetweenThermal 1000  //1 second
#define Temperature_Thresh  25   //25°C

float temperature = 0.00;

unsigned long lastTempReadTime = 0;  //keep track of the time temperature was checked
//boolean MotorOn = false;  //state monitoring

unsigned long lastWaterTime = 0; //last time the system did something with the watering thing
//boolean Watering = false; //state monitoring

// other variables related to specifics
//…
//

void setup(){

//setup of analog inputs
//setup of digital pins

}

void loop(){

 unsigned long presentTime = millis();

if((presentTime - lastTempReadTime) > TimeBetweenThermal){
lastTempReadTime = presentTime;
 int inADC = analogRead(0);

  //do whatever conversion is needed to get a value of the temperature
temperature = inADC*3.14;

if(temperature > Temperature_Thresh){

//   if(!MotorOn){
     digtalWrite(RLY, HIGH); //turn on pump
//     MotorOn = true;
//  }
 }
  else{
  digitalWrite(RLY, LOW); //turn off pump
  }
}

   if((presentTime - lastWaterTime) > TimeBetweenHydration){
   lastWaterTime = presentTime;

//put your watering code stuff here

  }
}

If you want to make the pump run without a microcontroller you could use a comparator with the thermistor and use its output to switch a transistor. I do not have the 555 timer art skills.

T1 is you thermistor. You should use the values listed for R1 - R3. The transistor, coil and flyback diode are there to show how you should connect it up, the coil could be a motor or a relay to control the motor. The comparator changes around the 30-40Kohm mark.


What happens when you call malloc()/free()/new/delete? So I understand that generally speaking, dynamic allocation should be avoided. My question isn't how or why, but what happens when you call a function that allocates memory?
On Windows or Linux, when a program allocates memory, a whole bunch of stuff happens, things like virtualisation and security related features that have no relevance to arduino, and the bit that I'm interested in, memory management:
There will be some code, that will look at the alignment and size requirements of the allocation request, look at the pool of memory it has access to, find a space big enough, make a note of the allocation (which also uses some amount of memory) and then return a pointer to the allocated space back to the calling function.
Is there a custom malloc implementation for each device, or does it come with the arduino toolchain (and does that mean Arduino has a different implementation from Teensy, or avr from sam?), or is there some magical default implementation supplied by the compiler? What kind of memory overhead is incurred with every allocation? How easy is it to override this functionality and implement your own (out of morbid curiosity or tendency towards masochistic endeavours)?

There are some hardware-specific abstractions (they mostly define the maximum memory available), but otherwise these are functions are implemented by the C/C++ runtime (on arduinos an implementation called "NewLib") and usually "just work". You might want to take a look at this question, where quite a bit of background is given on the SAM implementation of the hardware abstractions (because it's broken).
And yes, of course using malloc/free has some considerable overhead, which is one reason why it's not the recommended way of allocating memory on microcontrollers. But the logic behind it is mostly the same whether there's 2k of memory or 2G. And the memory model of modern microcontrollers (at least the 32 bit ones) is very similar to the one seen in 32 bit Windows or Linux apps.


Do we have an alternative for millis() function? This is actually a follow up question to this question, so basically I'm using DS18B20 temperature sensor which requires Onewire.h library that interrupts millis() function.

Luckily i have a DS3231 RTC module which I'm using it with RTClib library, is there any way to use that module as a timer instead of millis() function?

You can use the SQW output of the module to indicate the passage of precisely 1 second. Every time it transitions from LOW to HIGH one second will have passed.

RTCs cannot give you times of higher resolution than 1 second, but they can give you that 1 second granularity to a high accuracy.


Corrupted characters with an OLED displaying thermocouple output I'm super new to Arduinos but I'm learning as I go. I'm in the first stages of a small temperature control project and so far I've been able to display the output of a MAX31855 thermocouple breakout board on 124x64 spi OLED through my Arduino micro.

My problem is that the characters of the temperature are corrupted looking. As I think I understand it, the temperature is changing while it's being written to the display therefore you get overlapping values. I've attached an image of the display.

I've tried making the temp output an integer but that didn't work.

Any input would be greatly appreciated as I'm just banging my head against the wall.

Here's my code:

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_MAX31855.h>
#include <U8glib.h>

//Constructor line for OLED

U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9, 8);  // D0=13, D1=11, CS=10, DC=9, Reset=8

// Default connection is using software SPI, but comment and uncomment one of
// the two examples below to switch between software SPI and hardware SPI:

// Example creating a thermocouple instance with software SPI on any three
// digital IO pins.
#define MAXDO   3
#define MAXCS   4
#define MAXCLK  5

// initialize the Thermocouple
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);

// Example creating a thermocouple instance with hardware SPI
// on a given CS pin.
//#define MAXCS   10
//Adafruit_MAX31855 thermocouple(MAXCS);

void draw() {
  double c = thermocouple.readCelsius();
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void setup(void) {

}

void loop() {

  // picture loop
  u8g.firstPage();
  do {

    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

The U8G2 library saves RAM by drawing the screen in smaller chunks (i.e., a "page").  Because you are taking a reading for each chunk, the temperature can change.  Just pull the reading out of draw and do it once in loop:

double c; // a global variable used in draw and loop

void draw() {
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void loop() {

  c = thermocouple.readCelsius(); // set the global variable once

  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}


FastLed (WS2812B) and IRRemote problem I am trying to control my WS2812B with a remote control. To archive this, I am using IRRemote library. The problem is that this two libraries doesn't work together.

I did some research and found out that it is a problem with timers.But, inside the IRRemote library file (boarddefs.h) there is a possibility to choose different timer (It uses TIMER2 as default, so I supposed that FastLed uses also Timer2).

So when I change the timer in boarddefs.h file to TIMER1, it is also now working fine for me. I keep recieving random IR codes. When I stop using FastLed library, I recive correct codes.

Some workaround to this problem is to read IR signal only once irrecv is idle:

  while (!irrecv.isIdle());  // if not idle, wait till complete
  if (irrecv.decode(&results)) {
     ...
  }

It makes around 80% of readings correct.

I am using arduino NANO clone. My question is, if there is any way to use IRRemote and FastLed libraries together other than using two arduino NANO (use one to read IR and other to control LEDs)?

The WS2812B chips are highly timing-dependent. You have to clock out bits within a range of ±150 ns. This isn't likely to work well with clocking in bits from an IR remote. You are finding errors on the IR codes - that doesn't surprise me.

I suggest you use your idea of two Nanos. One can be reading IR codes. The other can display a stream of pixels and then "ask" the other one (eg. via serial or I2C) if a different command has arrived. That way the timing can be shifted in such a way that both processors are not interrupted when they are busy.


GPS Short distance calculations, accuracy limitations for 1-30 meter distance I am a total beginner in the field of GPS, and this is actually my first post.

But, I have been looking into some of your questions, and especially the ones for short distance calculations, and time calculation used to measure traveled distance.

I want to measure distances from one coordinate to another with distances varying from typically 1-30 meters with an accuracy of 0.5 percent. Is it possible, and how can it be done? Or what is possible?

Thanks in advance

Update:

I want to create a small unit to measure short distances as mentioned above. So to be more specific, it will have a digital display and measure the distance from a coordinate 1. (0,0,0), to coordinate 2. for example 10 meters away. I will choose the location for the coordinates pressing a button on the unit, and the distance will show on the screen in meters and centimeters.

So for the accuracy, I actually believe that 2 percent accuracy is enough in the range between 1-30 m.

I am open for all types of measurement methods.

Take a look into Differential GPS, 10cm accuracy

Differential Global Positioning Systems (DGPS) are enhancements to the Global Positioning System (GPS) which provide improved location accuracy, in the range of operations of each system, from the 15-meter nominal GPS accuracy to about 10 cm in case of the best implementations.
Each DGPS uses a network of fixed ground-based reference stations to broadcast the difference between the positions indicated by the GPS satellite system and known fixed positions. These stations broadcast the difference between the measured satellite pseudoranges and actual (internally computed) pseudoranges, and receiver stations may correct their pseudoranges by the same amount. The digital correction signal is typically broadcast locally over ground-based transmitters of shorter range.
The United States Coast Guard (USCG) and the Canadian Coast Guard (CCG) each run DGPS systems in the United States and Canada on longwave radio frequencies between 285 kHz and 325 kHz near major waterways and harbors. The USCG's DGPS system has been named NDGPS (Nationwide DGPS) and is now jointly administered by the Coast Guard and the U.S. Department of Transportation’s Federal Highway Administration. It consists of broadcast sites located throughout the inland and coastal portions of the United States including Alaska, Hawaii and Puerto Rico.[1] Other countries have their own DGPS system.

https://en.wikipedia.org/wiki/Differential_GPS


Powering USB cable that powers Arduino with regulated 5V I am having an issue with external loads causing the computer I have my Arduino connected to to momentarily drop out, which causes the Arduino to lose USB power momentarily and the port drops out and won't reconnect unless I physically remove and reconnect the USB cable. Since I need the USB connected in order to send and receive serial data to/from the Arduino, I was wondering if I could physically open the USB cable, cut the 5V line, and supply it via and external regulated 5V supply. I wouldn't cut the ground wire, but would tie it to the external 5V supply. I have read conflicting information on this (something about handshaking) but was wondering if that applied to Arduino's specifically.

I solved this problem by using a laptop instead. It is immune to these power fluctuations


I'm trying to control a servo with a push of a button but its not working HELP I'm new to Arduino and I'm following this tutorial: https://www.youtube.com/watch?v=T2HMJiy9b_I   but the problem is the servo just keeps moving back and forwards on it own and the button is doing nothing when pressed please help.

Code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =90;    // initial angle  for servo
int angleStep =5;
const int minAngle = 50;
const int maxAngle = 110;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Robojax Servo Button ");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }

}

This condition below is never met because a boolean comparison is implied :

if( buttonPushed ){

and buttonPushed is declared as :

int buttonPushed =0;

A proper comparison should be OK :

if( buttonPushed == 1)
{
   // Do something
}

Also the buttons need proper debouncing or the push event will have undetectable results :

https://dduino.blogspot.com/2012/03/arduino-button-debouncing.html


Measuring lenght of time light levels peak using photoresistor I'm trying to measure shutter speeds on old cameras. This essentially consists of:

Shining a torch at one end of the camera
putting the photoresistor at the other end
trigger the shutter which temporarily lets in the light from the torch (boosting the photoresistor values temporarily)
Recording the duration of the increased spike in light levels

What I have currently records light levels but the variation is massive and typically incorrect in that they change depending on how close the torch is to the shutter and typically records values between 400 and 900 ms which is far too long (should be about 50ms).

This is the key code I have so far:

if (shutterbot.opened())
{
    /* Measure length of time it is opened until closure */
    unsigned long previousMillis = millis();

    while(true)
    {
        unsigned long currentMillis = millis();
        unsigned long time_elapsed = currentMillis - previousMillis;

        if (shutterbot.closed())
        {
            finished = true;
            /* Report back to user */
            Serial.println("Shutter speed is: ");
            Serial.println(time_elapsed);
            break;
        }
    }

}

The open and close methods in the shutterbot class are:

/* If light is 10% higher, set it to start recording */
int Shutterbot::opened()
{
    if (light_level() > 400)
    {
    return true;
    }
    else
    {
    return false;
    }
}

/*
  If light drops to below 10% higher, set it to stop
  recording
 */
 int Shutterbot::closed()
 {
     if (light_level() < 400)
     {
     return true;
     }
     else
     {
     return false;
     }
}

The full project code is here and just needs a photoresistor module and an arduino uno to test. I'm not sure I've provided enough information so if there are any questions, please let me know. Any help is greatly appreciated and thanks for reading.

It is unlikely a photo resistor can be used to time an event with sub second granularity.  This is because the electrons in such a device have many conductive states which they migrate into when exposed to light and out of when left in the dark.  It takes time for the electrons to drift into and out of these conductive bands.  In some cases it may take a good portion of a second. As described in the 2nd paragraph in the Design Considerations section of the above wikipedia page:

  Photoresistors also exhibit a certain degree of latency between
  exposure to light and the subsequent decrease in resistance, usually
  around 10 milliseconds. The lag time when going from lit to dark
  environments is even greater, often as long as one second. This
  property makes them unsuitable for sensing rapidly flashing lights,
  but is sometimes used to smooth the response of audio signal
  compression.


Arduino Yun & nRF24L01+ -> Linino crashing I'm trying to hook up a nRF24L01+ wireless transmitter to an Arduino Yun Mini on SPI, but I'm having a hard time. After a few minutes Linino crashes and becomes completetly inaccessible - until I upload a new sketch to the Arduino.

I connected the SPI pins (MOSI, MISO and SCK) to the corrensponding pins of the Yun. I connected CE to pin 3 and CSN to pin 2. I'm using the RF24 library found here: https://github.com/TMRh20/RF24

The following little code is enough to make Linino crash:

#include <SPI.h>
#include "RF24.h"

RF24 radio(3,2);

void setup() {
  radio.begin();
}

void loop() {

}

What am I doing wrong here? Any ideas? Any help is greatly appreciated!

I finally managed to get it running. It really seems to be a problem with radio interference. I failed to hook up an external WLAN antenna to the Arduino Yun mini but I found a very useful workaround with a usb adapter here:
http://www.lucadentella.it/en/2014/11/08/yun-adattatore-wifi-usb/

This workaround is possible with an Arduino Yun mini as well but you'll need the Arduino Yun Linux OS from here:
https://www.arduino.cc/en/Main/Software

because the necessary packages are not available for the Linino system that comes with the Yun mini. Then, you can connect the WiFi adapter to USB+, USB-, 5V and GND of the Yun mini and you're good to go.


How do I install Arduino drivers? I need to install my Arduino drivers, but Windows 8.1 doesn't seem to like Arduino, and it greys out the update driver button. Therefore I can't select the drivers from the drivers folder in my Arduino IDE folder.

There are drivers that need to be installed. But Windows 8.1 greys out the update driver software button. Also, it refers to Arduino Uno as an unknown device. How do I install the Arduino drivers and make Windows let me install the drivers?

The IDE package usually ships with the driver(at-least the latest one).
Go to Program Files in C: and find the Arduino folder and you should find a folder named Drivers. Inside you will find an application named dpinst-x86. Run it and you should be good to go!


AT firmware upgrade in ESP-01 using Arduino UNO R3 I need to upgrade the AT firmware in ESP-01 by using Arduino UNO R3 serial interface. Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware? Does it going to affect Arduino Bootloader?

Do I need to remove the Microcontroller Chip from the DIP socket before burning firmware?

No, just connect RESET to GND to stop the MCU from running.

Does it going to affect Arduino Bootloader?

No.