Problems burning bootloader on custom ATMEGA2560 board for High-powered model rocketry I've designed a custom board meant for high-powered model rocket telemetry & duel-deployment.  (More info upon request)

To do this, I've soldered a ATMEGA2560 (yes, overkill, but I needed multiple hardware serials), with the plan on using the ICSP programming header I designed on the board to burn the Arduino bootloader, and then use the super-easy ftdi-compatible serial connector to program the board....

Problem is, I have thus far been completely unable to burn the bootloader.  I've double-checked the wiring ten times, checked the labeling on my board, checked my board's schematic twice, and re-checked the chip's datasheet to make sure I didn't screw up the pinout, even held a jumper past my fancy reset circuitry that I largely copied from the official Uno schematic.

I've largely been using Nick Gammon's excellent "bootloader programmer" sketch Link on a Clone Arduino Mega.  But I've tested the connections and sketch by using it to program the bootloader on a Arduino Pro Mini successfully with no hitch at all.  :(

Attempting to enter ICSP programming mode..........................................
Failed to enter programming mode. Double-check wiring!

Here's a Board and (Schematic I can't post because I'[m new to the Arduino side of stack overflow...  so replace the URL with schematic.png) of my board, and I'll upload a picture of my soldered board soon, but I'm actually quite confident of my soldering job...

Really just completely out of ideas, and very demoralized because the project I've been working on for months isn't working, and I have nothing specific to even point at...

I have thus far been completely unable to burn the bootloader.

In what sense? What (error) messages did you get?

In your shoes I would be seeing if I can "talk" to the chip. My chip detector sketch will help you to see if the chip is "alive" or not. See my post about Have I bricked my Arduino Uno? Problems with uploading to board

You may possibly have inappropriate fuse settings for your clock source. If you get some sort of response from the chip using the chip detector sketch please post what it is.

  Also to note is that this is a completely virgin chip from the manufacturer, so I'm not sure what the clock settings come as in that case

According to the datasheet, 8 MHz internal oscillator with CKDIV8 fuse set. That should work.

However you need to resolve that before going any further. I would be taking voltage readings at various points.

Make sure you have Vcc at all the appropriate places, and Gnd.
Note that there are multiple Gnd and Vcc pins. You should also have 5V at AVcc.
Check that /RESET is normally high (5V) and check that it drops to 0V during the programming attempt (and stays there).
Check you have decoupling capacitors between Vcc and Gnd where necessary.
Assuming you have the TQFP-pinout chip, make sure that you have your SPI connections at pins 19, 20, 21 and 22.
If you have a scope or logic analyser make sure that there is some "action" on SCK, MOSI pins during attempts to program it. There should also be a response on MISO.
There should not be a capacitor in series with /RESET as I have occasionally seen people do. The programmer has to hold /RESET low during the entire programming sequence.


How has Arduino been used in the classroom? I remember seeing Primo, this robot that is based on Arduino and serves to teach kids to program. My interest in the platform comes from there, but it is always nice to learn about other cool applications.

What other applications are there that utilise Arduino for K-12 education?

I've used Sparki from Arcbotics as a robotics platform. It's uses Arduino Sketch to program and a modified Arduino IDE.

Sensors for line following , edge detection, distance and light level sensing are built in. Also the creators are focused on education so the material and projects are teaching oriented.

The Community seems pretty active and engaged too so the material should build over time.


How to break connection HM10 Bluetooth? I have 2 HM10 Bluetooth modules connected to 2 Arduino Teensy running the following code.

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  // If the baudrate of the HM-10 module has been updated,
  // you may need to change 9600 by another value
  // Once you have found the correct baudrate,
  // you can update it using AT+BAUDx command
  // e.g. AT+BAUD0 for 9600 bauds
}

void loop() {
  char c;
  if (Serial.available()) {
    c = Serial.read();
    Serial1.println(c);
  }
  if (Serial1.available()) {
    c = Serial1.read();
    Serial.print(c);
  }
}

By pairing them using the AT commands I was able to send messages back and forth by writing to Serial1. However now when I try to send AT commands it will just send the string to the other module instead of replying OK etc. How do I break the connection and make the AT commands work again?

The tutorial I used to pair the modules.

I was able to break the connection with:
AT

The data sheet says to use AT+PWRM1, but it didn't work for me. Instead the above command dropped the connection to the remote device.

From the Datasheet:

Execute “AT+PWRM1” command, Module will auto into sleep mode when
power on or disconnect from remote device.


Simulate motor encoder quadrature signals using an Arduino UNO I'm supposed to write a raspberry pi and arduino code to read the RPM of a motor with an encoder attached to it. However, I'm having weird numbers and I'm unsure about the specs on the motor and the encoder. So I thought it would be smart to use a second arduino to simulate the motor with encoder.
The simulator would need to produce a 2 signals representing the two signals from the encoder. I want to be able to set the frequency and phase shift of these signals in software to imitate changes in speed and direction of the motor rotation. Forward would have one signal 90 degrees ahead, and then reverse having that same signal to be 90 degrees behind. So phase difference of plus or minus 90 degrees.
I'd like to eventually have the simulator be able to simulate motor actions like oscillating between forward and reverse 5 seconds each, or forward for 5 seconds and then stop completely.
I found this code by bigjosh which is more or less what I want to do. However, that code doesn't allow for a shift of -90 deg by default. I know there's a comment there to change it, but I'm not knowledgeable enough to understand what's going on exactly. I'd like someone to help me with that.

Wow, that turned out to be way harder than I expected. It is very hard to do cleanly on the AVR timer. But I was able to come up with this working function, which I think is what you are looking for...
// freq_hz is frequency in hertz from 122 to 4,000,000
// shift_deg is phase shift between output A and output B in degrees (values outside -180 to +180 are normalized)

// Note that at frequencies above 44KHz you will loose precision on phase shift. At 4Mhz, everything is rounded to just 0 or +/-90 degrees.
// Note that all timing happens in 1/16Mhz increments, so frequencies that do not land on integer multipules of that will be aproximiate.
// Use startWaveforms() directly for more precise control.

void startQuadrature( unsigned long freq_hz , int shift_deg  );

It can glitch at start-up, shutdown, and changes in speed and direction... but so can a motor encoder so I guess that is ok. It would be possible to create a glitch-free version but more work.
Github repo here...
https://github.com/bigjosh/Quadrature
So, to simulate a motor going forward with 50KHz pulse rate, you would use something like...
startQuadrature( 50000 , +90);
...and the same pulse rate going backwards would be...
startQuadrature( 50000 , -90);
Do note that if you connect an Arduino UNO output pin to a Raspberry Pi input pin that it will likely damage the Pi. This is because the UNO outputs 5 volts for a "1" signal, but the Pi can only tolerate a maximum 3.3V on any pin. You can google "5V 3.3V level shifting" for solutions to this problem.


Sending MIDI messages using PING ultrasonic sensor I am working on a project that uses a potentiometer and an ultrasonic sensor to create MIDI signals. This is my first time working with an arduino. I took a class in C++, but am teaching myself some C in order to program the arduino. So far I have been looking at code that has been written, I've been trying to understand it and mess with it so that my arduino works. The first code creates notes, but I have no control over what notes play or when they play. The first code:

#include <SoftwareSerial.h>

int val;
int AnalogValue = 0;
byte note = 0;
SoftwareSerial midiSerial(2, 3);

void setup ()
{

  pinMode(Pingpin, OUTPUT);
  Serial.begin(9600);
  midiSerial.begin(31250);
}

void loop()
{
  val = 0;
  digitalWrite(Pingpin, LOW);
  delayMicroseconds(2);
  digitalWrite(Pingpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(Pingpin, LOW);

  AnalogValue = analogRead(0);
  note = AnalogValue/8;

  pinMode(Pingpin, INPUT);
  val = digitalRead(Pingpin);
  while(val == LOW)
  {
    noteOn(val, note, 0x40);
  }
  while(val == HIGH)
  {
     noteOn(val, note, 0x40);

  }

}
void noteOn(byte cmd, byte data1, byte  data2)
{
    midiSerial.write(cmd);
   midiSerial.write(data1);
   midiSerial.write(data2);
}

The second code makes more sense to me, but I get no notes to play. I am lost, and can't seem to get the second code to work. Second code:

#include <SoftwareSerial.h>

int val;
int timecount;
int AnalogValue;
int ultrasoundValue;
const int Pingpin = 8;

byte note = 0;

SoftwareSerial midiSerial(2, 3);

void setup ()
{

  pinMode(Pingpin, OUTPUT);
  Serial.begin(9600);
  midiSerial.begin(31250);
}
void loop()
{
  AnalogValue = analogRead(0);
  note = AnalogValue/8;
  Serial.print(note,HEX);
  Serial.print("\t");

  timecount = 0;
  val = 0;
  digitalWrite(Pingpin, LOW);
  delayMicroseconds(2);
  digitalWrite(Pingpin, HIGH);
  delayMicroseconds(5);
  digitalWrite(Pingpin, LOW);

  pinMode(Pingpin, INPUT);
  val = digitalRead(Pingpin);
  while(val == LOW)
  {
   val = digitalRead(Pingpin);
  }

  while(val == HIGH)
  {
   val = digitalRead(Pingpin);
   timecount++;
  }

   ultrasoundValue = timecount;
   ultrasoundValue = ultrasoundValue - 14;
   ultrasoundValue = ultrasoundValue / 5;

  Serial.print(ultrasoundValue);

if(ultrasoundValue > 127)
 {

 }

else
  {

   noteOn(ultrasoundValue, note, 0x40);

  }

}
void noteOn(byte cmd, byte data1, byte  data2)
{
   midiSerial.write(cmd);
   midiSerial.write(data1);
   midiSerial.write(data2);
}

There is quite a bit that needs to be addressed for these programs to work, and I don't know too much about midi, but i'll use the arduino midi tutorial for info. http://arduino.cc/en/Tutorial/Midi?from=Tutorial.MIDI

The first code will take one measurement of an analog value, set it to note, make one digital reading of pingPin, set that to val, and then write noteOn() forever afterwards. The second code will continually make analog and Ping readings and then write those to serial if the ping reading is greater than 127.

Infinite loop aside, Your programs don't work largely because they send the sensor data in the wrong ways. The first byte sent to noteOn is a command byte, it should not contain sensor data. the arduino tutorial uses the command 0x90 to control the note being played on channel one. the second byte is the note and the third byte is velocity, which seems to work like volume.

to set the pitch and volume of channel one, you need to repeatedly send

noteOn( 0x90, note, volume);

If you want to play a note based on the analog readings that both of your codes set to "note" only when the ping value is larger than 127, you need something like this

if(ultrasoundValue > 127){
    noteOn(0x90, note, 0x45); //middle volume according to arduino tutorial
} else {
    noteOn(0x90, note, 0x00); //make the note silent by using 0 volume
}

if you instead wanted to control the pitch with the ultrasoundValue, you would need to scale the value to being within 0-255, and then use that as note instead of the analog reading. You can get much more complicated than this, but you will need to find a reference for the MIDI protocol you can use.


Calling a function that is outside of a class from inside I have an Arduino sketch with a timer interrupt class and would like to place the TIMER2Services() function in the TimerTwoTest.ino file for easy access. On compile I get a multiple definition of tmb2 error in the .ino TIMER2Services() function. I have tried all the variations I can think of but no luck. Is there a way to do this?

TimerTwoTest.cpp.o: In function `TIMER2Services()':
D:\Arduino157/TimerTwoTest.ino:41: multiple definition of `tmb2'
TimerTwo.cpp.o:C:\Users\...\build8577138580185682113.tmp/TimerTwo.cpp:10: first defined here

collect2.exe:

TimerTwo.h:

class Tmb2
{
  public:
  void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
  void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
  TIMER2_TYPE getPeriodTIMER2(void);
  void activeTIMER2 (void);
  private:
}tmb2;

TimerTwo.cpp:

extern void TIMER2Services(void);

[this function is line 10 for the error]
void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod){  //setperiod and enable interrupt
  if (Hz){
    ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
  }
  Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
}

TimerTwoTest.ino:

volatile unsigned long burpCount = 0;

//This routine services the interrupt
void TIMER2Services(void){
  burpCount++;
}

The problem is your definition of tmb2.  You're declaring the variable in the header file, and not the C(++) file.

Please try this:

TimerTwo.h

#ifndef __TIMER_TWO_H__
#define __TIMER_TWO_H__

extern void TIMER2Services(void);

class Tmb2
{
    public:
        void initTIMER2(unsigned int Hz, unsigned int ulPeriod);
        void resetTIMER2(unsigned int Hz, unsigned int ulPeriod);
        TIMER2_TYPE getPeriodTIMER2(void);
        void activeTIMER2 (void);
    private:
};

#endif // #ifndef __TIMER_TWO_H__

The #ifndef TIMER stuff saves you getting multiple definitions from header files if they're included more than once.  There's other ways to do this, but this is simple and well-known.

TimerTwo.cpp

#include "TimerTwo.h"

void Tmb2::initTIMER2(unsigned int Hz, unsigned int ulPeriod)
{
    //setperiod and enable interrupt
    if (Hz)
    {
        ulPeriod = 1000/Hz;    //if Hz > 0 use frequency microseconds
    }
    Timer2.attachInterrupt(TIMER2Services).setPeriod(ulPeriod).start();
}

TimerTwoTest.ino

#include "TimerTwo.h"

Tmb2 tmb2;
volatile unsigned long burpCount = 0;

// This routine services the interrupt
void TIMER2Services(void)
{
    burpCount++;
}

void setup()
{
    tmb2.initTIMER2(blah1,blah2);
}

For the sake of neatness, I'd move TIMER2Services into class Tmb2 as a static function... if possible.


DHT22 need pull down/up ESP8266 I have the strange pb.
My esp8266 was working fine with my DHT22 and then failed every time.
I loaded an example sketch in a other ESP8266 and I have the same pb.... until I shut down -> up the DHT22 when the ESP8266 is working.
To check more, I added this at the setup before dht.begin() :

      digitalWrite(0, LOW); // turn the LED on (HIGH is the voltage level)
  delay(1000); // wait for a second
  digitalWrite(0, HIGH);

And it works. But I don't know why I need to do this "pull up".
PS : I already tried with or without the 10K resistor, same pb.
PS2 : I already tried with 3.3v or 5V for DHT22. Same pb.

Any idea ?

I answer my own question in case someone has the same issue.
The ADAFRUIT_DHT lib DOESN'T WORK WITH ESP8266. It keep saying Failed to read from DHT sensor! until you unplug/plug the VCC on the DHT.

But the DHTesp (link) works very well at first try !

Thx @Juraj and @Jot for their support.


Reusing LED from RC helicopter controller I have an old RC helicopter controller, but not the helicopter.  I recently purchased an Arduino Uno and would like to do something with LEDs(beside the on-board one built-in). Can I use an LED from the controller, that is already soldered in, cut it free and plug into my breadboard.

Side Note

I have no experience in soldering and don't own a soldering iron.

Yes, you can. For convenience, cut a bit shorter the lead on the side of the package where the flat part is so that you can identify the leads easier.


Serial Communication Between 3 Arduinos Doesn't Work (Daisy-Chain) In my project, I have to send a string from one arduino to a second arduino, and make it send the same string to a third arduino. I used UART and SoftwareSerial library, and connected the arduinos like that:

In all the arduinos:
Pin 10 - RX port, pin 11 - TX port

Arduino 1 pin 11    ---->  Arduino 2 pin 10
Arduino 2 pin 11    ---->  Arduino 3 pin 10
Arduino 3             ---->  PC (by hardware Serial)

By theory, Arduino 1 sends string "CA" to arduino 2, which resends that same string to arduino 3, that prints it back on Serial.

The problem is that I get the string "C�" instead of "CA" (that weird "C�" is equal to "067 255" on ASCII).
Does anyone knows why it happens? Maybe there's something wrong with my code?

Here's the code for all the three Arduinos:

Arduino No. 1:

#include <SoftwareSerial.h>

#define ADDR "CA"
SoftwareSerial tiny(10, 11); //TBD

void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
  delay(2000);

  tiny.write(ADDR);
}

void loop() {
  //nothing here
}

Arduino No. 2:

#include <SoftwareSerial.h>
SoftwareSerial tiny(10, 11); //TBD
void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
}
void loop() {
  if(tiny.available() > 0) {
    tiny.write(tiny.read());
  }
}

Arduino No. 3:

#include <SoftwareSerial.h>
SoftwareSerial tiny(10, 11); //TBD
void setup() {
  Serial.begin(9600); //debug only
  tiny.begin(9600);
}
void loop() {
  if(tiny.available() > 0) {
    Serial.write(tiny.read());
  }
}

Any idea on what went wrong?

Arduino #2 should have two SoftwareSerial instances, one to listen to Arduino #1 and another one to talk to Arduino #3:

// In Arduino #2
SoftwareSerial tiny1(10, 11); // Listen to Arduino #1 on pin 10
SoftwareSerial tiny2(8, 9);   // Talk to Arduino #3 on pin 9

You may not need to wire unused signals (11 and 8).

There is an example here : https://www.arduino.cc/en/Tutorial/TwoPortReceive

Note that what you are trying to do is a bus. Serial in Arduino is RS232 based and that is not a bus but a point to point protocol. You should consider using I²C or SPI.


Arduino UARTS Auto addressing slaves i'm using this serial topology to connect my Act ATmega328p (Arduino) slaves together to a master ESP32.

They are in total 10 ATmega328p slaves and one master:

With this type of wiring i'm sure that only one slave per time will talk back to master (when requested), now here comes the problem, basically i need dynamic addressing of slaves: they can be many (up to 30) and i need to access in order the slave devices.

In order to solve the "dynamic addressing" problem i'm thinking about that:

The first slaves will be plugged in and will send to the master his default address (i.e.: 0xFF)
The master will check if the address is used and then reply back to the device with the first available address (i.e.: 0x01)
The slave will get back the response from the master and set an internal variable with the new address (maybe it's a good idea to store the variable in a EEPROM like M24C02: enter link description here)
Starting from the next cpu cycle, the master will ask sequentially to all enumerated slaves to (for example) do an analog read using this workflow:

The master will send a message to the serial bus with address 0x01 asking to do an analog read
The respective slave will handle the request, read the analog input and then reply back to the master
I think that this can work, but i've not found any kind of this implementation...maybe i'm totally out of mind?

New idea and concept

Guys, what do you think about sequentially power up the circuits and using the same mechanism to assign dynamically the address?

This assumption will avoid me to save the assigned id to the eeprom and some other id software function defined functionalities like address reset, etc...

It can be a good (and dynamic) method to solve the problem, about that, how I can implement this sequential power up?

The first slaves will be plugged in and will send to the master his
  default address

If this happens while the master is talking to one of the other slaves,
you risk a collision.

I suggest a very small variation on your scheme. Each slave has a
default address (0xff). When you turn it on, it doesn't say anything.
The slaves only talk when they are addressed.

Every now and then, the master sends a “ping” message to 0xff. The newly
installed slave responds, then the master gives it a real address, and
goes back to its business of collecting sensor data. If no response is
received for the ping within some specified timeout, the master assumes
there is no unconfigured slave.

Since no slave ever sends unsolicited messages, this should avoid any
kind of collision. You just have to make sure that new slaves are added
at a slow rate: after connecting a slave, you wait for slightly more
than the ping period before connecting another one.


Regarding turning exact 180 degrees using an MPU6050 I want to turn robot exact 180 degrees by using an MPU6050. This is the code I tried. Can anyone help me?

#include <MPU6050_tockn.h>
#include <Wire.h>

#define enA 9
#define in1 4
#define in2 5
#define enB 10
#define in3 6
#define in4 7

MPU6050 mpu6050(Wire);

void setup() {
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
  setupmotor();

}

void setupmotor(){
    pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

}

void loop() {
updatempu();

while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
       turn();
  }

}

void updatempu(){
    mpu6050.update();
  Serial.print("\tangleZ : ");
  Serial.println(mpu6050.getAngleZ());

}

void turn(){
  Serial.println("turn");
        digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
      digitalWrite(in4, LOW);
    digitalWrite(in3, HIGH);
      analogWrite(enA, 100); // Send PWM signal to motor A
  analogWrite(enB, 100);
}

void stp(){
    Serial.println("stop");
        digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    digitalWrite(in3, LOW);

}

As I understand, you want the robot to position itself automatically at either 180° or -180° and stay there. When an outer force get's applied to the robot - turning it out of the target positions - it should again try to reach the target positions.

The first problem was pointed out in the comments and your own code correction seems ok to tackle that:

if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
    stp();
} else {
    turn();
}

But I see a second problem: In the real world sensor mostly have some kind of noise imposed on their signal (not necessarily meaning electrical noise). For example if you shake the table, where the robot stands on. Or - more importantly in my opinion - The motor, that you use, might not stop fast enough. The MPU might return a value of 179° or 181° when it should be at 180°, because the motor could stop the robot fast enough (inside the time span it needs to travel 1°). In your current logic, this would trigger another turn command. Since you are only turning in one direction, this can create an instable system, which will turn infinitely.

This kind of problem is often solved by using a feedback loop control (of course in combination with the ability to control/turn into both directions). A good and useful example is a PID control (Proportional, Integral, Differential: This is how the control is mathematically structured), where there are already Arduino libraries for it (like this one). If you want it easier, you can define a range of angles, which are acceptable for your positioning (where it should stop) (for example 175° to 185°). The size of the range, that you need, would depend on the mechanics of your robot and the motor. Note, that this also has drawbacks, but it might be easier for now, depending on what exactly you want to achieve.

As Tom pointed out in his comment, you also get trouble with your first approach, if the method getAngleZ() returns not an integer, but a float, which it indeed does. You can see this in the source code of the used library here. The line

float getAngleZ(){ return angleZ; };

tells us, that the return type of the method is float. The problem with this type is, that it cannot represent every rational value inside it's range. There are gaps between two following float values. The values inside this gap cannot be represented by float. Instead a value nearby will be used (Actually I'm not sure, how this is been done. Probably by going to the next lower value, like with int). This also means, that not every integer is representable by float. Even if the Z angle is exactly 180°, the float value may be something like 179,98. But since 179,98 is not equal too 180 the statement

mpu6050.getAngleZ() == 180

would never become true. Of course the mentioned solutions above apply here too.


Trying to move a stepper motor back and forth So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.

I am having some trouble with this though, because while it will move in one direction, it will not move in the other.

void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      forthMotion(stepper1.currentPosition());
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop?
Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...

Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?

Edit: The code seems to work when I uncomment the if statement in the loop function.

Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.

Are you sure you're using a stepper?


Slaving multiple Arduinos via SPI I am attempting to use SPI communication between a Master Arduino Mega 2560, and standalone Slave Arduino Unos (4, to be exact).

The intention is for the Unos to do some trivial work and produce one byte of data that the Master will take from it, whenever needed. They produce this byte very quickly, and the SPDR is updated with a holding variable (a byte) when the slave is interrupted. The Slaves do not take data from the Master.

The standalone platforms are working 100% (doing the work without problem), and using a single Slave to perform the work, create the byte of data, and have a Master take that data from it, is also working 100%.

The issue When all four slaves are connected (all being powered from the Master), all sharing the MISO, MOSI, and SCK lines, each with its own unique SS line, I am getting xFF for my data byte (garbage data) from the primary slave. I am using the default Mode 0, and the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)... All other SPI lines are wired directly.

The other three slaves are floating their MISO lines (third state), and the Master has all four SS lines as outputs, and all are pulled HIGH in the Master setup. The primary slave I am attempting to communicate with is SS connected to the main SS on the Master (pin 53 on a Mega). I pull the pin LOW, grab the byte from the Slave, and then pull the line HIGH... still garbage.. but only when all four slaves are 'hooked up', like I said, it works fine with one Master, one Slave.

Anyone have thoughts as to what I could be neglecting, missing, etc??

Here is the slave schematic. What you can't see is that VCC and AVCC are tied to the 5V line from the 10-pin header (the connection to the master).

The external power supply I am currently using is added in parallel to the 5V/Grnd you see in the schematic. The power supply has a max current draw at 5V of 10A, so I'm pretty confident that power is not my issue now, unless I have missed something.

I just realized that the imgur image is hard to see, here is a cut-away that should be clearer.

the SCK lines are tied to ground via a 0.1uF capacitor (to smooth the clock signal)

Get rid of that for a start.

  The other three slaves are floating their MISO lines (third state)

That's your problem. They should all be outputs. From the datasheet:

  When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high.

As you can see from that, you should configure all the MISO pins as outputs. However the SPI hardware will turn them into inputs if SS is high. Thus only one slave (the one you set MISO as an output) is capable of responding at present.

You should probably set them as outputs after turning on SPI slave mode. eg.

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

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


Background processes - Arduino Mega and SeeedStudio CAN shield I am attempting to interface an Arduino Mega 2560 with a system of four Black Jaguar motor controllers connected in CAN. I'm using the CAN shield from SeeedStudios to accomplish this.

The way Jaguars in CAN mode are configured, you must send a message every 100 ms to the network to keep the link active. However, I'm also getting input from Serial to another Arduino as well as sending other commands to the Jaguars, but not regularly enough to specifically time it out.

Is it possible to have the link message sent asynchronously in the background while I perform other code? I have looked into timers and interrupts, however I am unsure if this would truly solve the issue considering I have other processes that take more than 100 ms to complete.

Here's my loop statement:

loop() {
  CAN.sendMsgBuf(HEARTBEAT,1,0,volModeEnable); //HEARTBEAT keeps CAN link active
  setVoltage(3,.5); //Sets voltage of Motor by percent
  setVoltage(4,.5);
  setVoltage(6,.5);
  setVoltage(8,.5);
  //GrabFromSerial(); Takes longer than 100ms
  //Control Statement for Additional Commands goes here... (also necessary to be > 100ms)
}

I see several options:

Change your code to achieve lower delays on the other functions
Use interrupts at a set frequency to trigger the sending (and maybe the automatic transmission trigger pins, see MCP2515 datasheet, depending on pin use & schematic of your specific shield)
Use a basic scheduler/rtos

It is hard to tell what is going on without the rest of your code, if it is a good idea to try to achieve faster functions.

I am not 100% sure the CAN-lib would will work well in the context of an interrupt.


Can I charge a 4.2 V battery with a 5 V adapter? Can I charge a 4.2 V battery with a 5 V adapter without damaging the battery?

This question would be a better match to the Stack Exchange Electrical Engineering group.

A 4.2V battery is very likely a LiIon or LiPo battery. I'll call it LiPO below as it's easier to type.

Most cellphones and many small electronic device use a single LiPo battery and use a 5V input to charge them. To do this they have internal control circuitry that ensures the battery's specifications are met. You can obtain suitable control electronics (in many cases as a single IC requiring maybe a few external resistors to configure it) and it makes great sense to use such a control circuit.

In an emergency you can use a 5V source to charge a 4.2V battery IF you know what you are doing and are able to ensure the battery specifications are adhered to. Failing to stay "in spec" may lead to the traditional LiPo "vent with flame" response, and even if there is no apparent damage the battery life can be greatly or very greatly reduced by out of spec treatment.

Key requirements are:

NEVER exceed 4.2V at battery terminals.
NEVER exceed Ichg_max = manufacturers max charging current.
This is usually the same value in mA as the battery capacity in mAh.
ie 1000 mA for a 1000 mAh battery
3300 mA for a 3300 mAh battery etc
When charging, EITHER stop charging when battery potential reaches 4.2V OR if you are able to hold the battery AT 4.2V, then stop charging when Ichg falls (under battery control) to say Ichgmax/4.
If Vbattery is under 3.0 V (which it NEVER should be) charge at no more than C/10 (eg  for a 1000 mAh cell) until Vbattery rises to >= 3.0V. If the battery will not rise to 3.0V under C/10 charge it is dead.

IF you can satisfy ALL these requirements at all times you can charge a LiPo or LiIon battery from 5V without a special charger.


Powering an Arduino directly from a motor driver (DRV8825) or external power source? Hello people from StackExchange,

I'm new to Arduino and driving stepper motors in general; please excuse me for my limited knowledge on the subject. I've been doing research for a few hours already, looking into powering stepper motors and the Arduino, though I've gotten conflicting information regarding my problem.

My problem, or well question if you will, is as follows:
The circuit I need, simplified, contains an Arduino, a stepper motor driver (DRV8825), a NEMA17 5kg.cm stepper motor and a 12V battery pack (yet to be decided what kind of pack, though it will be 12V). Do I need another, lower voltage, battery pack?

After looking into how to power stepper motors using the Arduino online, I found several sites instructing me how to do so. All of the sites had the same circuit I would use, only the motor was different. Here is one of the circuits:

As you can see, it only has a single power supply (with capacitor to catch voltage peaks). I understand most of the circuit, though one question remains: why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver? (You can see the pin descriptions in the second image below) Or do they simply not show the (5v) power supply for the Arduino?

The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not? And if not, would connecting the Arduino to the power supply via the VIN pin work? That would be nice, as it would offer a simple way of fixing the problem instead of getting a separate power source. Connecting the Arduino through USB wouldn't work for my project, as it can't have any wires coming from it. It needs to be completely mobile.

For comparison, here is a circuit that does show the Arduino with an external power source:

I'm a first years mechanical engineering student, hence my little knowledge on Arduino's and stepper motors.

Thanks in advance.

why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver?

No. It is assumed that you will provide the power to the Arduino yourself - either through the USB connection to the computer, or through the barrel jack.

  The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not?

No. The Arduino requires power to be provided.

  And if not, would connecting the Arduino to the power supply via the VIN pin work?

Yes, but it's not ideal.  At 12V the power wasted by the on-board linear voltage regulator will be proportionally high.  As long as all that is being powered is the Arduino itself that shouldn't be too bad, but if you try to draw any significant current either out of the 5V pin or through multiple IO pins (for example to drive lots of LEDs) then it will overheat and potentially shut down.

A more ideal arrangement would be to connect a 5V switching regulator to the 12V battery and use that to power the Arduino either through the 5V pin or the USB connector. Personally, I use cheap UBEC modules from RC model suppliers. They are small, low-cost, and very easy to wire up.


How to control a DC Motor with Hall Encoder using Arduino and Motor Driver? I'm using a DC motor with Hall Encoder. I bought it from DX.

I have made all the connections to motor driver and arduino and I suppose all are correct. I've connected m1 and m2 pins of motor to that of motor driver, encoder A phase and B phase to arduino pins 3 and 11, and GND of motor to GND of Arduino and 3.3V pin of motor to 3.3V pin of Arduino. Also motor driver is also connected to arduino.

The problem is that I'm unable to run the motor but I can count the rotations made by the motor. Please help me with the working code. Thanks.

What are the "m1" and "m2" pins you mention?

On the diagram I see on that link, the pins "1-M1 motor -" and "6-M1 motor +" should be connected to the motor driver. The other four pins should go to the Arduino only.

You can probably test the motor by disconnecting it and connecting pins 1 and 6 to a 9-12V battery or similar, to see if it turns.

By the way I guess the two Encoder Phase connections would be set up on the Arduino using PinMode setting "INPUT_PULLUP". But as you can already read the positions, that part may not matter.


Is it possible to use Pi's output signal as Arduino's input signal? I have a relay attached to an Arduino Uno which I want to control using my raspberry pi 3b. And yes I know it can be done by attaching the relay directly to Pi but I cannot do so. Don't ask me why. That is why I want to know whether it is possible to use Pi's output signal as input for the Arduino or not. I do not have spare parts so I don't want to experiment. If anyone knows about this, please tell me.

This way is fine: the Pi is a 3.3V based board, so connecting one of the GPIO pin from the pi to an Arduino will not damage it. Furthermore, the 3.3V are sufficient to be considered as HIGH even on a 5v Arduino like the UNO.

The other way around: connecting the output of a 5V Arduino to the input of a pi, will very likely damage the raspberry Pi!

So beware of your Pinmode before doing such a connection!


Memory allocation on Arduino Due never returns NULL I'm working on a project that uses quite a bit of RAM to store and analyze data that is sent from the PC. The program heavily relies on malloc/free, which normally works just fine. However, if the data set gets to big - which I can't tell beforehand - the Arduino just dies. Some analysis found that it has to do with memory management. Running a simple sketch which just does
void loop() {
  int SIZE_TO_TEST = (1024 * 10);
  int* mem = (int*)malloc(SIZE_TO_TEST);
  if (mem == nullptr)
  {
    // This never happens
    Serial.print("Allocation failed\r\n");
    return;
  }
  Serial.print("Allocation succeeded\r\n");
  Serial.print((int)mem, HEX); // this always prints 0x200712E0, regardless of the size
  Serial.println();
  for (int i = 0; i < SIZE_TO_TEST / 4; i++)
  {
    mem[i] = i;
  }

  for (int i = 0; i < SIZE_TO_TEST / 4; i++)
  {
    if (mem[i] != i)
    {
      // You better get a new board if this happens
      Serial.print("HARDWARE ERROR: Memory broken\r\n");
    }
  }
  free(mem);
}

works fine and repeatedly prints "Allocation succeeded". When I start increasing the SIZE_TO_TEST, the CPU crashes when the value is over the effective memory size of 96k. The weird thing is, that even when the value is 1000k (far beyond what the uP actually has), the pointer returned by malloc() is still the same memory address, not NULL, as one would expect. The crash also does not occur if the allocated memory is not used (if the two for loops are commented out), so I suspect the actual crash occurs because the program tries to write to memory that is not actually there.
How do I find out that the memory is exhausted? Why does malloc() never return NULL?
(Note: I know about the problems of memory fragmentation with small micro controllers, but I can work around that issue)

Why
This is a partial answer, for now, mostly with regard to:

Why does malloc() never return NULL?

So, the Due appears to use Newlib as its libc implementation; that is the systems C (standard and some non-standard) runtime that includes malloc(), or the greater part of malloc() anyway.  The Newlib malloc() relies on an  sbrk() function which is implemented by the specific system, the Due in this case.
This name and basic idea comes out of Unix; you can read about the interplay between malloc and sbrk some without it having to be in connection with Newlib or the Due specifically.  In short, sbrk extends the area that malloc has to work with and malloc divides that area into requested chunks.  Here is Newlib's documentation for sbrk and a sample implementation.
The Due (SAM) core for Arduino implements sbrk as:
extern caddr_t _sbrk ( int incr )
{
    static unsigned char *heap = NULL ;
    unsigned char *prev_heap ;

    if ( heap == NULL )
    {
        heap = (unsigned char *)&_end ;
    }
    prev_heap = heap;

    heap += incr ;

    return (caddr_t) prev_heap ;
}

This is a kind of degenerate implementation of _sbrk that just blindly says, "You want more memory, sure here you go" without limit.  If you look at the sample sbrk implementation for Newlib, you'll see it just calls abort() instead of a proper failure that would result in malloc returning NULL, which is admittedly not great, but at least it's not pretending that everything is fine.
There should be a condition somewhere in this code that check so see if there's any more space to be had and sets errno = ENOMEM and effectively does return -1 if there is not.
I modified this code to allow me to set a variable from the sketch that could force the next call to _sbrk to fail as described above.  And sure enough, on the next call to malloc() it returned NULL because _sbrk had indicated failure.
So the _sbrk implementation provided by the Due/sam core should be changed so that malloc fails when appropriate.  That said, I'm not precisely sure how that should be done.  So I'm going to hold off on making specific recommendations about it.  Maybe I look into it more I'll come back and update this with something more useful, addressing your other question of:

How do I find out that the memory is exhausted?

In rough terms though, the answer going to be that you modify that function so it returns -1 with ENOMEM under the right conditions.

How
This is the previously mentioned update with some details on the how:

How do I find out that the memory is exhausted?

So I've made something to give you an idea what the condition would look like.  I'm not strictly recommending you use it; for one thing it's barely been tested.
From the ATSAM3X8E's family datasheet:

SRAM0 is accessible over the system Cortex-M3 bus at address 0x2000 0000
and SRAM1 at address 0x2008 0000. The user can see the SRAM as
contiguous thanks to mirror effect, giving 0x2007 0000 - 0x2008 7FFF
for SAM3X/A8

The stack pointer starts near the top of memory 0x2008 7FFF and grows
downward.  The _end symbol marks the end of the mutable static storage
duration variables or the beginning of the heap.  Somewhere closer to
0x2007 0000; the fewer of these variables the closer.
On this system, which has a fairly common layout, the heap grows up with positive increments to sbrk as the stack pointer grows down with stack frames (local variables, return addresses etc).  So, "the end" of memory happens when the heap would otherwise allocate over the stack or the stack runs into the heap as your pushing things onto it.
So a typical thing to do is to check to see whether or not the sbrk's argument would cause the edge of the heap to get "too close" to the stack.
In the the /.arduino15/packages/arduino/hardware/sam/1.6.12/cores/arduino/syscalls_sam3.c, I've include some extra headers:
#include <errno.h>
#include <stdlib.h>

And put the following as a replacement _sbrk():
size_t __malloc_margin = 4 * (size_t)1024;
extern caddr_t _sbrk (int incr) {
    static const unsigned char *       heap      = (unsigned char *)&_end ;
    /****/ const unsigned char * const prev_heap = heap;

    if (incr > 0) {
        // Extra checks for stack growing

        if (incr >= 96 * (size_t)1024) {
            // The Due only has 96K of ram,
            // so any request for 96K or greater
            // is a failure out of the gate.
            errno = ENOMEM;
            return (caddr_t)-1;
        }

        unsigned char *stack_ptr;

        asm volatile(
            "mov %[sp_out], sp"
            : [sp_out] "=r" (stack_ptr)
            :
        );

        if (stack_ptr < heap) {
            // We're already in real trouble.
            abort();
        }

        if (stack_ptr - heap  <  incr + __malloc_margin) {
            // Not enough memory considering safety margin.
            errno = ENOMEM;
            return (caddr_t)-1;
        }
    }

    heap      += incr ;
    return (caddr_t) prev_heap ;
}

__malloc_margin was used as a variable name just because it's the name that avr-libc uses for the same purpose, namely to tune the minimum distance between the stack and heap during an allocation that the break to increase.  By the way, you can see this same kind of check happen in avr-libc's implementation of malloc (which also takes sbrk's role.)  Why is __malloc_margin 4K ?  No really scientific reason.  It's about 4% of memory, so it's not large, and it's not completely inconceivable to me that someone would try to put local variable(s) approaching 4k in a stack frame on a system that has 96kb total memory.  4K may not be an appropriate default though; more thought should go into that.  Having it in a variable like this allows it to be tuned at runtime; usually there would be a header that provides an extern declaration for it.
I may add more later to explain, but it short if the break is being increased, this sbrk looks to see if the new break would get within __malloc_margin of the stack pointer on a request, an if it would it returns the -1 value and errno = ENOMEM to cause malloc to behave correctly from the user's perspective.
Before anyone bothers to mention: Yes, I know you can take the address of a local to get a stack pointer value.  Yes, the check to see if the single allocation is larger than 96K is probably unnecessary.  Yup, it has Due specific stuff in it even though it's not strictly a Due; there are probably identifiers that could be used instead.  It should probably abort() if sbrk tries to go below 0 sized heap.  It's just a somewhat working illustration of what should be in _sbrk().  More thought and at least one change should be put into it before general use.
Regarding abort()
It occurs to me in some cases abort() may be an appropriate way to handle this.  If you believe that you can characterize the system (or the sketch if you like) at runtime so well that malloc() failing can be regarded as a major oversight, then calling abort() in sbrk() could make sense.  Or at least providing the option to do that.
In the comments you asked:

What does abort() exactly [do] on the Due?

Well, Newlib documentation says:

Before terminating your program, abort raises the exception SIGABRT
(using ‘raise(SIGABRT)’).

and then further down:

Supporting OS subroutines required: _exit and optionally, write.

The SIGABRT and _exit parts are more or less standard behaviour.  So it will call your signal handler for SIGABRT if you have one.
So then what does _exit do?  It loops forever.
I called abort() in a sketch and dumped the following via an arm version of the binutils objdump with -dS command-line options.
Here's the relevant abort() code:
00081b98 <abort>:
   81b98:   b508        push    {r3, lr}
   81b9a:   2006        movs    r0, #6
   81b9c:   f000 fb5c   bl  82258 <raise>
   81ba0:   2001        movs    r0, #1
   81ba2:   f7fe fec5   bl  80930 <_exit>
   81ba6:   bf00        nop

bl <raise> would in turn call your signal handler.  and bl <_exit> calls exit which displays as:
00080930 <_exit>:

extern void _exit( int status )
{
   80930:   e7fe        b.n 80930 <_exit>

00080932 <_kill>:

    for ( ; ; ) ;
}

It appears the optimizer has combined some things here, but essentially _exit has an instruction that jumps (branches) to itself, equivelent to for(;;);.
I half-expected the abort(); code to disable interrupts before calling _exit().  If you do plan on abort() in your _sbrk() that might be something to think about.  You may also want to provide a global flag that can be inspected from SIGABRT that allows the signal handler to do something diagnostically appropriate specifically for _sbrk() failures.
Perhaps sbrk should set a flag in a no-init data section and then set the watchdog timer and let it expire (or provide the SIGABRT handler with the information to do that).  Lots of things to consider.


The Wire library and an ATTiny88 MCU This is the MCU: http://www.microchip.com/wwwproducts/en/ATtiny88 - it advertises a hardware I2C interface, but I am struggling with it. It is mounted on my own board (which worked fine if I dropped an ATMega instead).

edited - prev screencapture were from an ungrounded logic analyzer

First tried the Femtocow ATTiny - it has complained about no Wire library at the #include Wire.h line. So i went into C:\Program Files\Arduino\hardware\arduino\avr\libraries, grabbed the Wire folder and copied it into C:\Program Files\Arduino\libraries. Compiled fine, loaded the binary with avrdude, got a few first TWI communication fine, then it started trashing.

Second attempt was with the cores from Drazzy ATTinycore which came with its own Wire library. Compiled fine, loaded the binary and got the same behaviour.

This is how the messed up I2C line looks in both cases. Starts fine, then appears to go wonky, after a few of these wonky bursts the lines go silent. Also, in spite of having changed the frequency to both 100 and 400 kHz i have this weird 1.953 kHz clock...

#define F_TWI             400000L
//#define F_TWI             100000L

....

  Wire.begin(); // Initiate the Wire library
  Wire.setClock(F_TWI);

I am using Arduino 1.8.2. Anything gives ?

My issue has ultimately come from some memory differences between the ATTiny88 and the ATMega88 - the latter has twice as much SRAM - 1 kB. There normally have not been any warnings on this running out of RAM issue except for once - can't recall how but Arduino IDE did warn.

However, until I got to the bottom of it there have been some digging that had to be done. Like getting used to the programmer either working as expected, or erroring and failing, or erroring and not failing. Then there are the, sometimes changing, folders into which Arduino IDE outputs its files. Also there are non-working board configurations causing the used Wire libraries to issue read and write requests followed by just a NAK. Oh, and not to forget about the messed up signals - turns out they weren't messed up, just the logic analyzer was.


Issues with Stacking Ethernet shield and USB Host shield I want to stack Ethernet shield and USB host together with my Arduino MEGA 2560.
Each of these shields works fine separately.
Is it necessary to contact bootloader pins with each shield and arduino board?
I have connected and tried, but the problem exists.
only one shield works fine at once.(always the sheild that directly connect to the Arduino board).
How do I resolve this problem ? I want to work all 2 shields at once.
these are the sheilds I have used.

Circuits At Home USB Host Shield v2.0
Ethernet Shield v5.0

Thank you

Both shields are SPI devices, and both shields seem to be hard-wired to use D10 as the chip select line.

In order for you to use both shields at once you will have to either modify one of them or connect the shield via jumper wires.

You will need to change the chip select connection on one of the shields from D10 to some other pin that is not currently used, and then modify your software (or the library) accordingly.


Voltage, current measurement from solar panel using INA219 and ESP-12F I recently started tinkering with ESP-12F thus I am a novice here. As a standard novice project, I am making a standalone weather station for my living room. I want to use solar panels to charge the batteries which power up the ESP-12F via USB. I am using ESP-12F as a controller and sending data to Rpi using MQTT.
I am using the following items:

ESP-12 F powered by USB
2.5W 5V solar panel ( I want to connected two in parallel but for now using only one )
RPi 3B
INA219A to measure voltage and current generated by solar panel.
IN4001 diode as blocking
DHT11 sensor for temp and humidity values
Battery pack to charge 2 x 2500mAh batteries ( This is not done yet )

I am quite confused by the connections to INA219 and the data its providing. Thus, ESP-12F is still connected to independent usb power source and my goal is for now to understand and monitor the voltage and current generated by solar panel.
The INA219 Vcc, GND, SDA, SCL are connected to ESP-12F. I can read the values and observe them on serial monitor or mqtt panel.
1. Below is the breadboard connection when INA219 Vin+ is NOT connected.

The voltage measurement sent via MQTT is as below:
Ignore graph, I was pluging in/out Vin wire too many times thus very bizzare lines.

Current connections are as below:
Solar Panel (-) --> INA219 Vin (-) and breadboard to power LED
Solar Panel (+) --> Only to breadboard to power LED [INA219 Vin+ NOT connected]
ESP-12F 3V --> INA219 Vcc
ESP-12F GND --> INA219 GND
ESP-12F D1 --> INA219 SCL
ESP-12F D2 --> INA219 SDA
ESP-12F is powered by separated USB power source
Code using which the values are computed:
I have used Adafruit_INA219 library.
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

I dont understand the values sent by INA219 and have no idea how to interpret them. At this point, INA219 is connected to ESP-12F 3V power (Vcc) and GND. It does not have any Vin. Why there is a load voltage of -1.9 and current?
2. When INA219 has Vin(+) and Vin(-) connected

When I connect the Vin+ and Vin- of INA219 I dont have any voltage/current on the breadboard. You can see the LED if OFF. I dont understand why this happens. The whole circuit on breadboard is redundant once I connect INA219 Vin pins to solar panel output pins.
Current connections are as below:
Solar Panel (-) --> INA219 Vin (-) and breadboard to power LED
Solar Panel (+) --> INA219 Vin(+) and breadboard to power LED
ESP-12F 3V --> INA219 Vcc
ESP-12F GND --> INA219 GND
ESP-12F D1 --> INA219 SCL
ESP-12F D2 --> INA219 SDA
ESP-12F is powered by separated USB power source
The voltage and current values at this point is shown below:

The load voltage increases and the difference which is approx 2.1V.
This delta voltage matches the voltage values from solar panel when measured by multimeter at this point. Thus, I would assume load voltage = current voltage generated by solar panel. But, current is unchanged and LED on breadboard if OFF the moment I connect INA219 Vin. Thus, I assume I have done wrong connections.
It will be great if you can point out my mistakes and make suggestions!
Thank you!

You connected the V- and V+ probes of the INA module direct to the V- and V+ of the solar panel. That means you connect V+ with V- from solar panel  over a 0.1 Ohm resistor. That is like a short. The Solar panel gets overloaded and the voltage breaks down. Lucky you, the solar panel can not provide more current. If it could, then the shunt resistor would be grilled. RIP ;-). Try put the v+ and V- in series with the LED and LED_Resistor. e.g.
Solar+ --> IN4001 --> INA+ |no connection| INA- --> LED --> R(LED) --> Solar-

That would make more sense. It'll show you how much current is drawn by the LED.
If you want to know how much current the panel can deliver, you would have to build a circuit with a potentiometer and measure the Voltage between V+ and V- of the Panel. You can also use the INA to mesasure the current through the potentiometer. Begin with a high resistancy, then turn the poti towards lower resistance and check when the voltage breaks down. The INA shows you the current. But be aware that, the max current depent on the amount of light the panel is exposed to and on the age of the panel itselves. So the values will change as these conditions change.


How to keep a pin LOW for a small amount of time after pushing a button and while device is booting? Context

I keep the board in deepsleep mode and want to wake it with different buttons. I need to know which button has been pushed on boot. The board is immediately put back in deepsleep mode afterward.

I've been able to reset the board and pull a pin LOW at the same time. (see circuit below). The reset pin is momentarily pulled low so it reset the board effectively.

I'm not an electronic engineer, just a hobbyist, so any other method to do something are always welcome.

Problem

With the actual code/circuit, I need to hold the button until the device boot up so it can detect button was pushed but I would like to be able to just push the button quickly instead of having to hold it.

Question

How to add some sort of delay that will "hold" the SW-D5 button until the board boot?

Or anything that keep my D5 pin LOW for a short amount of time after the button has been pushed?

I think something in the range of 500 to 1000 milliseconds would be enough.

My actual circuit

simulate this circuit – Schematic created using CircuitLab

My code

#include <Spi.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>

int buttonPin = D5;

void setup() {
  // Read pin value as soon as possible after boot
  pinMode(buttonPin, INPUT_PULLUP);
  int buttonValueAtBoot = digitalRead(buttonPin);

  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);
  Serial.println();

  if (buttonValueAtBoot == LOW) {
    Serial.println("D5 was pressed");

    // Do something useful here like making an HTTP request.
    digitalWrite(BUILTIN_LED, LOW);
  }

  // Avoid problem when the button is being hold
  while (digitalRead(buttonPin) == LOW) {
    // wait before going to deepsleep
    // or the capacitor will be drained
    delay(1);
  }

  Serial.println("going to sleep");
  ESP.deepSleep(0);
}

void loop() {
}

A simple RC network should do the job.

simulate this circuit – Schematic created using CircuitLab

Ok. A quick explanation of what we have here.  C1 and R1 are the same as you have at the moment for your reset circuit. R1 is the existing pullup resistor in the Wemos. R3 recharges the C1 when the button is released. It's effectively the pullup for the button.

D2 is to separate the two parts of the circuit. It prevents R3 from charging the capacitor C2.

The magic happens with C2 and R2. Pressing SW1 discharges C2, and the GPIO goes low.  When you release SW1 C2 charges up again through R2.  When the voltage across C2 rises to the VIH of the GPIO the GPIO will go high.

D1 is to protect the GPIO from the negative pulse you can get from C2 as it discharges.

Here's a simulation. Top line is the GPIO, bottom is RESET.

VIH for the ESP8266 is 0.75VIO, so 75% of 3.3V, or 2.475V.

The charge time of the capacitor C2 is calculated as T=RC, where T is the time taken to charge up to 63% of the supply voltage (2.08V)

With the shown values the time taken to rise to 63% of 3.3V will be 10,000 x 0.0001 seconds, or 1 second.  So to get to 75% it will take a little longer than 1 second.  75% is about 1.4T, so if T is 1 as in the above equation then it will take 1.4 seconds (1 * 1.4) to rise enough for the GPIO to register as HIGH.

Note these times are all from the moment you release the button. Reset has already happened before that time.

Also the internal pullup of the GPIO should be disabled otherwise it will also charge the capacitor and the charge time will be reduced. Since you don't know that resistor value it then becomes impossible to calculate what the charge time will be. Simplest to just disable it and only use the external resistor R2.


Arduino SDFat Libray overwrites last value I'm trying to create a comma delimited file using this SDFat library
Calling this code creates my file
const char Header[24]="Desired RPM,Output RPM\n";
...
foo()
{
  SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
  SpeedCache.write(Header);
  SpeedCache.sync();
}
...

After running, I have a file containing

Desired RPM,Output RPM'\n'

When I call the following function, I want it to add int target and int reference to the bottom of the file.
bool SDClass::SetLine(SdFile Cache,int target, int reference)
{
  bool good = false;
  char NewLine[32];
  Cache.seekEnd();
  sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
  Serial.println(good=Cache.write(NewLine));
  Cache.sync();
  return good;
}

On the first call, this works so for an input of SpeedCache,50,100 I get

Desired RPM,Output RPM'\n'
50,100'\n'

However, if I then write an input of SpeedCache,5,10 I get

Desired RPM,Output RPM'\n'
5,10'\n'

How do I adjust my function so that I will get:

Desired RPM,Output RPM'\n'
50,100'\n'
5,10'\n'

You just need to open the file in APPEND mode:

SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

  O_APPEND

  The  file  is  opened  in append mode.  Before each write, the file offset is positioned at the end of  the  file,  as  if  with               lseek.

You should also pass your file around by reference so it doesn't keep creating new copies of the internal structure:

bool SDClass::SetLine(SdFile &Cache,int target, int reference)


Changing address of MPU 9250 connected to ESP32 Can I change the I2C address of a device (MPU9250) connected to ESP 32 using int pin. I understand that in arduino board if we connect the int pin to A0 the default I2C address of MPU 9250 changes from 0x68 to 0x69. Is something similar possible with ESP 32? Which Pin I should connect to?

You have only two choices with this device on an I2C bus.  As stated in the datasheet:

So it's either:

0b1101000
0b1101001

The AD0 pin selects which of these two addresses are used.
The complete datasheet can be viewed at the following link as well as other places:
Datasheet


Serial data plotting programs I need to plot serial data from Arduino.

I require support for:

Various data formats (e.g. signed, unsigned, 8 bits, 16 bits);
Plots several data on the same axes;
Exports / Imports file data.

As plotting serial data from Arduino is a common need, my question is:
What programs/utilities are available for plotting serial data from Arduino that meet the needs above?

What are the advantages / disadvantages of the method you have suggested?

There are some good applications for visualizing the serial data, including:

MegunoLink ($29.95; Lite free) - plotting, logging, programming, reporting and more.

MakerPlot ($39) - digital & analog plotting, monitoring, custom interfaces and more.

ArduinoPlot (free) - simple plotting.

arduino-plotter (free) - easy, light-weight plotting with support for all primitive types

Bridge Control Panel (free) - logging, plotting, and more.

RealtimePlotter (free) - 6 channels data plotting.

Real Time Serial Data Plotter (free) - CSV data plotting, logging and more.
SimPlot (free) - 4 channel plotting.

Arduino Serial Plotter (free) - built in Arduino Editor under Tools > Serial Plotter.

(This is a community wiki, you can expand the list.)


NeoPixel library performance: Adafruit vs. FastLED I'm new to these addressable LED things – I just received a 149-LED WS2812B strip today, and I'm experimenting with various approaches. Adafruit's own tutorial says the FastLED library is faster than their Adafruit_NeoPixel library, so I wanted to test their performance.

I'm running this code on a Nano clone:

// Adafruit
#include <Adafruit_NeoPixel.h>
// FastLED
#include <FastLED.h>
// Common
#define NUM_LEDS 149
#define DATA_PIN 6

// Adafruit initialization
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);
const uint32_t adaBlack = strip.Color(0, 0, 0);
const uint32_t adaWhite = strip.Color(255, 255, 255);

// FastLED initialization
CRGB leds[NUM_LEDS];

void setup() {
  // Common
  delay(2000);

  // Adafruit setup
  strip.begin();

  // FastLED setup
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);

  // Common
  Serial.begin(57600);
}

void loop() {
  unsigned int adafruitMillis = adafruitLoop();
  unsigned int fastLedMillis = fastLedLoop();
  // Yes, this is ugly -- but it works every time
  Serial.print(adafruitMillis);
  Serial.print(",");
  Serial.println(fastLedMillis);
}

unsigned int adafruitLoop()
{
  long unsigned startMillis = millis();
  for (int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
    strip.setPixelColor(whiteLed, adaWhite);
    strip.show();
    strip.setPixelColor(whiteLed, adaBlack);
  }
  return (unsigned int) millis() - startMillis;
}

unsigned int fastLedLoop()
{
  long unsigned startMillis = millis();
  for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed++) {
    leds[whiteLed] = CRGB::White;
    FastLED.show();
    leds[whiteLed] = CRGB::Black;
  }
  return (unsigned int) millis() - startMillis;
}

The results are totally disastrous for FastLED (shown in red):

Am I doing something wrong, or is FastLED winning on features, rather than on speed?

For the record, I did check whether the performance hit comes from setting the pixel values or from sending the data – FastLED is faster at setting the pixel values than Adafruit's library, but that doesn't matter because setting two pixel values takes 3 ms or less for the entire strip, regardless of the library. Sending the data to the strip takes most of the time, and that's where FastLED lags behind big time (900 ms compared to Adafruit's 200 ms).

You can't rely on the timing reported by millis when comparing FastLED and Adafruit's neopixel library.  Writing out Neopixel data involves disabling interrupts, which is what the clock uses to advance.  FastLED accounts for this and attempts to update the system clock time after writing out led data to account for the amount of time that interrupts were disabled, but the adafruit NeoPixel library doesn't.  You need to use something else to compare timing.

(WS2812 data has a pretty strict data rate - 800khz, or about 30µs per rgb led)

(I should know, I wrote FastLED :)


Powering arduino and sensors and motor damaging 16x2 LCD? I have an application that requires reading sensors and moving a stepper motor.
The sensors draw about 200mA between them, and need 5V to work. (Too much to draw through the Arduino, I thought) The stepper is recommended to run off 12V, and is driven through a BigEasy board. And, of course, the Arduino needs 5V.

My actual setup has an old laptop power brick, which puts out nominally 12V. This is fed into a voltage regulator (one of the cheap ones with a voltmeter built in) which outputs a steady 5V, even if the input voltage changes a bit. So, I've got a reasonable 12V supply and a fairly fixed 5V supply.

From the 5V supply, I run wiring to the sensors, and from the 12V supply I wire the stepper driver.

The thing is, to power the Arduino, I thought I could just wire up a USB socket (only the power lines) and wire the USB socket to the 5V regulated output. Then I could either plug my arduino into my computer to program it, or plug it into the dummy usb socket to power it standalone.

This arrangement seemed to work for a while, but I've noticed strange behaviour with the 2x16 LCD board which is also attached. I should point out that the LCD takes it's power from the regulated 5V, not from the 5V rail of the Arduino, although the data lines go to the Arduino. The LCD has gone into a "lock-down" mode whereby it only displays half blocks on the top line and nothing else.

I'm wondering if it could be related to effectively powering the system with 2 supplies; one for the majority of the load through the old laptop power brick, and the Arduino through the USB port of my (also laptop) PC. Somewhere along the line, ground get connected to ground, but are all grounds equal?

Is there a standard solution for having the Arduino plugged into your development PC (so as to get debug messages through the Serial COM monitor) whilst still be able to safely power the high-draw loads of the rest of the system. I did consider powering the Arduino through it's barrel jack, but then I'll need an additional 7V supply. (The 5V regulated supply would be too much, and the 12V "semi-regulated" supply would be too much).

And can I do something to protect the next LCD that I use? (Stick a 5.2V Zener across the power pins to prevent spikes??)

In some instances, it is a known issue that certain LCD's pull more power from the arduino than is sustainable depending on the power source.

A few suggestions:

Put something like a 100-200 ohm resister in the 5V to the LCD and connect just that and GND, then measure the voltage drop across said resister.  That will give you the current with ohms law, if its much more than 4mA its a faulty LCD or a fault in your wiring.

You should also check the pins for continuity errors, or shorts.

Another idea, is to make sure the voltage, and amperage coming from the 5vdc step down you are using is adequate for the task at hand.

And finally, you'll need to calculate the complete pull on your power source. i.e. you'll need to know how much load your bigeasy driver pulling from the 12vdc power supply, as well as how much your 5v stepdown is using. if they are exceeding the output of the PSU, you can run into issues.

I ran into a similar issue with my own project, using an arduino Uno with grbl + 3x easydriver motor controllers, & mega 2560 + lcdkeypad shield. Powering the easydrivers with 12vdc & using a voltage stepdown module also gave me issues, as it didn't provide enough current for the stepper motor drivers and the LCD + mega + uno from the 5vdc. I was overloading the power supply, and the 5v wasn't producing the correct power requirements.

I bought a better power supply that had 24, 12, 7, and 5v on it, and haven't had an issue since.


Single #include pulls in all libraries I am tracking down the memory usage of an Arduino-like project I am working on (not a real Arduino, but has same microcontroller and it uses the Arduino build environment, version 1.6.8). I have some modules that I am using and placed them in the Libraries directory in my sketch directory:

Encoder
LiquidCrystal
OneWire
TGPages
TGPro

Now, when I compile a minimal sketch...

#include <Arduino.h>

void setup()
{
}

void loop()
{
}

...the compiled size is 450 bytes Flash and 9 bytes RAM. So far, so good.

Now here's the weird part: when I include a single header file from anywhere in the Libaries folder, the compiled size increases dramatically.

#include <Arduino.h>
#include "pins.h"

void setup()
{
}

void loop()
{
}

"pins.h" is located in the TGPro directory and only contains #defines, not even code or other includes.

....
Using library TGPro in folder: C:\Users\User\Project\TG\libraries\TGPro (legacy)
Using library OneWire in folder: C:\Users\User\Project\TG\libraries\OneWire (legacy)
Using library Encoder in folder: C:\Users\User\Project\TG\libraries\Encoder (legacy)
Using library LiquidCrystal in folder: C:\Users\User\Project\TG\libraries\LiquidCrystal (legacy)
Using library EEPROM at version 2.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\EEPROM
Using library Wire at version 1.0 in folder: C:\Users\User\Project\TG\hardware\arduino\avr\libraries\Wire

Sketch uses 2,266 bytes (7%) of program storage space. Maximum is 32,256 bytes.
Global variables use 230 bytes (11%) of dynamic memory, leaving 1,818 bytes for local variables. Maximum is 2,048 bytes.

And I'm like: WTF? I'm not even referencing any of the files, still they get pulled in, wasting space. There are a few global, static variables in there which explain the used space and referenced code.

So, my questions:

Is het normal for Arduino to pull in all files in the Sketch\Libraries directory, regardless if they are referenced or not? It doesn't seem to do this with the 'core' libraries.
How can you prevent this? Suppose I have a large collection of modules that I use in various projects, but not all modules are used all the time. It would be a waste to include code that is never actually used.
How can I find out more about the code that is compiled in; I know the linker will leave out unreferenced code, but I want to make sure this is due to the statically defined variables.

What you are experiencing is due to the fact that your use case does not match with the Arduino foreseen use cases of "importing a library".

Basically you want the use case "include a file" and you get "import a library". The use case "import file" is simply not foreseen in the Arduino IDE.
Because the Arduino IDE add the library to your code it also adds the source doe files to your code. When these source codes contain global variables (which is very common and not a bad practise in embedded world) these will be part of your final code. As such your sketch will increase size even if you do not use these global variables.

To answer questions
1) yes it is normal because the use case "include file" is translated into "include library" in .ino files in the Arduino IDE.
Why this does not happen for the core? The core is first linked into a archive and then linked to the sketch. This leaves the linker more options to remove stuff.

2) I think the easiest is to copy the pins.h file in your sketch work folder (and you probably will need to restart the Arduino IDE).
Another option is to go for a real IDE like the arduino eclipse plugin called sloeber (which I develop)
In sloeber you could link to the pins.h file instead of copying. You could also reference the pins.h with a (partial/full) path avoinding the library include.

3) All global variables, static and similar stuff in the source code of the "imported libraries"


Arduino Nano 3.0 and Arduino Uno Benchmarks What are the benchmarks (MIPS) of an Arduino Uno (ATmega32P) and Arduino Nano 3.0 (Atmega328) @ 1.6MHz?

ATmega16U4/ATmega32U4, ATmega48A/PA/88A/PA/168A/PA/328/P, ATmega2560, and numerous other Atmel AVR 8-Bit microcontrollers have an instruction set typically with “135 Powerful Instructions – Most Single Clock Cycle Execution” per datasheets.

That is, many of the AVR instructions, including almost all of the logic and arithmetic instructions, execute in 1 cycle.  A fair number of memory access instructions take 2 cycles.  A few instructions (eg JMP) take 3 cycles, and some (RCALL, CALL, RET, RETI, et al) take 4 or 5 cycles.  Others (eg SBRC) take 1, 2, or 3 cycles, depending on operand values and whether a branch occurs that disrupts the pipeline, which is shallow.  For an overview, see the instruction set summary in any AVR-part datasheet. For details, see Atmel's AVR Instruction Set Manual, doc0856 at atmel.com.

Overall, the average instructions per second in a typical compiled C program probably is between 1.5 and 2, so a 16 MHz system might do 8 to 11 MIPS on average, while carefully tailored do-nothing code can easily achieve 16 MIPS.


help connecting atmega32 micro-controller to LAN I have an atmega32 micro-controller and I would like to connect it to my LAN via ethernet, I'm planing to do this using arduino ethernet shield W5100 but I don't know how to start or how to interface it or code it, I need help finding a step-by-step tutorial to do that if it's possible or help to find a better solution if using arduino ethernet shield may cause problems, thanks in advance.

There are quite a few diagrams and tutorials on the web that will help you achieve this.  I think the obvious choice would be to use SPI to interface to either a W5100 or ENC28J60 based board since your chip supports that.

You might be able to get smaller boards that would be better suited to your needs, but before you buy you should check that there is a library that will suit your needs.


What is the name of a peripheral which reads servo output data physically? I know the title is phrased terribly, but I'm not sure how to phrase it since I'm not sure of the name.

I have a servo, that I cannot connect to, except for the output spine/shaft (physically).  I need to get the output of that servo into an arduino, or raspberry pi.  So I need some kind of peripheral that can attach to the shaft of the servo, and tell me what position it's in.  I can't figure out how to find what part I need, because I can't google for the name of it correctly.  I've tried servo input shaft, and many other things that don't make sense.

More Info.

I have a servo on a machine, and I can not interface with this servo in any way but physically.  I can't read the output from it electronically, and the signals are proprietary.  I can't take anything apart, all I can do is put something physically on it.

So, the issue is, I need to (based on nothing but the position of the servo shaft) figure out what position that 3rd party servo is at.

With that information, I'm then going to man in the middle, and attach another servo to my device, and change the value to what I want.

So if the factory servo is at 50%, and I know that by using something like a rotary encoder, if that ends up being the answer, I then could add x% to my actual servo.

What you need is an absolute rotary encoder.

It will provide feedback about the absolute rotational position of the servo shaft.

An encoder that uses gray code is preferred because only one binary bit changes between adjacent positions.


Using a MOSFET module to control DC LED PWM I've seen some similar questions here for using MOSFET to control 12V LEDs
But apparently the only MOSFET currently available to us is a 2-MOSFET high power trigger module, details in the link below.

https://www.elecrow.com/high-power-mosfet-trigger-switch-drive-module.html

How do we connect this to the Arduino to send the PWM trigger (I get confused by the three holes) and how do we connect the DC power to this??? I get confused with the power connections.

it seems to be a typical low-side switch (dual switches). the load goes into DC+ and DC- --> ask the manufactuer to be sure.

whether it works for you will depend on the load, driving signal and the mosfet used -> you should ask the seller for a schematic, or buy one and reverse engineer it.


Question on how "f" value is calculated in converting Morse Code to laser audio from this tutorial I am working on this tutorial,

https://www.hackster.io/SURYATEJA/morse-code-communication-using-laser-module-both-ea1b01

and the author created a "Send" and "Receive" code for encoding and decoding Morse code. He created the "Send" code with the entire alphabet A-Z, but his receive code only has 9 letters.

I thought I could easily add in the missing characters, and even add in numbers, but I am stuck.

His code has 2 values to decode the morse - "a" and "f"

In his receive code he has a value "f" that is supposed to be calculated by the number of spaces, but I cannot see how he comes up with his result.

For example, this is his sending code for "a"

    case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;

Then this is the receive code;

if(a==4 && f==10) {   Serial.print("a");

I understand the value of 4 for "a", but I cannot understand the value of 10 for "f"

"a" is calculated by assigning a value of 1 for a dot and 3 for a dash and adding the values (in this case one dot and one dash, 1+3 = 4)

He explains how to calculate "f" here in his tutorial, but I still don't understand.

When the LASER falls on the LDR, the value goes beyond 1000, and then it will enter into a loop.
Now quantize the values i.e. if the value goes beyond 1000, then assign it as '1', otherwise assign it as '0'.
Inside a loop, calculate the number of '1's and '0's. Set the counters 'a' and 'f'. Count the number of '1's and store it in 'a' and similarly count the number of '0's and store it in 'f' respectively.
Now check the specific values of 'a' and 'f' respectively. Each character will have different set of 'a' and 'f'. The matching value will be displayed.

That seems to indicate;
Laser on = Over 1000 = 1
Laser off = Under 1000 = 0

So for the letter a, I only see 2 times the laser goes off, not 10.Minof formatting changes

This is not a good tutorial. The receiver works by assuming 14 dotLen time periods for each character. There is a loop that runs 14 times, with a 200ms delay between each iteration. If the laser is detected, then a is incremented, otherwise f is incremented. This means that the sum of a and f is always 14, and the case where a==0 means nothing was transmitted. The incomplete receiver code shows only 10 options for received characters and leaves out a==5 (which would be R or U), but does define 1 through 10 otherwise.

The receiver code does not differentiate between dots and dashes, it only counts the number of dotLen transitions where light is detected. This is not Morse Code.

The receiver code cannot distinguish between S (dot-dot-dot) and T (dash) because they both have 3 dotLen value. Same for A (dot-dash) vs. N (dash-dot).

If you want to understand decoding morse code, this is not a good tutorial to follow. It does not decode morse code, and I cannot see how it would work even with it's companion transmitter program.


Random numbers being printed back after entering data I am currently working with an Arduino Micro / Linduino and making a program based on a lot of switch statements to execute certain functions that will be passed to a microprocessor (LT2974) on a board serially. For the most part, all of the functions I have work, except there is one that I am trying to determine if it is my program that is causing issues, or the Linear Tech libraries that are provided. Upon research, I did discover something strange in my code that I cannot explain.

Here is a quick snippet of my code:

unsigned long serialdata;
int inbyte;

long getSerial()
{
  serialdata = 0;
  while (inbyte != '/')
  {
    inbyte = Serial.read();
    if (inbyte > 0 && inbyte != '/')
    {
      serialdata = serialdata * 10 + inbyte - '0';
      Serial.print(serialdata);
      Serial.print("test \n");
    }
  }
  inbyte = 0;
  return serialdata;
}

void loop()
{
  getSerial();
  // Switch statement represents Slot choices
  switch (serialdata)
  {

    case 1:
      {
        commands(Slot1);
        break;
      }
    case 2:
      {
        commands(Slot2);
        break;
      }
    case 3:
      {
        commands(Slot3);
        break;
      }
    case 4:
      {
        commands(Slot4);
        break;
      }
  }
}

I have left out the following switch statements that are found in the commands function as they are not where the issue lies.

For some reason, when I pass data through to the Arduino, and then go to reprint it out with my Serial.print command in getSerial(), there is an additional number printing, and I believe the issue to lie here.

So, for example, if I type "/1/" (the slashes were used to pass multiple variables as shown in the function, but I'm only passing one for now), the Arduino reponds with:

1test
4294967268test

here is "/2/"

2test
4294967258test

and here is passing multiple variables with "/2/9/"

2test
9test
4294967258test

All of the values I just showed you do not correspond to any of my switch statements implemented, and so no actual data is being returned besides the print command from getSerial(). So can anyone explain what is going on here?

EDIT: I added the data types of serialdata and inbyte to the top of the post.

The problem is that you are blindly reading serial data without first looking to see if there is actually any serial data available to read.

If there is no data there Serial.read() will return -1.  Since you have only provided a snippet of your program I can't say what data type inbyte is, but my guess is it's some form of unsigned 32-bit value, since -1 mapped into an unsigned 32-bit value is 4294967295.

You need to be checking the presence of data, and only reading when you should read, and also looking for the end of your data sequence (add some terminating character, like a line feed) to know when to stop looking for and reading characters.


How to use the analog comparator to determine when an analog pin has reached a certain voltage? I am trying to find some information on how to use the analog comparator on an Atmega328 to detect when an analog pin has reached a certain voltage (3.16 volts).

I cannot find any example code that says how to do this, although I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin. I do not understand how this would work as the PWM pins do not output an analog voltage, but a pulse width modulated square wave. Is it possible to use the comparator to compare with a certain voltage this way?

I have tried polling with analogRead(), but it is too slow for my application.

I have a page about the analog comparator that has code:

volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

This is for a fixed reference voltage, for example:


Make Sure Digital pin is high before Serial.write() I have the following code for a TTL to RS-485 Adapter Module

[...code]
digitalWrite(DE_PIN, HIGH); //directional control for adapter
Serial2.write(Message, Size);
Serial2.flush();
digitalWrite(DE_PIN, LOW);  // Set To Recieve
Serial2_reading_foo();
[code...]

I've noticed that DE_PIN does not seem to go High fast enough before Serial2.write() executes I confirmed this by adding a small delay(ms) which made the code function perfectly.

digitalWrite(DE_PIN, HIGH);
delay(100);
Serial2.write(Message, Size);
Serial2.flush();
digitalWrite(DE_PIN, LOW);  // Set To Recieve
delay(100);
Serial2_reading_foo();

Unfortunately, there's pretty much universal agreement that you shouldn't ever use delay() in programming. Plus doing any kind of wait function here seems to be insensitive to the real problem. Is there a better way to make sure that DE_PIN==HIGH before the Serial2.write() Function begins?

The MAX485 requires 2V on the DE pin to register a HIGH. It takes no more than an absolute maximum of 50ns for the DE pin to switch the buffers. The Arduino takes 10.4ns for an IO pin to rise to 2V.

That's an absolute maximum of 60.4ns.

One clock cycle of a 16MHz Arduino is 63ns.

That is longer than it takes for the IO pin to tell the MAX485 to switch the buffers.

You can increase that rise time by taking in to account the input capacitance of the MAX485 and the resistance of the connection between the Arduino and the DE pin, but it will still be microscopically small compared to the time between the pin going HIGH and the serial transmission starting.

So there must be something fundamentally wrong with your setup.  Two possibilities spring to mind:

You aren't controlling RE, only DE, so RE is floating and is being capacitively linked to DE through the parasitic capacitances of the board and circuitry, making it rise and fall very slowly.
You haven't set the IO pin on the Arduino to OUTPUT, so it switches between floating and HIGH through a very high resistance, causing slow rise to HIGH and maybe never getting to LOW at all.

Or a combination of the two.


Unable to connect esp8266 12 module with arduino uno Here is what I am doing

Arduino(UNO)--------Esp8266
3.3 v -- vcc
TX      -- RX
RX      -- TX
3.3 v  -- EN(ch_pd)
GND     -- GND

there is no blinking of LED on Esp8266, sometimes the LED is on and sometimes it is not. And when I send "AT" command using Serial of Arduino IDE, only RX light of Arduino blinks, TX is not blinking and there is no response of that command. I am having 3.3 voltage on my Vcc pin of Esp8266 but the voltage on the TX and RX pins of Esp8266 is 5 volts, I know that i can reduce this to 3.3 voltage by using a voltage regulator but my question is why there is no blinking on the module even when i have supplied the proper 3.3 voltage and GND?
What's the difference between the blinking and a still LED on Esp8266?
I have tried every tutorial on internet. No help at all. Right now I am so exhausted that I want to quit.If you can help in solving the problem, I would be very thankful to you sir.

When you are using Arduino board just as USB --> RS232 converter to send AT commands from PC to ESP8266 you have to connect TX to TX and RX to RX. But when you want communication between microcontroler and ESP then you have to connect TX to RX and RX to TX. Here I explained that in details.


Why does DHT-library (and others) only allow one object instance? I came across the problem to handle two DHT22 devices.

I use the Adafruit DHT Sensor library.

Since my Arduino sketch works as a "relay" for Serial commands on a host, I tried to wire up and dynamically instantiate DHT22. With no luck.

I checked the source and found, that the DHT object only gets constructed before setup() as a constant in the examples, because the library is written that way.

I did a quick hack, which works, but seems ugly to me:

DHT.cpp

DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) {
-  _pin = pin;
-  _type = type;
-  #ifdef __AVR
-    _bit = digitalPinToBitMask(pin);
-    _port = digitalPinToPort(pin);
-  #endif
+  //_pin = pin;
+  //_type = type;
+  //#ifdef __AVR
+  //  _bit = digitalPinToBitMask(pin);
+  //  _port = digitalPinToPort(pin);
+  //#endif

...

-void DHT::begin(void) {
+void DHT::begin(uint8_t pin, uint8_t type, uint8_t count) {
+  _pin = pin;
+  _type = type;
+  #ifdef __AVR
+    _bit = digitalPinToBitMask(pin);
+    _port = digitalPinToPort(pin);
+  #endif

DHT.h*

-   void begin(void);
+   void begin(uint8_t pin, uint8_t type, uint8_t count=6);

Basically, I moved a few lines from the constructor to the begin() method. The whole thing works. I can even rewire & change the data-pin dynamically while the Arduino runs.

Here are my questions:

Is the hacked away behavior a bug or feature?
Would my solution be good enough for a pull request to Adafruit? I would clean it up beforehand.

There is nothing wrong with the library. It does not allow just one object instance.

What is wrong is your way of using it.

It, and many other libraries, specify the pin numbers and other (under normal usage) static data in the constructor. You want to have two objects then create two objects.

But it seems you want to change that static data. So you need to construct differently.  Instead of statically declaring your objects you need to be dynamic. Use new and delete.

DHT *myDHT = NULL;

myDHT = new DHT(4,5);
// do something
// change pins
delete myDHT;
myDHT = new DHT(6,7);


how can i split string data in arduino? im sending string data via serial with following format ex. :45:60 or such as ":120:57".i got the data shown in Serial.println (secondValue) Serial.println (thirdValue); but i cant convert it to int

String myString;
char c;
int Index1,Index2,Index3, azi;
String secondValue, thirdValue;
void setup(){
Serial.begin(9600);}
void loop(){
while (Serial.available()>0)
{
delay(10);
c = Serial.read();
 myString += c;
}
 if (myString.length()>0)
{
Index1 = myString.indexOf(':');
Index2 = myString.indexOf(':', Index1+1);
Index3 = myString.indexOf(':', Index2+1);

secondValue = myString.substring(Index1+1, Index2);
thirdValue = myString.substring(Index2+1, Index3);

Serial.println(secondValue);
Serial.println(thirdValue);

myString="";
}
delay(1000);
}

All numbers are integers?
If yes, you can use toInt() function.

int secondValueInt, thirdValueInt;

secondValueInt = secondValueInt.toInt();
thirdValueInt = thirdValue.toInt();


Unstable ESP8266 - flickering lights A while ago I have bought NodeMCU board along with few sensors to play with. I have coded everything, and, when powered via USB, works like a charm. Problem begins, when I try to use my contraption as a standalone system. It works for few minutes, then it starts giving me false readings from the sensors (like, luminosity of few thousands in a dark room).

I am powering the system with (pics at the bottom of the post) AC-DC step down module, 230v -> 5v (1A of current), which then I am stepping down with DC-DC step down module, 5v -> 3v (800mA of current). Using only these two modules, I power NodeMCU and all of my sensors - currently luminosity, temp&humid, motion, SSR (I had led matrix too. I thought that maybe it drags too much current, but no luck there - after disconnecting it I have same problems).

My main indicator that something is not right, is SSR module. It has a built-in diode of the same size that NodeMCU has. It lights immediately as I start the system, and it (it's diode) flickers (it's intensity changes). It does not flicker, when I connect everything through USB.

I have also tried to put 50uF capacitor into the wiring, but no luck either, system is still unstable. What am I doing wrong? Why does the light flickers? Is 1A/800mA not enough power for my system?

Edit: I know what is the cause. I just do not know how to fix it. I just kept my multimeter on for 10mins for both of the step down modules. 5V -> 3V step down (2nd item in the pics below) is initially giving me 800mA, but then gradually losing current (right now it's at 350mA after just few minutes of work). Is there anything I can do here? Or just throw the thing away and look for some other power supply? It's a standard AMS 1117 with some capacitors on it.

Below are the pictures, of my step-down modules and SSR module:

The VIN pin on the NodeMCU board can take the 5V directly. Had no problem with that way until now.

What is strange to me is that the current from your 5V to 3V regulator  is degrading. The regulator on the board it's self is basically the same (maybe another manufacturer). What may be the cause is that the regulator is overheating and somehow that the effects the output current and/or voltage.

What you can also try is a LM2596 step down regulator.
Those are pretty cheap as well and have a good output capacitance. They can deliver up to 3A at down to ~1.3V. Input voltage is somewhere between 40V and your output voltage plus 1 or 2 volts to let it properly regulate.
You can use that module to transform your 5V down to 3.3V easily - i've done it so often with it, i lost count.


Calling a localhost php script from arduino Is it possible to connect arduino uno to call a php script using ONLY an arduino uno board, and an esp8266-01 wifi module.? That is, I lack wifi shield such as node MCU.
I just need the setup to call a php script on my localhost server.
I'm using arduino IDE 1.8.13.
Gracias

You can program the ESP-01 module using the arduino IDE. There are instructions in the README here: https://github.com/esp8266/Arduino
You can program the ESP-01 to connect to WiFi and communicate with your arduino sketch using the serial port. Don't forget the ESP-01 runs at 3.3V while the arduino runs at 5V. You'll need to shift the voltages somehow, otherwise you'll burn the arduino uno.
Here's an example of code you can run on the ESP-01 to connect to WiFi and start a TCP connection: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiClient/WiFiClient.ino
All that's missing is making an HTTP request instead of a "raw" TCP connection. You can probably find that in the examples. Then, add code for serial communication back to your arduino uno.
Good luck!


Help connecting an Arduino and an electronic speed controller We have this controller that we are planning to use with this motor. How do we plug it to the Arduino to make it work?

This is a totally new subject for our school team, since we are mostly programmers, so your help will be really appreciated.

HobbyKing, which sells Arduinos and is a great source for motors and controllers, has an instructable on this at http://www.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/

I found another on the OpenROV site, at http://community.openrov.com/forum/topics/how-do-i-activate-electric-speed-controller-with-arduino

Did you actually try googling "arduino electronic speed control" before coming here?