How to delay so that LED stays on a bit longer? I have a circuit with a shift register which controls 8 LEDs: http://node-ardx.org/exercises/5. In code, I created a function cycle() cycle through each LED one at a time, but this occurs too quickly on the board. How can I add a delay inside the loop so that each LED stays on for 500ms?

Here's my code:

var five = require("johnny-five"), board, shiftRegister;

board = new five.Board();

board.on("ready", function() {
  shiftRegister = new five.ShiftRegister({
    pins: {
      data: 2,
      clock: 3,
      latch: 4
    }
  });

  var bytes = [
    00000001,
    00000010,
    00000100,
    00001000,
    00010000,
    00100000,
    01000000,
    10000000,
    00000000
  ];

  function cycle() {
      for ( var i = 0; i < bytes.length; i++ ) {
          console.log(bytes[i]);
          shiftRegister.send(bytes[i]);
      }
    }

  this.repl.inject({
    sr: shiftRegister
  });

  cycle();

});

Insert a delay of 500ms?

function cycle() {
    for ( var i = 0; i < bytes.length; i++ ) {
        console.log(bytes[i]);
        sr.send(bits[i]);
        delay(500);
    }
  }


Using Temperature sensor arduino to trip off an ac device Using Temperation through arduino to trip off an ac device?

Yes, there are lots and lots of project descriptions similar to yours (if I guesstimate) on the web. Google is your friend.

Here is one link to an interesting project - if you are interested in brewing beer.

Cheers!


How to connect a simple wall switch to arduino GPIO I am trying to create a smart doorbell, but my problem is that doorbell makes ring any time when nobody touch the button.

I think that the problem is caused for the incorrect way to connect the analog wall button to arduino GPIO.

Basically my wiring diagram is:

Analog Input (A0) to 1 pin of the button.
Ground of the Arduino (GND) to the other pin of the button.

When the button is pressed, the circuit is closed, and doorbell makes ring!

But surely this is not the way to connect a button on the wall because the doorbell sounds on its own.

I leave a picture of the button

jose can u c is absolutely right, you need a pullup. No need to change your wiring however: the Arduino has built-in pullups on all the inputs. You just have to activate them:

const uint8_t buttonPin = A0;  // or any other pin for that matter

void setup()
{
    pinMode(buttonPin, INPUT_PULLUP);
}


Powering a Sim800L Module I am trying to use a DC power supply. I am thinking whether I can use this power supply to provide power for Sim800L module. After some research, I gathered that the Sim800L module requires a max current of 2A during GPRS transmission at 3.8-4.2 V (4.0 recommended). With the power supply I can easily configure the voltage at 4.0V. My question is: for this setup, do I need a DC-DC Buck Converter as in this one for regulation/step-down (not sure which)?

The lab power supply you linked is serious overkill for your needs. It shouldn't need a separate voltage regulator or buck converter, since I assume that it provdes a voltage and current regulated supply.
A regulated, fixed voltage 4V power supply that can provide 2A is what you want. That will probably cost < 1/10 of the amount of the lab supply you linked. The challenge is to find a 4V supply. (Most regulated power supplies are either 3.3V or 5V, since those are common voltages for solid state electronics.)
That said, the linear voltage regulators are usually adjustable with a decent voltage range using a resistor.
You could always build your own voltage regulator using a linear voltage regulator rated for 2A, plus a resistor and a couple of capacitors. You could either feed it from an unregulated 6V power supply or use a transformer, bridge rectifier, and capacitor to provide an unregulated DC input to a voltage regulator.
Edit:
With a little googling I found a few 4V 2A power supplies online. This one, for example:
https://www.alibaba.com/product-detail/US-AC110-220V-To-DC-4V_62155516966.html?spm=a2700.7724857.normalList.14.a5e64009aUU1ln&s=p
(That link is to a wholesale manufacturer that sells them in volume, but you may be able to find the same supply for single unit sale. A 2A switching 4V supply would meet your needs as well)


HTTPS with ESP8266WebServer? I see many ESP8266HTTPClient examples, pasting in a fingerprint from an outside website, but I want to host an html page from the ESP8266 in AP mode using HTTPS.

Judging by the lack of examples, and the lack of a domain for a cert in AP mode, I'm thinking this is impossible, but would like confirmation before I give up.

Is it impossible to get the browser's green padlock on an AP-served web page?

The ESP8266 just doesn't have sufficient CPU power to do this reliably.

It is possible, since the EPS8266 SDK docs have an "SSL User Manual" which describes this scenario.

In my experience, using the Arduino core for ESP8266, it doesn't work reliably.

Consider using an nginx reverse-proxy and having that proxy handle SSL negotiation. Understand that this is more for situations where the ESP8266 is local, in a network sense, to the nginx proxy, and you consider your WLAN secure enough.

On the plus side, you have room to grow in key sizes and/or complexity.


Exporting ADC data to excel Do I need third party s/w to export to a spreadsheet? I have built a heat flux sensor meter and wish to log my data.

You need some way of getting the data from the Arduino to the PC. There's a number of ways of doing it depending on what resources you have available.

Through serial as CSV

This entails printing the data to the serial port in CSV format then using some software on the PC to capture that and save it to a file. That could be as simple as a good terminal emulator that provides "capture to file" or similar, or you could write your own program in your favourite programming language.  This method is essentially free.

To an SD card

Writing the data as a CSV file onto an SD card directly attached to the Arduino can be quite convenient. It means you can then just take the SD card with the data on it and slip it into your computer to import the data as you would with any other file.  It needs an SD card shield or breakout board attaching to the Arduino

Through the network

If your Arduino has a network connection of some form (WiFi shield, Ethernet shield, etc) you could POST the data to a web page running on your PC and store it in a CSV file for later importing. Probably the most expensive option but it does mean you can do things with the data "live" as it comes in.


Is WiFi traffic encrypted on ESP32? I am using the ESP32 in soft access point mode. In other words I specify my wifi username and password on the ESP32 and I am able to connect to it from my phone.
So I am not using any router or internet connection. Only my phone and the esp32.
If my phone is the only device on the network created by the esp32 do I have to worry about HTTPS? People say HTTP is not secure and I also know how easy it is to see http traffic with Wireshark. But if no one else has access to the network I guess http is secure correct? If no one knows the wifi password will my http requests be encrypted? Moreover, if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted?

If you provide a password for you network, it will be encrypted. Thats the point of the password. When you look at the function description in the WifiAP.cpp file of the Wifi class for the ESP32, the description suggests, that it will be encrypted with WPA2, which is currently the standard in Wifi encryption. (Though that can depend on the actual library, that you are using)

do I have to worry about HTTPS?

That depends on your needs. In IT security is a scale, not a binary. Using HTTP on a WPA2 protected network can be considered safe on the one side and unsafe on the other. You need to thing about, if your project needs that additional layer of encryption through HTTPS.
For example: If you control your Smart Home with that ESP32, which may be able to open your windows or even the door, I would consider that critical. Then I would take every bit of security, that I can get, as there are ways to break into a WPA2 protected wifi network.
An example in the other direction: I'm currently building a game, which gets configured on a smartphone via the Wifi network of an ESP32. The network is encrypted to prevent casual attackers from messing with my current game run, but the project has so low security needs, that I will not bother with HTTPS. It's just a game, that will not that often being used, and the possibility of an attack on it is very low.
So it's about risk assessment (as with all security in IT).

if I connect from my computer instead than my phone via wifi to the ESP32 and send UDP packets will those be encrypted

The mentioned types of encryption (WPA2 and HTTPS) happen on two different layers of the network communication. With WPA2 your complete wifi data of that network is encrypted. So the UDP packet is also encrypted, but only in that wifi network, and it can be read by any authenticated user of the network. HTTPS works in a layer above that, so that your packet would be encrypted, even if it would move out of that Wifi network. For learning more about network layers, refer to the OSI model.

Apart from the security perspective: When you use HTTPS you also need to think about the certificate, that you are using. If you use a self-signed one, your browser will present you a warning about that, everytime you open that site. To prevent that, you either need to trust that certificate on all your devices, or you need to use an officially signed certificate (which might be a problem for a pure local project).


I2C device responding, but data is nacked I'm working on a project where I have to communicate to several devices over I2C using a Genuino 101. Now I'm trying to get data off the bus but wire.available() stays at 0, even though my trace clearly shows there's data being sent.

with the following timings

Because the wire is never available my readbuf will always be empty.
Rdbuf[0] is: 0 Hex is: 0
Rdbuf[1] is: 0 Hex is: 0

I'm using the following code to read from the I2C bus.
void i2cRead(unsigned char device, unsigned char memory, int len, unsigned char * rdBuf) {
  ushort memstart = memory;
  bool available = true;;
  while (len > 0 && available) {
    available = false;
    ushort blockSize;
    /*If the number of bytes is smaller than the block size, read that size*/
    (len < RD_BLCK_SIZE) ? blockSize = len : blockSize = RD_BLCK_SIZE;
    Wire.beginTransmission(static_cast<int>(device));
    //send i2c START command
    Wire.write(memory);
    //Write memory address
    Wire.endTransmission();
    //send i2c STOP command
    Wire.requestFrom(static_cast<int>(device), blockSize,true);
    //Request blockSize bytes from the device
    /* for every byte in the response add that byte to the read buffer */
    while (Wire.available() && (len != 0)) {
      available = true;
      rdBuf[memory - memstart] = Wire.read();
      memory++;
      len--;
    }
  }
}

I'm not quite sure what I'm doing wrong, any help would be much appreciated.
Edit:
Below is an image of the current (minimal) setup. On the left there's the board with the ADC and multiplexer visible.

The third set of wires goes to my protocol analyzer.

You want to get the resulting code working, but you should do small minimal tests.

Start with the i2c scanner.
Connect only one sensor, and if it is detected, add more sensors.

How long are the wires, and what is the value of the pullup resistors ?
Perhaps you have too many modules with sensors, and the total pullup value it too low. The I2C bus is specified for maximum 3mA pull down current.

Do you have a more common 3.3V Arduino board ? For example the Arduino Due or the Arduino Zero ?


Are there any reasons to pick Nano over Micro? Nano is from 2008, and micro from 2012. Micro seems better on every parameter, in particular in having a better (I think) microcontroller, ATMega32u4, over ATMega328P.

However, all the shops I've checked out, both local and online, sell the Nano, and only some sell Micro. And Nano is always more expensive than Micro. E.g. at RS-Online 26GBP for Nano (link) and 16GBP for Micro (link).

Why do many shops only sell the inferior product?

Why is the older and less capable Nano more expensive?

Why would anyone buy the Nano over the Micro?

The main difference between the ATmega32u4 and the ATmega328P is that the 32u4 has onboard USB. When ATmega328P are used in an Arduino they are often coupled with an FTDI USB to serial chip. The FTDI chip is about $5 so this may be where the extra cost comes in.

Having the USB chip separate is actually not a bad thing:

The Atmega328P consumes less power than the ATmega32u4
FTDI chips are common, so the drivers are on most computers, whereas the 32u4 requires an .inf file to be loaded on Windows.
The FTDI chip uses the FTDI vendor and product ID and thus can be used in large-quantity commercial projects whereas the ATmega32u4 would require purchase of a vendor id and product id from the USB group. (My conclusion after reading around the net a bit, please correct if wrong).


Designing a robotic arm using Arduino Uno We are making a robotic arm using Arduino Uno board in which we are not able to decide which kind of motor to use.

Which motor will be better if we want to lift weight up to 1kg using gripper at the ending shaft of arm? Specification of our design is as given below:

4 DOF ARM
Movable vehicle as base weight of 1kg.
Individual length of link 20cm, 20cm, 10cm and after that gripper of 8cm length.

Which kind of motor should we use? DC or Servo?

So you have a total length of your arm of 58cm. The center of mass may be further past the end of the gripper so I am allowing 5cm for that. Total length of 63cm.

Holding torque required just for the load:

Force = mass x acceleration
Torque = Force x radius
Torque = 1kg x 9.8 x 63cm    [in N.cm]
       = 617 N.cm

This is a lot of torque and we haven't factored in the weight of this robot arm.

Some motor datasheets/specifcations:

DC Servo Motors: http://oceancontrols.com.au/datasheet/lea/MOT-2x0_DCM5xxxxd.pdf
Nema 17 stepper motor: http://motion.schneider-electric.com/downloads/datasheets/17_mtr.pdf
Nema 23 stepper motor: http://motion.schneider-electric.com/downloads/quickreference/NEMA23.pdf

Whether you go DC servo motors or stepper motors, you will need to use decent motor drivers hooked up to your Arduino to drive the current needed by the motors.

You will need at least 4 motors for your 4 DOF. Lets assume each gearbox-motor combo weighs 700g. On top of that lets assume that the frame weighs 1kg. Lets assume the center of mass is exactly half way along the arm (ie. 31.5 cm)

Torque = (4 x 0.7 + 1) x 9.8 x 31.5
       = 1173 N.cm

The gripper needs to be decent to hold 1 Kg - so lets assume that it weighs 600 grams. Lets assume the center of mass is exactly in the middle of the gripper (ie. radius = 54 cm)

Torque = 0.6 x 9.8 x 54
       = 318 N.cm

So now lets add the total torque required:

Torque = 617 + 1173 + 318
       = 2108 N.cm
  or 211 kg.cm

The motor closest to the base will need to be the strongest as it needs to provide the most torque. The motors need less torque the further away from the base they are.

If you were to use stepper motors, you will need gearbox assemblies to increase the output torque.  It is even possible to use 2 stepper motors driven in unity to provide double the torque.

If you were to use a stepper motor you will need a motor like this:
http://www.phidgets.com/products.php?category=23&product_id=3334_0

Alternatively, servo motor like this could be used:
http://oceancontrols.com.au/MOT-280.html

Either DC servo motors or stepper motors (with gearboxes) would be OK for this robot arm. I would go with DC servo motors because they are slightly lighter and can handle the torque without needing a gearbox. However the DC servo motor is about 3 times the price of the stepper/gearbox combo.


Unable to compile SimpleTimer code - Exit status 1 I downloaded the SimpleTimer library from the Arduino's library manager and navigated to Arduino Playground website for some sample code for testing - SimpleTimer - Arduino Playground. After copying the following code into the Arduino IDE:

#include <SimpleTimer.h>

// the timer object
SimpleTimer timer;

// a function to be executed periodically
void repeatMe() {
    Serial.print("Uptime (s): ");
    Serial.println(millis() / 1000);
}

void setup() {
    Serial.begin(9600);
    timer.setInterval(1000, repeatMe);
}

void loop() {
    timer.run();
}

I receive the following error:

exit status 1
no matching function for call to 'SimpleTimer::setInterval(int, void (&)())'

Please help me out here as I am doing everything according to the instructions given in the arduino playground page of SimpleTimer.

There are quite a few Arduino libraries called “SimpleTimer”. According
to arduinolibraries.info, the one you get through the
library manager is Alexander Kiryanenko's SimpleTimer. The
one described in Arduino Playground is Marcello Romani's
version. You should try the examples that come with the
specific library you install.


Arduino uno AVR assembly with LEDs I am currently in an introductory assembly language class.
My assignment is to use a sparkfun joystick shield kit to do something with an arduino uno. I figure turning on LEDs is the easiest. We must program it in AVR assembly(note: we have only used nasm assembly all semester).

I don't really know how this needs to be done, but I would like the lights to turn on when a button is pressed (one LED per button). I also want to use the analog pins to have the joystick LEDs fade in and out.

below is the code I have right now, and don't have the equipment to test it.

Am I on the right track, or is it a horrible mess?
The professor was referring to the arduino pins with hex, but I couldn't find a mapping of the pins and their hex values.

Thanks in advance.

.include "/usr/local/include/atmega32u4.def"

        .global  main

        .section .text

main:

        cbi     PortD, 2            ; joystick button
        cbi     PortD, 3            ; right button
        cbi     PortD, 4            ; up button
        cbi     PortD, 5            ; down button
        cbi     PortD, 6            ; left button

        cbi     PortC, 0            ; joystick vertical output
        cbi     PortC, 1            ; joystick horizontal output

        ldi     r16, 0x7c           ; select pins 2-6 for button input mask
        in      ddrd, r16           ; set digital button pins as input
        ldi     r17, 0x03           ; select pins 0 & 1 for joystick input
        in      ddrc, r17           ; set analog joystick pins as input

        ldi     r18, 0x1f           ; select pins 8-12 for button LED output
        out     ddrb, r18           ; set digital button LED pins as output
        ldi     r18, 0x0c           ; select pins 2 & 3 for joystick LED ouput
        out     ddrc, r18           ; set analog joystick LED pins as output

loop:

        ldi     r20, PortD          ; read in from digital pins 0-7
        and     r20, r16            ; apply button input mask
        mov     r20, r20 >> 2       ; shift left twice
        sts     PortB, r20          ; turn on LEDs of pushed buttons

        ldi     r20, PortC          ; read in from analog pins
        and     r20, r17            ; apply joystick input mask
        mov     r20, r20 >> 2       ; shift left twice
        sts     PortC, r20          ; turn on LEDs of joystick movement
        rjmp    loop

Did you know that the Arduino Uno uses the Atmel ATmega328P processor?

using the ADC for analog input in assembly language

You may want to skim through Chapter "24. Analog-to-Digital Converter" of the ATmega328P datasheet.

You may want to read application note "AVR126: ADC of megaAVR in Single Ended Mode" and browse through the corresponding AVR126 example software.
(It's in the C language, but it mentions all the registers you'll need to read the ADC in your assembly language program).
(As you can tell from the ATmega328 datasheet, the ATmega88 has exactly the same ADC as the ATmega328).

"Assembler source code for the conversion of an analogue voltage to an 8-bit-number",
"AVR ASM Introduction: A moron's guide to ADC"
and
"ATmega8 ADC Example"
have a pure assembly language program for reading the ADC on a Atmel AVR chip
-- alas, on a slightly different chip that may have slightly different registers than the ATmega328P.

Good luck!


How do I use interrupt service routines inside libraries and classes? I'm trying to have a millis() timer run to emulate a hardware timer inside a library, but I'm having issues compiling the code. I want the callback (pseudo ISR) to be part of the class, and not use global variables.

I'm using Christensen's / Monk's Timer library, but I'm open to suggestions if there are other better/easier timer libraries out there.

This is what I have so far. It's just an example for me to understand how this might work. I'm sure there are better ways of making an LED blink, but this is just for illustrative purposes.

Compiling gives a bunch of "invalid use of member variables in static functions" errors.

  error: invalid use of member 'Blink::_led_status' in static member function
           int _led_status;

EDIT

After trying to add glue routines as per your other answer I can seem to get one instance working, but adding another stops the first light from blinking, and the second one blinks on and off at the wrong times.

The test library is on github

Blink.h

#ifndef Blink_h
#define Blink_h

#include "Arduino.h"
#include <Timer.h> // https://github.com/JChristensen/Timer/master
    // Timer.h uses millis() instead of built in timers

class Blink {
public:
  Blink (int led_pin, int duration);
  void begin ();
  void updateTimer();

private:
  static void _callbackGlue();
  void _callback();

  static Blink *_instance;
  Timer *_blink_timer;
  int _led_pin;
  int _duration;
  int _led_status;
  int _blink_event;
};
#endif

blink.cpp

#include "Arduino.h"
#include "Blink.h"

Blink *Blink::_instance;

Blink::Blink (int led_pin, int duration) {
  _blink_timer = new Timer();
  _led_status = 0;
  _led_pin = led_pin;
  _duration = duration;
  pinMode(_led_pin, OUTPUT);
  digitalWrite(_led_pin, LOW);
}

void Blink::begin () {
  _blink_event = _blink_timer->every(_duration, _callbackGlue);
  _instance = this;
}

void Blink::_callbackGlue() {
  _instance->_callback();
}

void Blink::_callback() {
  if (_led_status == 0) {
    digitalWrite(_led_pin, HIGH);
    _led_status = 1;
  } else if (_led_status == 1) {
    digitalWrite(_led_pin, LOW);
    _led_status = 0;
  }
}

void Blink::updateTimer() {
  _blink_timer->update();
}

test/test.ino

#include "Blink.h"

Blink first_blink (13, 500);
//Blink second_blink (12, 1000);

void setup() {
  Serial.begin(9600);
  Serial.println("Starting...");
  first_blink.begin();
  //second_blink.begin();
}

void loop() {
  first_blink.updateTimer();
  //second_blink.updateTimer();
}

Nick Gammon's answer is good for one Timer - but now you want two!

OK, then you can take advantage of the Timer Library's context parameter. What's that? If you take a look at the header for every(), you'll see as well as passing in the function to call, you can also pass in another value (called context) to pass back to that function when it fires*. So instead of you remembering just one copy of instance, get each Timer to remember it for you.

  *If you can't see the context parameter in Timer.h, then make sure you're using the v2.1 branch, not master.

So:

Get rid of _instance everywhere.
Change:
static void _callbackGlue();
to
static void _callbackGlue(void *context);
Change:
void Blink::_callbackGlue()
{
_instance->_callback();
}
to
void Blink::_callbackGlue(void *context)
{
((Blink *)context)->_callback();
}
Change:
_blink_event = _blink_timer->every(_duration, _callbackGlue);
to
_blink_event = _blink_timer->every(_duration, _callbackGlue, this);

Note that I've submitted these changes as a Pull Request on your GitHub repo.

Incidentally:

You don't need _blink_timer to be a pointer. Get rid of the *, get rid of the line with new Timer() in it, and replace all your _blink_timer-> with _blink_timer.


Powering LED Strip at both ends shorts my psu? I've got a 200 LEDs strip of sk9822's hooked up to a 5V 8A power supply.
As expected, at full white, there's considerable voltage drop and the far end of the strip turns from white to amber.

I wanted to hook up another set of V+ and GND at the far end of the strip, but doing so trips my psu? The strip blinks full white as a result.

Hooking up ONLY GND or ONLY V+ at the far end significantly improves the drop off where only the middle of the strip turns slightly amber-ish.
But! I do notice a faint buzzing from the PSU if I do this.

Am I doing something wrong here?

Put a diode to every psu cable or just take only one psu but make a connection between the input and the far end eith a cable of more than 0,5 mm^2... Spesker csble or so.

Problem with two psu is: one gives 5,00 Volt,  the other 5,05... And there is s power of 0,05 Volt / 8 Ampere running.

Second problem can be the influrnce of different PSU switching frequencies.
Regards,  Michael


How can I record a push button sequence and store it in an array I have 3 push buttons and I want to record the sequence in which they are pressed in array of size 10,i.e, I want to record 10 values for example {1,1,2,2,3,3,1,1,1,3}. I want to blink an array of 3 LED in the same pattern in which the buttons were pressed. I have two extra push buttons for putting the arduino in record and play modes respectively. If any one can suggest how I can store the values in the array I will really be very thankful. I am also facing the problem because it's very difficult to manage the bouncing of the buttons simultaneously.

You can create an array like this, make it global to easy access it:

int states[10];

And the current index:

int index_state = 0;

And initialize the array (in setup):

for (int n = 0; n < 10; n++)
{
    states[n] = 0; // Unpressed
}

When a new button press should be stored:

states[index_state] = state;

And add one to the index state, if 10 is reached, start over (this means the last 10 are stored).

index_state = (index_state + 1) % 10;

And to check the states you just iterate from index_state.

Hope this helps you get going.

Note this is called a ring buffer.


Are there any alternatives to Tinkercad Circuits that is PC application based instead of web app based? I have been using Tinkercad's Circuits web application to create my Arduino circuits and apply my Arduino code (c++) for testing.

Despite the amazing product they have and the fact it's free, I find myself very disappointed at times.  Don't get me wrong, Tinkercad has a bunch of great products that I use all the time (like "3d Designs").  I just feel like "Circuits" needs work or maybe even a different dirrection.

I have been dealing with some of the following issues...

An extremely slow interface creating my circuit:

I have seen it do a bunch of random things that could use some TLC in the interface.  Sometimes objects get stuck and you have to disconnect them from everything before you can move them.  Sometimes using a breadboard, objects that seem connected to a pinhole does not make a connection and need to be connected to the breadboard using a wire.  There are a bunch of little quarks I see.  None are a show stopper and I can work around them but the slow interface makes me hate dealing with a web app.  It makes me really want a PC app instead.
The lack of support updating the Arduino compiler:

It's a very old version and they are not in a hurry to upgrade it.  I have contacted support a bunch about issues with the compiler not compiling code that works perfectly fine in the Arduino IDE.  Classes need to be defined in a specific way, enums need to be defined in an old way that makes the source look ugly etc.  Also, I have let them know when debugging it's about impossible to find out where your bug is because it does not tell you a line number it had a problem on.  It tries to highlight the line with little success in my tests.  I have suggested to them that maybe they could introduce a new option to choose the compiler version to use for each project this way old designs do not break etc.  I didn't get any feedback on the feedback I submitted.  So I guess that is a no go.
The simulation time:

This is the worst offender by far!  This is the main reason I want to look for different software to replace Tinkercad Circuits.  When simulating code on my circuit design the simulation runs in milliseconds (NOT real-time).  I have my code set to do something in 15 seconds.  Seems like it will happen in no time...  NOPE!  I have to wait about 15 minutes to see the results!!

So back to my original question...  Is there a PC application out there that does the same thing as Tinkercad Circuits?  I want to be able to design an Andrino circuit and then test code with it.

I work with the wokwi Arduino simulator

It is faster
It uses the latest Arduino IDE for compilation
It almost runs in real-time. For example, your job of 15 seconds might get executed at about the 17th or 20th second.

Please give it a try. here are some references

Links: https://wokwi.com and https://wokwi.com/arduino/libraries


Why is the result of this product operation wrong? I had a problem in a program where the result of product is not what it's supposed to be. For example: 775*775 gives 10801 instead of 6006025.

To try to isolate and resolve the problem, I made a simple sketch to test the result of different products. What I found is that if I do the same product in this way: 775/100.00*775/100.00 then multiply the result by 10000 I get the right value: 600625.00

The attached pictures illustrate what I said.

While I can use this solution in my initial program by I still want to do the multiplication directly as more operations means more time.

I would appreciate any help. Thank you.

Integer overflow. You're multiplying an int by an int then assigning it to a long.  Instead if you multiply a long by a long, or an int by a long, or a long by an int, it should work.

unsigned long res = 775L * 775;

The L suffix tells the compiler to treat it as a long, not an int.


how to find find out capacitance using time constant? i'm trying to find out the capacitance value using the time constant of the RC ciruit. so i followed the technique on the below link.

http://www.gammon.com.au/forum/?id=12075

Now, it's working fine.. but still i need wider range so i want to know the full core logic of that program like how the capacitance formula has been derived out in those program?

thanks in advance...

The key concept is this line:

  ... we find the point where the voltage reaches 63.2% ...

The time constant τ is how long it takes for a capacitor to charge up to 63.2% of the supply voltage. That is governed by both the capacitance (C) and the resistance (R). τ=RC. That is one of the basic formulae you should know as an Electronic Engineer.

If you know R (which you do because you chose it at 10KΩ) and you know τ (which you do because you measured it) then you can calculate C (τ/R).

Since τ, C and R are tied together like that it is possible to change the balance of C and R and keep τ the same. For instance, a 10KΩ resistor and a 47nF capacitor would give the same τ as a 1KΩ resistor and a 470nF capacitor. Also the same τ as a 100kΩ resistor and a 4.7nF capacitor.

You can easily change the range without having to change your time measurement system by changing the resistor to give a different scale.


Arduino Mega as a USB device My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?

Thanks,
Alexander

Not directly, no.  You have basically have 4 UARTs on the Mega2560 - one of them (USART0, pins 0&1) is connected to the USB interface chip, and the others are left unassigned for you to use as you like.  It's the USB interface chip that is being seen in your computer as /dev/ttyUSB0, not the UARTs in the Mega2560 chip.

That's not to say that what you are after is not possible - it is perfectly possible, but it will require some clever programming on your part.  You will need to:

Define a protocol that will multiplex 3 streams of serial data through the one USB serial connection
Write a sketch that works with that protocol to direct the incoming data to the right UART ports and multiplex the UART traffic into the protocol stream you have defined
Write software on your computer to perform a similar task - read in data and multiplex it, and read the multiplexed data stream and split it out to three separate destinations.

What the destinations on the PC end can be is a bit of a wooly area.  If you want to make it look like serial ports in /dev then you can use a pty pair, which is a master/slave pair of pseudo TTY devices that you can use to pass data through.  On most Linux systems they are numbered devices in /dev/pts, so /dev/pts/1 would be an example.

The function openpty(...) creates and opens a pty pair for you to use in your program.  You would do that 3 times to make three pairs and each one would be the endpoint to a sub-stream in your multiplexed data.

For instance, here is a bit of code I use to open a pty pair:

struct termios options;
openpty(&_masterfd, &_slavefd, _dev, NULL, NULL);
fcntl(_masterfd, F_SETFL, 0);
tcgetattr(_masterfd, &_savedOptions);
tcgetattr(_masterfd, &options);
cfmakeraw(&options);
options.c_cflag |= (CLOCAL | CREAD);
if (tcsetattr(_masterfd, TCSANOW, &options) != 0) {
    fprintf(stderr, "Can't set up PTY\n");
}

That makes it appear to almost be a serial connection in style.  Of course you don't have the concept of a baud rate over a pty connection, so it will be down to your software to define how you control the baud rate (probably easiest to have it hard coded to the baud rates you need).

In that snippet you talk internally to the _masterfd with normal read() and write() functions as you would any other device or file.  Some other piece of software would open the other end of the pty pair (the _slavefd), the name of which is placed in _dev when the pty pair are opened.  You could use that _dev name to then create a symbolic link to a better named device instead of using the /dev/pts/x name that could change without warning from one run to the next.


Send Keyboard Media Keys with Keyboard Library I have an Arduino Pro Micro (ATMega32u4) that I want to use as an IR receiver for a media PC and need to send codes like Volume Up, Media Home, Play, etc. But when I look up the scan codes for those and send them to Keyboard.press() it just prints out '0' every time.

Any way to send those keyboard commands?

You have to do some tweaks to the usbkeyboard libraries that comes with the IDE.

For a video tutorial, take a look at this:

Arduino Leonardo as a multimedia keyboard

Which uses the information from this site, if you prefer text only:

Arduino Leonardo multimedia keys

The Leonardo and ProMicro both use the ATMega32u4 and should both work with theses tweaks. If you need more functionality than the ones that this tweak gives you, you have to dig down into usb descriptors on usb.org for the commands you need.


using UART bridge module to have serial communication through usb port of arduino nano This can be a silly question but I'm having a trouble with serial communication between arduino nano with other serial device. Please help me to handle it.

I'm currently doing a RF communication project using arduino nano and radio telemetry which is using serial communication. I tried to use SoftwareSerial but unfortunately, every pin is being used on arduino nano to control other extra devices. So I decided to have serial communication via usb port of arduino nano

Firstly, I directly connected rx and tx wire of RF device with D- and D+ of B type mini USB. but it did not work

Secondly, I tried to connect rx and tx wire with arduino nano via UART to USB bridge, cp2102 module. I soldered a female USB - male mini USB wire for this connection. but It did not work. the wiring that I build seems like the picture below.

Did I miss something? It doesn't work theoretically anyway?
Please help
Thank you in advance

This is not possible - USB is not an ambidextrous protocol, rather there are distinct Host and Device roles, and while a few chips can switch-hit between them, the USB interface chips commonly used on Nano-style boards are strictly device only, and therefore cannot communicate with another USB device such as a USB-serial adapter.  There may well even be a duplicate here somewhere of a similar question having been asked before.

What you should probably do is just use the ATmega UART that interfaces to the USB chip, to talk to your external device directly (or through level translation and possibly inversion if it requires that).  The transmit side is no problem, however you will need to give some though to the receive side, as only one thing (the USB chip, or your external device) can drive that ATmega pin at a time.  Many of the official Arduino designs have a resistor there, which lets an external driver dominate over the on-board USB serial chip, but your board may or may not have that - if not, you may need to modify it.

And of course such a scheme requires that you disconnect the external device when uploading a new sketch via bootloader.

Another option would be instead of a traditional USB-serial converter, to use some sort of embedded USB host and have that convert to serial - the Kinetis KL25Z chip does this well, as does its close cousin on the Teensy-LC.  But at that point, you might as well just replace the Arduino Nano with a better chip having more pins, or even the ATmega328PB which has a second hardware UART.


Can I safely integrate 3,3v sensor with 5v Arduino UNO? How? I plan to use Adafruit's RGB sensor with Arduino working as a RGB controller running on 5V. In my location, the 5V-compatible version of the sensor is not available.

There is a 3,3V pin on my Arduino board. Can I use it to power the sensor, or will the data pins (which are rated 5V) still burn it?

The TCS34725 chip uses I2C communication, which arguably would still be compatible with the 5V (http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter)

I am still very new to the electronics, and I don't feel confident enough to build my own level converter, and sadly, no converters advertised on arduino.cc are available in my country (Poland).

If you need I2C the best solution is go for a logic level converter based on BSS138 mosfet or similar. I've used a few and they never let me down. Examples: Sparkfun have this https://www.sparkfun.com/products/12009 and Adafruit http://www.adafruit.com/products/757

if you have also a few transistors available, you can make your own homemade solution till you get something more robust, according to arduino page: https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter

(source: arduino.cc)


Can a KCPI-3101 be replaced with an Arduino? I'm planning to use a KPCI-3101 Keithley with a computer to creat a DAS with a sensor to show the data on computer

can i replace the Card and computer with an Arduino?

An Arduino's ADC cannot sample fast enough to sustain 225ksps over 16 channels. That equates to a total of 3.6Msps.  The Arduino can manage something like 120ksps in total.

That's not to say there aren't microcontrollers that can't do that kind of speed - there are.  The PIC32MZ, for instance, can run at 15Msps (although it's somewhat buggy still) and there are many other microcontrollers.

The main bottleneck though is in the communication between the microcontroller and the computer.  Regardless of the sampling speed of an Arduino the serial interface is too slow for high speed sampling. Even at its practical maximum of around 2Mbps it gives you 200000 bytes per second, which with 2 bytes per sample would be 100ksps maximum throughput, not taking into account any protocol overheads.

So that's where having a PCI card is a big advantage. A 32-bit (or even 64-bit on PCI64) 66MHz direct channel to the CPU means you can shift considerably more data. And having the computer perform DMA access means that smooth data transfers without the CPU needing to be involved can be performed.


Reducing read time for reading DS18B20 temp sensors I have a number of temperature sensors connected up to an Arduino - I've split it into 3 sections, with each section having a 2-4 sensors on it (due to distances).   This works, but the code I'm using would seem to me to be very inefficient - particularly with respect of how long it takes to read all the sensors.

I've got 3 code blocks one after each other (which are modified from some code online) which look as below - save, of-course, for the name of the 1wire class.

// Dallas 1 Wire (Main Area):

 //  ds.reset_search();
 //  delay(250);
  while (ds.search(addr))
  {
    for( i = 0; i < 8; i++) {
      Serial.print(addr[i], HEX);
    }

    if (OneWire::crc8(addr, 7) != addr[7]) {
        Serial.println("CRC is not valid!");
        return;
    }

    ds.reset();
    ds.select(addr);
    ds.write(0x44, 0);        // start conversion, with parasite power on at the end

    delay(1000);     // maybe 750ms is enough, maybe not
    // we might do a ds.depower() here, but the reset will take care of it.

    present = ds.reset();
    ds.select(addr);
    ds.write(0xBE);         // Read Scratchpad

    for ( i = 0; i < 9; i++) {           // we need 9 bytes
      data[i] = ds.read();
    }
    raw = (data[1] << 8) | data[0];
    if (type_s) {
      raw = raw << 3; // 9 bit resolution default
      if (data[7] == 0x10) {
        // "count remain" gives full 12 bit resolution
        raw = (raw & 0xFFF0) + 12 - data[6];
      }
    } else {
      byte cfg = (data[4] & 0x60);
      // at lower res, the low bits are undefined, so let's zero them
      if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
      else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
      else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
      //// default is 12 bit resolution, 750 ms conversion time
    }
    celsius = (float)raw / 16.0;
    Serial.print(":");
    Serial.print(celsius);
    Serial.print(",");
  }

I note that there is a 1000ms delay after each sensor is read, and I'm wondering if I can reduce this to a single 750ms delay for all the sensors.  My initial attempts to do this did not meet with success - but I confess that I can't quite get my head around the ds.reset, ds.select etc - and my initial attempts to do this have all failed.

Is it possible to remove this delay after reading each sensor ?

Doing a search every time is quite inefficient. The search function is for if you don't know the device address - and it takes a while to do. In your case, presumably the addresses will never change. Find the addresses and hard-code them into your code. Or if that isn't practical, store them in EEPROM. And if even that isn't practical find the addresses once in setup.

Next, you need a delay while you take the temperature readings. Why not parallel those up? In a loop, tell all the devices to take a reading. Then wait one second. Then read them all (in another loop). That way the one-second delay is shared between all your sensors.

However from the page Gerben linked:

  And it is NOT possible to run DS1820 sensors on a simple pull-up resistor. During the "Conversion" phase, it needs more power. And there are Application Note discussing this in length.

That suggest that if you are using parasitic power, my suggestion won't work too well (having multiple devices taking readings would make it worse).

I found this code on my disk from a couple of years ago. There don't seem to be any delays between reading sensors. There is a delay at the end of the main loop, mainly to stop spamming the serial monitor.

Notice the comment:

  Call sensors.requestTemperatures() to issue a global temperature request to all devices on the bus

See if that works for you.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <Streaming.h>

// Data wire is plugged into port 10 on the Arduino
const byte ONE_WIRE_BUS = 10;
const byte TEMPERATURE_PRECISION = 10;
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// arrays to hold device addresses
DeviceAddress myThermometer [10];
int deviceCount;

void setup(void)
{

  // start serial port
  Serial.begin (115200);
  Serial << "Dallas Temperature IC Control Library Demo" << endl;

  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial << "Locating devices..." << endl;
  deviceCount = sensors.getDeviceCount();

  Serial << "Found " << deviceCount << " devices." << endl;

  // report parasite power requirements
  Serial << "Parasite power is: " << (sensors.isParasitePowerMode() ? "ON" : "OFF") << endl;

  // method 1: by index

  for (int i = 0; i < deviceCount; i++)
  {
    if (sensors.getAddress(myThermometer [i], i))
    {
      Serial << "Device " << i << " Address: ";
      printAddress(myThermometer [i]);
      Serial << endl;
      sensors.setResolution(myThermometer [i], TEMPERATURE_PRECISION);
    }
    else
      Serial << "Unable to find address for Device " << i << endl;
  }  // end of for loop

}

// function to print a device address
void printAddress(DeviceAddress deviceAddress)
{
  for (uint8_t i = 0; i < 8; i++)
  {
    // zero pad the address if necessary
    if (deviceAddress[i] < 16) Serial.print("0");
    Serial.print(deviceAddress[i], HEX);
  }
}

void loop(void)
{

  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  sensors.requestTemperatures();

  // now get all temperatures
  for (int i = 0; i < deviceCount; i++)
  {
    float tempC = sensors.getTempC(myThermometer [i]);
    if (tempC > -80)
    {
      Serial << "Device " << i << " Temperature: " << tempC << endl;
    }
    else
      Serial << "Unable to find temperature for Device " << i << endl;
  }  // end of for loop

  delay (1000);
}


Arduino thermometer and humidity display with 7 segment LED display I want to use an Arduino Uno, a seven segment LED display (four digits) and the SevSeg library, to see temperature and humidity (alternatively).

First of all I try this code:

  #define COMMON_ANODE 1
  #define COMMON_CATODE 0
  #include "DHT.h"
  #define DHTPIN A5     // pin analogico che legge i dati
  #define DHTTYPE DHT22   // DHT 22  (AM2302)
  #include "SevSeg.h"

  // Crea un'istanza dell'oggetto
  SevSeg sevseg;
  DHT dht(DHTPIN, DHTTYPE);
  unsigned long timer; // the timer
  unsigned long INTERVAL = 5000; // the repeat interval (30 seconds)

  int segA = 6;   // Undicesimo PIN del display 7Segment x 4
  int segB = 2;   // Settimo PIN del display 7Segment x 4
  int segC = 10;  // Quarto PIN del display 7Segment x 4
  int segD = 12;  // Secondo PIN del display 7Segment x 4
  int segE = 13;  // Primo PIN del display 7Segment x 4
  int segF = 5;   // Decimo PIN del display 7Segment x 4
  int segG = 9;   // Quinto PIN del display 7Segment x 4
  int segDP = 11; // Terzo PIN del display 7Segment x 4

  int digit1 = 7; // Dodicesimo PIN - PWM che Accende il primo digit
  int digit2 = 4; // Nono PIN - PWM che Accende il secondo digit
  int digit3 = 3; // Ottavo PIN - PWM che Accende il terzo digit
  int digit4 = 8; // Sesto PIN - PWM che Accende il quarto digit

  void setup()
  {
    dht.begin();
    int numberOfDigits = 4; //Numero di cifre del display

    // Inizializzo i PIN
    sevseg.Begin(COMMON_CATODE,digit1,digit2,digit3,digit4,segA,segB,segC,segD,segE,segF,segG,segDP);
    // Imposto la luminosità (valore da 0 a 100)
    sevseg.Brightness(90);
    timer = millis(); // start timer
  }

  void loop()
  {
    if ((millis()-timer) > INTERVAL) {
      // Reset the timer and get/display the current temperature
      timer += INTERVAL;
      // Leggo dal sensore la temperatura
      float t = dht.readTemperature();
      float h = dht.readHumidity();
      //La converto in un numero intero a 4 cifre
      int a=t*100;
      sevseg.NewNum(a,2);
    }
        sevseg.PrintOutput();
  }

And it works very well!

But I cant see temperature (first) AND humidity (after) and again temperature (first) AND humidity (after)...

I have tried many ways but... nothing!! Can you help me?

You need to maintain a state which tells your program whether you are displaying the temperature or the humidity.  Every time the timer expires you need to change from one state to the other, and then display the relevant value depending on what the state is.

Something like:

bool displaying = false; // false = temperature, true = humidity

void loop() {
    if ((millis()-timer) >= INTERVAL) {
        timer = millis();
        display = !display; // Switch between display values

        if (display) {
            float h = dht.readHumidity();
            sevseg.NewNum(h * 100, 2);
        } else {
            float t = dht.readTemperature();
            sevseg.NewNum(t * 100, 2);
        }
    }
    sevseg.PrintOutput();
}


How to connect a 12V power supply to an RGB LED strip receiving RGB values via Arduino Uno PWM pins? Desired Behaviour

I want to send RGB values from my Arduino Uno PWM pins to an RGB LED strip.

What I've Tried

I've purchased this RGB LED strip and 12V power supply (specs below).

I'm trying to follow this adafruit tutorial but am finding the diagram references unclear.

I've mocked up a diagram but am not sure it would work:

( I haven't used the Vin pin before, so, just to be clear, that is the pin that is connected to the positive line on the breadboard - is that how to transfer the 12V power to the breadboard? )

Questions

01)  Is the above diagram safe and sound?

02)  How do I connect the power supply to the RGB LED strip?

03)  Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

04)  I've seen references to grounding the power source, how do I do that?

05)  Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Printed Text on MOSFET:  IRF520 Y32K BE

MOSFET Datasheet:  Link (IRF520NPbF)

Specifications

RGB LED Strip

LED type:  5050 SMD
Color:  RGB
LED quantity:  300LED
Package:  5 Meter/REEL
Voltage:: 12V DC
Working Power:    14.4W
Working temperature: -20° to 50°
Size: ⌀180mm
Length :  5m
Life Span:    50000+hours
Weight:   0.3kg

Power Supply

Input Voltage: AC 100 - 240V
Output Voltage : DC 12V, 6A
Power : 72 Watts
Connector Size:
External Diameter: 5.5mm
Internal Diameter: 2.5mm

01) Is the above diagram safe and sound?

It looks to be OK, except one thing:

The current you can draw from the Arduino's VIN pin is limited to about 1A. That is a sixth of what your power supply can provide, and the LED strip when everything is on needs more than that (1.2A), so you could run into problems.  The limit is threefold:

The barrel jack itself is rated at up to 1A
There is a protection diode with a limit of 1A
The header pins are rated at up to 1A

And of course the Arduino itself needs to use some of that available 1A.  So you might be better off splicing your LED circuit into the power supply's wire before it enters the Arduino.

  02) How do I connect the power supply to the RGB LED strip?

Power goes in (+) to the common pin of the LED strip and then out of any of the three colour pins that happen to be connected to the ground of the power supply. That is, the ground of the Arduino in your schematic since they are (as they should be) all shared.

  03) Is it ok to keep the Arduino 'powered' by the USB whilst plugged in to the 12V power (so that it can keep sending the RGB values to the LED strip via the PWM pins)?

Yes. There is circuitry on the Arduino that allows both the USB and barrel jack to be plugged in together.

  04) I've seen references to grounding the power source, how do I do that?

That refers to connecting the external power supply's ground and the Arduino's ground together. By using the barrel jack that is all taken care of for you.

  05) Are the MOSFETS I have from the Arduino Uno starter kit sufficient for this task?

Not really.  They are designed to be switched with a higher voltage than the Arduino's IO pins provide.  While they will work, they may cause the LEDs to be dimmer than they should be, or the MOSFETs might get hot.  Basically a MOSFET has a "threshold" voltage range which is the voltage range at which the MOSFET transitions from off to on. That is 2V - 4V for that MOSFET, which while within the range of an IO pin isn't really that great. At 4V the MOSFET still isn't completely on. You may notice from the datasheet that the "R_DS(ON)" value - that is the resistance of the MOSFET when it is on, is measured with the gate voltage at 10V. That is a voltage where the MOSFET is guaranteed to be fully on. Anything less than that and the resistance will be higher causing more losses across the MOSFET.  I could see that instantly from the model number - it starts with "IRF".  There is a specific range from International Rectifier which is designed to be directly driven by an IO pin - these are the "IRL" (for International Rectifier Logic-level) series.  These have their R_DS(ON) values measured typically at a gate voltage of 4.5V and a threshold voltage in the region of 500mV to 1.5V. When directly driving from an Arduino these IRL (or equivalent from other manufacturers) are preferred.


Set clockspeed of Arduino Pro Micro a. k. a. AtMega32u4 Is it possible to change clock speed when running sketch?

Low-power lib drops the current consumption from 20mA to 9.5mA at 8MHz, it is still too much. Is there a way how to set clockspeed (for example) to 1MHz, go to sleep, after interrupt wake up, set clockspeed back to the 8Mhz (for 3v3), do some stuff and then go sleep again?

Thanks

Absolutely. The built-in prescaler can dynamically change the clock speed for most of the systems on the chip (USB still needs to run at full speed in order to operate properly).

#include <avr/power.h>

 ...
clock_prescale_set(clock_div_32);
sleep();
clock_prescale_set(clock_div_1);
 ...

See the datasheet and AVR Libc documentation for more details.


What is RSR 09TI chip? There is a chip on Arduino UNO board which I can not find anything about. It is labeled RSR 09TI. It is placed near other power related components (see the image), but what is its purpose on the board?

I believe that is the dual op-amp that is used for both monitoring VIN to enable/disable the USB power, and as a buffer for the LED on pin 13.

In the schematic it's U1, and is an LM358.


How does measuring angled surfaces using ultrasonic distance sensors affect the readings? I've read online that ultrasonic distance sensors do not work well when measuring surfaces that aren't close to perpendicular to the sensor (read something like 5 degrees from perpendicular).
I was wondering what kind of reading would occur if a surface is say, 10 degrees from perpendicular, or more? Would it give a reading that's close but with a greater amount of error, or would it give completely wacky readings? Is there any way to overcome this? Thanks!
(Visual: Imagine there's a wall at the red line, what would the reading say?)

Speaking form experience: The behavior can be fairly unpredictable and depends on the surrounding objects as well as the texture of the surface.
Ultrasonic distance sensors are just sonars that ping at a higher frequency than humans can hear. They work by bouncing sound off of an object and measuring the amount of time it takes to get back. When an object is slanted or angled away from your sensor, it can deflect the sound rather than bouncing it back toward the sensor, making the object essentially invisible to your sonar. However this can be effected by the texture of the surface.
Rough surfaces can scatter sound, sending it in multiple directions. So an angled rough surface may still be detectable to your ultrasonic distance sensor.
When you get an inacurate reading, one of two things will happen. 1: Your sonar ping will bounce off of a surface, hit another object, and bounce back, returning the distance from your sensor, to the surface to the object.
2: The sound will deflect your sound which will be deflected and absorbed, without returning to your sonar sensor. This will return a distance of infinity or whatever your maximum measurable distance is.
I hope this answers your question!


Mega code not compiling on Wemos Mega board Hi I have some code that I'm trying to port from a Mega 2560 R3 to a Wemos Mega.

#include "SoftPWM.h"
#include ESP8266WiFi.h

// Outputs to PWM & H bridge direction
// PWMs:
// DC_pwm, left_pwm, right_pwm = 3, 4, 5
int pwm_out[] = {3, 4, 5};
const int num_pwm = sizeof(pwm_out) / sizeof(pwm_out[0]);

// H bridge direction control:
// dc_1, dc_2, left_1, left_2, right_1, right_2 = 6, 7, 8, 9, 10, 11
int dir_pins[] = {6, 7, 8, 9, 10, 11};
const int num_dir_pins = sizeof(dir_pins) / sizeof(dir_pins[0]);

// Variable for reading pin inputs
int from_r_pi_pwm = 0;
int from_r_pi_dir = 0;

void setup() {

  // Inputs from Raspberry Pi
  Serial.begin(38400);

  // Set up PWM pins
  SoftPWMBegin();
  for (int i = 0; i < num_pwm; i++)
  {
    SoftPWMSet(pwm_out[i], 0);
  }

  // Set up H bridge direction pins
  for (int i = 0; i < num_dir_pins; i++)
  {
    pinMode(dir_pins[i], OUTPUT);
    digitalWrite(dir_pins[i], LOW);
  }
}

void loop() {

  // Check input from R Pi & send it to the H bridges
  while (Serial.available() < 2){}

  if (Serial.available()) {
      // read the incoming bytes:
      from_r_pi_dir = Serial.read();
      from_r_pi_pwm = Serial.read();
      Serial.print("Serial in: directions - ");
      Serial.print(from_r_pi_dir);
      Serial.print(" PWM - ");
      Serial.print(from_r_pi_pwm);
      Serial.println();
  }

  // Set direcions on H bridges
  for (int i = 0; i < num_dir_pins; i++)
  {
    digitalWrite(dir_pins[i], bitRead(from_r_pi_dir, i));
    Serial.print("pin ");
    Serial.print(dir_pins[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(dir_pins[i]));
    Serial.println();
  }

  // PWM to motors
  for (int i = 0; i < num_pwm; i++)
  {
    analogWrite(pwm_out[i], from_r_pi_pwm);
    Serial.print("pin ");
    Serial.print(pwm_out[i]);
    Serial.print(" : ");
    Serial.print(digitalRead(pwm_out[i]));
    Serial.println();
  }
}

This compiles and runs fine on a Mega & is my go to code for setting up pwm & h bridges.

So when I was playing with WiFi I selected the Wemos R1 board from the programmer & everything worked fine but if I try that with this code I get,

#include <avr/io.h>
                    ^
compilation terminated.

exit status 1 Error compiling for board WeMos D1 R1.

So after a bit of searching I found that I should be selecting Arduino/Genuino Mega 2560 but now the upload keeps timing out,

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
An error occurred while uploading the sketch

Anybody come across this before?

Edit #1:  As per the comment below I tried setting DIP switches 1 & 2 ON and all the rest OFF (I also tried 1, 2, 3 & 4 ON and the rest OFF) but still the same compliation error if I select Wemos board.

If I select the Mega 2560 I get ESP8266WiFi.h: No such file or directory which is a new error!

The Wemos/Mega board and IDE setup is complex and not for the faint hearted. Here is the table for the DIP switch setting:

1=ON  2=ON  3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (ATmega2560<->ESP8266)
1=OFF 2=OFF 3=ON  4=ON  5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=ON  8=OFF (USB<->ESP8266 (Update firmware or sketch))
1=OFF 2=OFF 3=OFF 4=OFF 5=ON  6=ON  7=OFF 8=OFF (USB<->ESP8266 (communication))
1=OFF 2=OFF 3=OFF 4=OFF 5=OFF 6=OFF 7=OFF 8=OFF (All independent)

Table DIP switch Special Solution:

1=ON 2=ON 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <-> ATmega2560<-> ESP8266)
USB converter CH340G connect to RX0/TX0 of ATmega2560
ESP8266 connect to RX3/TX3 of ATmega25

https://arduino-esp8266.readthedocs.io/en/latest/index.html for ESP8266 documentation.

Set the Additional Boards URL to http://arduino.esp8266.com/stable/package_esp8266com_index.json in preferences

Under Tools select Board then Board Manager, then install the esp8266 by ESP8266 Community

The Arduino IDE setup requires understanding what board setting and communication setting to use to build and upload a sketch.

Under Tools select Board then select the "Arduino/Genuino Mega or Mega 2560"

Set the DIP switches on the actual board to 1=OFF 2=OFF 3=ON 4=ON 5=OFF 6=OFF 7=OFF 8=OFF (USB <->ATmega2560)

That was the DIP switch and USB setup.

Ref. https://forum.arduino.cc/index.php?topic=578430.0

The error ESP8266WiFi.h: No such file or directory is easy. The file name should be a string: #include "ESP8266WiFi.h".


What are the main differences between Arduino and mbed? I have been working a lot with the Arduino platform over the last year. Arduino makes it very easy for beginners (in my opinion) to get started and has a large community and a lot of libraries for all kinds of peripherals.

Now, I am considering to have a look at mbed, too.
What are the main differences I would face, both practical and conceptually?

As both an Mbed user and an Arduino user, this is my perspective on the differences between the platforms.

The IDEs are completely different. The Mbed IDE is an in-browser compiler that allows you to easily import other people's source code. It is a full c/c++ IDE that saves your code to your online Mbed account. You must be signed in to do any development work (requires internet access). Code completion exists, but is clunky. Project format more closely mirrors c/c++ programming than does Arduino's environment.
Programming the board is different. The Mbed uses a custom boot loader. The Mbed shows up as a flash drive when you plug it into your computer via USB. You compile your code using the online IDE, download the .hex file, and copy it to the Mbed. It's actually pretty neat, but more time consuming than clicking the 'Upload' button in the Arduino IDE.
The Hardware is different. This means different pinouts, as well as different capabilities. Take a look at the Mbed platforms and compare them to the Arduinos. Mbeds are generally more powerful than Arduinos (cpu speed, mem size, build in capabilities).

I use my Mbed when my Arduino isn't powerful enough or fast enough. It would replace Arduinos for me if it wasn't for the online IDE. The IDE is a little awkward to use, and it takes too long to program the board (downloading/copying and pasting is much more inconvenient).
I'm able to use all my same sensors and peripherals that I purchased for the Arduino with my Mbed (Except for shields due to the physical layout differences). I sometimes have to rewrite code to get it to work on the Mbed, but that's a good learning exercise.


esp8266 esp-01 printing garbage values on serial monitor I am trying to up an esp8266 esp-01. While monitoring the serial monitor it's printing garbage values. I am using arduino-mega to write the code to the esp8266. The sample code i'm trying to write is

#include <ESP8266WiFi.h>
const char* ssid     = "SSID";
const char* password = "PASSWORD";

void setup() {
  Serial.begin(9600);// tried other rates as well
  delay(10);
  Serial.println('\n');

  WiFi.begin(ssid, password);
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }

  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());
}

void loop() { }

Before this I tried to test the esp with a blink program, and it seems working. The connections between esp and arduino are as below

Arduino | ESP
------------------------------------------------------------
3.3V    | VCC(through a button)
3.3V    |CH_PD
TX      | TX
RX      | RX (connected through a voltage divider to arduino)
GPIO 0  | GND (through a push button to GND)
GPIO 2  | 3.3V (through a 1K resistor to 3.3V)

Arduino's the RESET and GND are shorted. What I'm trying to achieve to make the wifi module to act as message que, sending and receiving data to and from a device which is connected to it via internet.

The "garbage values" are most likely messages from the bootloader, output at 74880bps. Try watching its serial out at that speed. You'll probably see messages that look something like:

ets Jan  8 2013,rst cause:2, boot mode:(3,7)
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d

The rst cause number will give you an indication of why the chip rebooted.

The most common reset causes are

power on
hardware watchdog timer
fatal exception (most likely error in your code or power issue)
software watchdog timer
software reset
deep sleep
hardware reset

If it's a "fatal exception", you should see another line that looks like this:

Fatal   exception   (28):
epc1=0x4025bfa6,    epc2=0x00000000,    epc3=0x00000000,    excvaddr=0x0000000f,
depc=0x00000000

Look up the exception number; if it's not obvious what it means, google it to learn about the causes.


Why is function mentioned in global declaration? I came accross this code for writing data into EEPROM in arduino. Why is void printTemp();, void clearEEPROM(); and void writeTemp(); functions are mentioned in global declaration? How will this help?
#include <EEPROM.h>

#define SAMPLE_TIME 2000  //The time between each EEPROM write function call in ms

int tempPin = 0;      //the ADC pin
int printPin = 2;     //the print button pin
int erasePin = 4;    //the erase button pin

int address = 0;      //EEPROM address counter

unsigned long timer;

float conv_coeff = 0.0;   //coefficient for converting from 0-1024 to 0-5 range

void printTemp();
void clearEEPROM();
void writeTemp();

void setup(){
  Serial.begin(115200);     //start the serial connection as always
  conv_coeff = 5.0/1024.0;  //find the coefficient to do the conversion
  timer = millis();         //millis() returns the time since program start in ms
}

void loop(){
  if(millis()-timer > SAMPLE_TIME)  //check if it's time to do a temp sensor sample
  {
    writeTemp();
    timer = millis();
  }

  if(!digitalRead(printPin))  //check if print button is pressed
  {
    printTemp();
    delay(500);
  }

  if(!digitalRead(erasePin)) //check if erase button is pressed
  {
    clearEEPROM();
    delay(500);
  }

  delay(1);
}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    byte value = EEPROM.read(i);                //read EEPROM data at address i
    if(value != 0)                              //skip "empty" addresses
    {
      float temp = value*conv_coeff;            //convert ADC values to temperature
      temp = (temp - 0.5)*100;                  //take care of the offset

      Serial.println(temp);
    }
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  byte value = analogRead(tempPin);     //read sensor value

  EEPROM.write(address, value);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

Those are called function prototypes.  They mean "These functions exist somewhere else".  That "somewhere else" could be later on in the same file, or a different file entirely.

Usually these kind of things are provided by header (.h) files, or are automatically created (for functions in the INO file) by the IDE and hidden from you, so you never really see them. But if you're not using the IDE then you need to have them so your code (which is parsed linearly) knows that these functions exist before the parser comes across them.


Interrupt every second on ATTiny84 (and sleep the rest) I'm building a digital watch just like in this post, except I'm using an ATTiny84. However, the ATTiny84 doesn't have an asynchronous Timer2 like the ATMega328 and does not have a power save mode, so it cannot wake up from the Timer2 interrupt as is suggested in that post.

I need to increment my 'seconds' counter every second, and I need to do it precisely so I don't lose/gain time (so I can't use the watchdog timer which, as I understand, does not use the crystal oscillator but rather its own imprecise clock). I was planning on just keeping the CPU on and using an external crystal, but it seems that that takes a lot of power (~3mA). Even with the SLEEP_MODE_IDLE, I could only get the current draw down to around (~1.2mA).

Like Nick Gammon suggested in that post, I feel like the real solution is to sleep when not changing the counter. Is there any way to wake up after a precise amount of time in the POWER_DOWN or STAND_BY modes?

Is there any way to wake up after a precise amount of time in the
  POWER_DOWN or STAND_BY modes?

I'm afraid not. You will have to use a timer. Since the ATtiny84 does
not have an asynchronous timer, you will have to keep your timer
clocked. This means the clkIO clock domain has to stay
active. Now, take a look at the table “Active Clock Domains and Wake-up
Sources in Different Sleep Modes”, on page 33 of the ATtiny84
datasheet. It shown that “Idle” is the only sleep mode
that keeps this clock domain active.

  Even with the SLEEP_MODE_IDLE, I could only get the current draw
  down to around (~1.2mA).

There are ways to bring this down. First, there is a collection of
functions named power_*_disable() in the avr-libc. You can use
these to power down every single peripheral except the one timer that
you will be using.

Most importantly, you can save power by reducing the clock speed. Since
these devices have extremely little leakage current, the current draw is
roughly proportional to the clock frequency. You can then achieve huge
power savings by drastically reducing that frequency. Obviously, your
processing power will also suffer, but this may not be an issue for a
simple binary clock.

I think the best option for you is to clock your ATtiny84 off a
32.768 kHz watch crystal. See the section
6.2.4 – Low-Frequency Crystal Oscillator in the datasheet.
These crystals can be very accurate, as they are specifically designed
for time keeping. And the frequency is so low that the current draw from
the MCU will likely be negligible compared to whatever other components
are in your clock.

Edit: answering the question in the comment.

  Wouldn't waking from idle still use the watchdog timer though? Or is
  there a way to wake up based on the 32.768 kHz crystal?

As the watchdog timer is way too inaccurate, it is of no use to you.
Instead, you would use either Timer 0 or Timer 1, and configure it to
deliver an interrupt every 32,768 CPU cycles. This interrupt will
be your 1 Hz wakeup source.

You can do this with either timer, in either CTC or fast PWM mode. You
have to configure the prescaler and the TOP value such that

prescaler_factor × (TOP + 1) = 32,768

Then, enable the relevant interrupt, and define the corresponding ISR
that will advance your clock by one second.


Powering Arduino Components with AA in Parallel and Series simulate this circuit – Schematic created using CircuitLab
I have 6 AA batteries that I would love to power my Arduino Nano and HCSR04 ultrasonic sensor. However, for my low power application I want to use the bare minimum power required for the components. Since the Nano can run as low as 4.5 volts and the sensor requires 5 volts, I think the best solution would be 4 AA batteries in series to power the hcsr04 and 3 AA batteries in series to power the nano. Since I have 6 batteries I was thinking 3 AA batteries wired in parallel with 3 AA series batteries. I drew the circuit diagram above and realize something is horribly wrong. So I was hoping someone could point me in the right direction.

Wiring 6 batteries up so it gives you both a stack of 3 and a stack of 4 is not easy, and although you can do it you shouldn't do it.  The only arrangement is this:

simulate this circuit – Schematic created using CircuitLab
(The grey link is optional and makes little difference if it's there or not).
The reason you shouldn't really do that arrangement is that you have a mismatch in your capacities, as [BAT1+BAT2] || [BAT3+BAT4] has more capacity than BAT5, so the current drawn from the 4.5V output will cause BAT5 to go flat far sooner than the others. This will then cause BAT5 to take a reverse charge as current from the other cells flows through it damaging it permanently (especially bad for rechargeable batteries as you will not be able to recharge it, but pretty nasty for alkaline batteries too).
Another consideration when running from different voltages like this is the communication between the different units. If the Arduino is running at a lower voltage the signals it sends out will be of a lower voltage, and it expects to receive signals at a lower voltage. Likewise with the HC-SR04; it will expect to receive higher voltage signals and will send out higher voltage signals. So you will require some logic level translation between the two devices to correct that mismatch in the signal voltages.
As you can see it's all starting to get a little messy now.
A much simpler solution is to keep everything at one voltage. The ideal voltage is 5V since that is the common voltage that all the devices expect to work at.
Since you are running from batteries you want efficiency. To that end you need an efficient solution for generating a stable 5V. The Arduino's built-in regulator is far from efficient, so that can be instantly discounted.
A more efficient solution is a step-down or "buck" switching regulator.  This uses PWM to rapidly turn the power on and off (before then filtering and smoothing it) to effectively convert voltage into current.
You'd run your system off a voltage higher than 5V then use a switching regulator to reduce the voltage down to 5V. Since you have 6 batteries at your disposal the logical voltage would be 6x1.5V = 9V - all 6 batteries in series:

simulate this circuit
If you're running non-rechargeable batteries then you don't need to worry about low-voltage cutoff (you shouldn't over-discharge rechargeable batteries), so this arrangement will get the most out of your battery life. Depending on the "drop out" voltage of the regulator (you can get some with a "zero drop-out bypass" mode) your batteries could get down as far as 0.8V each before the system starts to become unstable (even lower if your HC-SR04 is one of the "upgraded" ones that can run from 3V).


Is there a way to put multiple integers in a method? I'm working on a project that has 3 RGB LEDs. I want to make a simple method that I can call to control the LEDs for example:

showColor(left, 255, 0, 50);

Which would light up the left LED at 100% red, 0% green, and 20% blue. The code I have running for the method is:

 void showColor(int ledPosition, int redIntensity, int blueIntensity, int greenIntensity)
    {
      if (ledPosition == left)
      {
        analogWrite (redPin1, redIntesity);
        analogWrite (greenPin1, greenIntesity);
        analogWrite (bluePin1, blueIntesity);
      }
      else if (ledPosition == middle)
      {
        analogWrite (redPin2, redIntesity);
        analogWrite (greenPin2, greenIntesity);
        analogWrite (bluePin2, blueIntesity);
      }
      else if (ledPosition == right)
      {
        analogWrite (redPin3, redIntesity);
        analogWrite (greenPin3, greenIntesity);
        analogWrite (bluePin3, blueIntesity);
      }
      else if (ledPosition == all)
      {
        for (int index=0, index < 3 ; index++)
        {
          analogWrite (redPins[index], redIntensity);
          analogWrite (greenPins[index], greenIntensity);
          analogWrite (bluePins[index], blueIntensity);
        }
      }
    }

I'm getting tons of errors, like that all of the Intensity variables are not declared and that left, right, all, and middle are not declared. I don't know if this is possible, or what I'm doing wrong. I think I've seen something like this before somewhere else, and I don't want to just use 1 variable to control everything. An answer would be greatly appreciated!

Check your spelling Intensity instead of Intesity.

Consider using switch instead of if-then-else.

Define left, right and middle as [integer] constants somewhere (and probably something more descriptive like rightLED, leftLED and middleLED) because your code is looking for an int, instead you give it something undefined like left, right and middle (and all). I would consider using bitwise operators for identifying the LEDS, instead of a simple integer flag as this gives future flexibility in lighting up combinations without changing your code (the current function would be rewritten to accommodate this).


What does (byte*)variable_name mean in C++? Gentlemen,
  I am a novice C++ programmer, When I was trying to learn how to use EEPROM with Arduino, I came across this statement

  i2c_eeprom_write_page(0x57, 0, (byte *)somedata, sizeof(somedata));

where I need to know what does (byte*) somedata mean?, please let me know if someone know the answer

Regards,

Mr.B

It means "Interpret this pointer as a pointer to byte data".  It's called "Casting" and allows you to fool the compiler into thinking that one type of data is another.

For example, your function expects a byte * (a pointer to byte data), and if you have char * as your variable you can change it on the fly to byte * by casting it like that.


Why does a light bulb activate an infrared sensor? Is there a way I can filter this out? I've made 3 programs. One is written in python, c++ processing and bash.

Everything seems to be okay but then sometimes I get a signal from the arduino that activates the function to lower down the volume on the python code listening for serial data. This is sometimes random but it seems that I can reproduce the same behavior when I turn the light on. I can cause the same disruption if I wave my hands over it quickly.

How can I filter this? I know that IR is part of the electromagnetic spectrum in which the visible light takes part. The sensor is facing upward for a type of omnidirectional receptor. I've placed a TV IR blackish cover over it but with the same results. Do I need to use the function to hash decode the incoming signal? I suppose that it needs a simple circuit as any other sensor.

I want to discard the possibility of a random activation in my code.

Edit:

Taken into consideration the answers until now I can confirm that this is part of a physical phenomena due to the distance between my light and the device.

As for the solution to my volume problem It seems that I used "0" in the same statement as the ir code I remapped in the python code. It turned out to be part of the IRlib library of the arduino code that returns a "0" when it encounters an unknown signal. (due to protocol specification? - out of useful range? )

The thing is that I can change the if statement value for other than "0" but that won't stop it from returning "0" and that's a disadvantage. The solution that came to me is simply intercepting the signal and use continue to skip this.

Is there any alternative to this?

Yes, a light bulb will put out some infrared light.

Decoding remote control signals isn't that hard - there is a tutorial at instructables - http://www.instructables.com/id/The-Easiest-Way-to-Use-Any-IR-Remote-with-Ardiuno/?ALLSTEPS

This also means you can tell the difference between different buttons.

P.S. - when posting in this forum, it helps to include your code and your wiring.


Marlin Firmware troubles:  error I am trying to upload the Marlin Firmware to my 3D printer's Arduino Mega 2560 and I am experiencing a problem. It keeps saying:

qr_solve.cpp:7:18: fatal error: time.h: No such file or directory
 #include <time.h>
                  ^
compilation terminated.
Error compiling.

Please help as I'm lost as how to fix it, because I try to scroll up to see what is highlighted in red and I can't find anything.

From Gerben's link to the googlegroups's thread, Delta robot 3D printers › compiling jcrocholl's Marlin (Ubuntu), as Francis Mallet points out, at the bottom of the thread, it is necessary to change <time.h> to "Time.h":

  I copied the content of the Time library right in the Marlin folder, then changed line 7 of qr_solve.cpp from #include  to #include "Time.h"

  The code compiled and everything seems to be working ok.

So, to iterate, the line in qr_solve.cpp:

#include <time.h>

becomes

#include "Time.h"

Now, Marlin.ino should compile as expected.

Note that the latest version of Marlin, from github.com/MarlinFirmware/Marlin no longer suffers from this issue, but older versions of the software, such as github.com/gpfwestie/kossel_2020_sintron will do, due to line 7, in qr_solve.cpp.


How do voltage and resistance work for two 5v servos when using an external 12v power supply? I have a 12v/1.5 amp barrel plug power supply on my Arduino Uno. I have two servos that say they are rated for 4.8v to 6v, but no amps are specified. When my circuit is configured as it is in this image, it appears to work fine. (In my test sketch, I'm constantly and simultaneously rotating them from 0 - 180 degrees and then in reverse.)

But I don't understand why it works. I assumed the 5v pin can only supply 5v of total power to the whole configuration. Is it instead supplying a regulated 5v at as needed between both servos from a total pool of 12v (presumably up to 10v at once)? Do I need voltage regulation? Shouldn't I have to know the amps for the servo(s) and use some sort of resistance?

Thanks for any information and advice you can share on learning about the concepts underlying a situation like this.

Update: I ultimately modified my approach based on the feedback received here by wiring a separate 5v/2a power supply to the breadboard for the two servos, and wiring the rest of the circuit appropriately (using a common ground, etc.).

Because the supplies of both servos are connected in parallel, they both see the same voltage. Hence there is no "pool", both are being supplied the same 5V.

There is a regulator on the Arduino which reduces the 12V input down to 5V. It does so by burning off the other [7V times however much current is being used] as heat. Since you are supplying it with 1.5A, the most it can supply is in turn 1.5A.


Connecting Arduino Uno to a smartwatch via bluetooth I have a U80 Smartwatch from Bluetooth Watch International, which has bluetooth function. It is meant to be connected via to my smartphone (and it works perfectly).

I also have an Arduino Uno board and a corresponding BLE ZS-040 bluetooth chip.

I need for my smartphone to be able to detect my Arduino board, so I can send data from a simple circuit connected to the Arduino board to the smartphone.

Basically, my circuit is meant to be a simple push button. When the button is pushed, and the circuit is closed, the Arduino board will send a signal to the smartwatch. This will cause the smartwatch to ring and vibrate, as if it is receiving a call. Then to turn off the ringing and vibrating, the user can simply 'answer the phone call', and it will stop.

From what I understand, (I'm very new to Arduino) I have to connect the Arduino board to the smartwatch first, which means I have to somehow get the board to be detected by my watch, which it's not doing yet, eventhough the bluetooth module is connected to the board.

Then the push button needs to send a signal to the watch. Which means the command {if buttonpush='1', send (receiving call)}, so when the button is pushed, the signal is sent and the watch acts as if it is receiving a call. Basically showing all the physical signs (eg. vibrating and/or ringing based on the watch's setting, showing 'answer/deny call', etc.). Btw, the push button is not to be held down. As long is the button is pushed and released once, the signal should be sent, and the watch will buzz until the 'phone call' is answered or denied.

I have absolutely no idea how to get the board connected to the smartwatch via bluetooth.
And while I have a rough idea on the push button circuit I need, I also need to send the signal for the watch to act like it has received a call.

Mainly, I'm looking for any help with coding here. If anyone can help with the physical circuit connections, that would be awesome too.

HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).

The two are not compatible.

You will need a BLE module for the Arduino which is capable of running as a "Central Device".


I have a problem trying to limit motor speed to a certain RPM using a MOSFET trigger switch module I am using the potentiometer to control the duty cycle of a PWM signal to the MOSFET trigger switch module, thus controlling the motor speed.
In my code, I have used the map function to utilize the full resolution of my potentiometer (0 - 1023) and thus create a proportional PWM signal using analogWrite function (0 - 255).
However, in my setup I want to limit the speed of the motor from going beyond a MAX_RPM value, despite any further increase in analog value input from the potentiometer.
This means I have to continously check the RPM value (the RPM code works fine, so I will not include it).
If the motor speed hits the MAX_RPM value, any further potentiometer input should be ignored. To achieve this, I figured I need to hold the analogWrite function value constant thus holding the speed constant.
In the event that I turn the potentiometer in the reverse direction, this should decrease the PWM value thus also decreasing the speed.
I have written the code to achieve the process described above to no avail i.e., increasing potentiometer input causes the speed to go beyond the MAX_RPM value which is undesired.
In this project, I am developing a rev limiter of sorts.
Please help me figure out the problem in my code.
#define MAX_RPM 500
    #define MAX_RPM_PWM_MAPPED_VALUE 15

    //In this case, I first ran the motor while monitoring the speed and the potentiometer value
    //While doing this, I noted the potentiometer value at which the MAX_RPM is obtained
    //I then defined this potentiometer value as MAX_RPM_PWM_MAPPED_VALUE
    //With MAX_RPM_PWM_MAPPED_VALUE, I would directly limit the value written to the analogWrite function
    //

    MOSFETMODULE = 4;
    potentiometer = AO;

    void setup()
    {
        pinMode(MOSFETMODULE, OUTPUT);
    }

    void loop()
    {
        val = analogRead(potentiometer);  //Read potentiometer value - represents accelerator input
        mappedValue = map(val, 0, 1023, 0, 255); //Map the 10 bit value to 8 bit equivalent

        if(RPM >= MAX_RPM)
        {
            analogWrite(MOSFETMODULE, MAX_RPM_PWM_MAPPED_VALUE);
        }
            else
            {
              mappedValue = constrain(mappedValue, 0, MAX_RPM_PWM_MAPPED_VALUE);
              analogWrite(MOSFETMODULE, mappedValue); //Output a PWM signal to the MOSFET trigger module
            }
    }

Your problem is that you don't know what ADC value maps to the maximum RPM. If you did you wouldn't need to know the RPM.
What you have here is a "feedback loop", and what you need is some method of using the detected RPM to control the speed of the motor.
You need to decouple the potentiometer from the analogWrite completely - the potentiometer should be setting the desired RPM, not the value being sent to set the RPM.
So if you want an RPM range from, say, 0 to 100RPM you can map() the analogRead() to the values 0-100. Then you can examine the actual RPM and adjust the value you send to the PWM accordingly - if the motor is too fast then slow it down. If it's too slow then speed it up.
There's a special method that is used for this: PID. And there's a library that does it for you too:

https://playground.arduino.cc/Code/PIDLibrary/

The potentiometer provides the "set point", the RPM detection provides the "input", and the PID library gives you the "output" to feed to the analogWrite().  You need to then provide the special magic "tuning" parameters to give the best control over your motor.


How do I use lambda functions in Arduino? I want to pass a lambda function as an argument to a method. Example:
T reduce(const T initial, const std::function<T(T, T)> acc) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }

    return value;
}

...

int sum = this->reduce(42, [](int acc, int value) { return acc + value; });

If I try to compile this code for Arduino, I get an obvious error:

error: 'function' in namespace 'std' does not name a template type

How can I use a lambda function in Arduino?

std::function is not supported by the Arduino environment.
(Edit: as mentioned by KIIV in a comment, it's supported on ARM
targets, but not on AVR.) You can, however, pass a non-capturing lambda
to a function that expects a plain function pointer. For example, given
T reduce(const T initial, T (*acc)(T, T)) {
    T value = initial;
    for (size_t i = 0; i < S; ++i) {
        value = acc(value, this->values[i]);
    }
    return value;
}

You can call it as
int sum = test.reduce(42, [](int acc, int value){ return acc + value; });

If you want your lambda to capture something, it would seem you are out
of luck...


How to start a dendrometry dimension build (Dimensions of Trees) for research? I am looking to build a device that can measure the dendrometry fluctuations of trees (etc). I essentially want to build this https://publiclab.org/notes/kinasmith/09-09-2016/dendrometers to a t but I don't know where to start. I have admittedly pretty limited knowledge of arduino/microcontrollers and microcontroller kits and sensors.

The measuring principle, that is describe in that link, is quite cool and simple.

The string is wrapped around the tree. One end is connected to a fixed point (here the casing of the sensor). The other end is connected to a spring, which in turn is again connected to a fixed point. As the tree get's bigger, it will pull at the string. At the first side of the string nothing happens (because it is a fixed point). But the end with the spring will move according to the force of the tree. Force and displacement have a linear relationship for a spring (as long as you don't overload it): F = k*x with the force F, the spring constant k and the displacement x.

The displacement of the springs end can be measured with a linear potentiometer. That is just a simple strip of resistive material with a glider, which can be set to any position at the strip. It will create a voltage divider, giving you an analog voltage depending on the position (most potentiometers are linear, but there are also others). Connect both ends of the potentiometer to Vcc (supply voltage) and ground respectively and the glider to an analog pin of the Arduino. Then you can measure the voltage with analogRead().

As jsotola mentioned in his comment: Be sure to use a string, that will not stretch too much, as this will make your measurement less precise.


Is it possible to directly set the registers that control the ADC clock on the Arduino? Is it possible to directly set the registers that control the ADC in an Arduino Yun (micro-controller side is essentially a Arduino Leonardo) from a sketch or is there a specific file somewhere you must edit?

I am working on a project that collects a signal digitizes it and sends it through a digital filter. I looked up the Datasheet for the micro-controller on the Yun and wrote the code setting the registers associated with the ADC portion of the micro controller. The code setting the registers was something like REGNAME = 0x01;. Yet when tested several of the associated registers were unaffected. Pointers on the process to set the ADC manually without using the analogRead() function would be appreciated.

Edit:
My original code looked something like this:

void setup(){
    // register to turn on ADC
    REG1 = REG1 | 0x01;

    //register to set sample rate and set ADC to Free Running Mode
    REG2 = REG2 & 0x30;

    // register to set other settings
    REG3 = REG3 | 0xF1;
}

void loop(){
    // code to take samples from ADC
    // and send them through a digital filter here.
}

I can see no problem with your pseudo-code. You should probably post a
complete testable code in order to get better feedback.

That being said, here are a few suggestions:

You should completely set the ADC registers to the values that suit
your application, instead of just changing a few bits here and there.
This is because you should not care about how the Arduino core
library initializes those registers, especially if this is a
prototype for a final product that will not use Arduino core. For
example, instead of

REG1 = REG1 | 0x01;

you can write something like this:

REG1 = _BV(FOO)   // use foo mode...
     | _BV(BAR);  // ...in the bar setting

where _BV(x) is a macro from avr-libc that expands to (1<<(x)),
   and the bit names are those of the datasheet, for better readability.

You may want to run the digital filter in the ADC interrupt service
routine. If you can split your processing into a fast filter
(processing every sample) and a slow filter (running on decimated
samples), then do only the fast one in the ISR and leave the slow one
to the main loop. I say this from experience: when I tried to do
all the processing in loop() I always lost samples, which did not
happen when I moved the filter to the ISR.
But then, make sure your filter is optimized to be fast. Avoid
floating point operations in the ISR if at all possible.

I have written a program that looks very similar to what you are trying
to do: it samples an analog input at 9.6 kS/s and runs an
homodyne detection
filter in order to extract the signal power in a very narrow band around
1 kHz. The ADC is set to free running mode. In the ADC ISR, I
retrieve the sample, run it through the filter, and store the result
into volatile variables. In loop(), I read these back from time to
time. Here is how I set the ADC:

static void configure_adc()
{
    ADMUX  = _BV(REFS0)  // ref = AVCC
           | _BV(ADLAR)  // left adjust result
           | analog_in;  // input channel
    ADCSRB = 0;          // free running mode
    ADCSRA = _BV(ADEN)   // enable
           | _BV(ADSC)   // start conversion
           | _BV(ADATE)  // auto trigger enable
           | _BV(ADIF)   // clear interrupt flag
           | _BV(ADIE)   // interrupt enable
           | 7;          // prescaler = 128
}

The complete program is available here:
homodyne.ino.
It was initially intended for an Arduino Uno, but it runs unmodified on
a Leonardo clone.


Can you use an Arduino to control the output current and voltage of a DC/DC converter? I am using an arduino to create a device that outputs a specific current and voltage. I was wondering if there are any devices out there such as dc/dc buck boost converters that can be controlled by arduino to output desired powers. I am looking for something rated for at least 50 watts  that can carry at least 3 amps of current.

Thank you all in advance!

Yes, and it's actually far simpler than most realize. I've tried digitpots, but they are quite un-linear and only handle 5v, unless you spend $$$. Early on, i had soldered an LDR in parallel to a buck converter's adjustment pot, and fed that PWM. It worked to somewhat adjust the vout, but had a lot of ripple and was not linear. I had gotten an MCU-controlled linear PSU going, that wasn't too hard, but i always wanted a buck. Just recently, i've found an awesome method and built several MCU-controlled SMPSs.  You don't have to have any special parts or de-solder anything!

Basically, you:

use a buck/boost (or dual) with a built-in V-adj potentiometer.
use a lowpass to convert the MCU's PWM output into a 0-vcc signal.
feed smoothed PWM voltage to a unity gain opamp to buffer available current.
create a common ground between MCU and SMPS.
feed the buffered 0-vcc control through a resistor into the pot's wiper, ~200-1k.
the amount of "injected" voltage will be inversely proportional to the SMPS's output voltage.

Since most SMPS's feedback is in the area of 1-2.5v, the 0-3.3/5v output of the MCU works well to provide or take away feedback from the regulator. The best part about this scheme is that output voltage regulation is maintained by the SMPS's hardware, the MCU just sets an offest. In short, you can set it to 10v via the MCU, attach a big load, and the voltage stays at 10v!

I've used this technique on the xl4005 and the xl4015, but i would imagine it would work for just about any common driver package.