Using Due (SAM3X8E) native USB port for programming? I would like to make my own version of the Arduino Due.

What I can't find the answer to is;
Can I program a blank SAM3X8E using the native USB port from within the Arduino IDE, or do I first need to program some bootloader or similar?

My board will not have the Mega16U2 which is normally used for programming.

The SAM3X8E comes with a bootloader in ROM.

Memories

256 to 512 Kbytes embedded Flash, 128-bit wide access, memory accelerator, dual bank
32 to 100 Kbytes embedded SRAM with dual banks
16 Kbytes ROM with embedded bootloader routines (UART, USB) and IAP routines
Static Memory Controller (SMC): SRAM, NOR, NAND support. NFC with 4 Kbyte RAM buffer and ECC

Since this bootloader does all that the Arduino IDE asks of it, and has a freely available cross-platform command-line upload tool (bossac) the IDE just uses that. No need to invent the wheel when the wheel does everything you need and even comes with a tin of axel grease.

While technically it is possible to use your own bootloader in conjunction with the existing one (use the existing one to install yours, and then use yours to upload sketches) it requires in-depth knowledge of both the chip and GCC linker ("ld") scripts to set aside a block of memory for your bootloader to reside in and relocate the compiled code around it properly. Too much work when the bootloader that already exists does what you want.

However other chips either don't have a bootloader (like the M0 in the Feather) or don't have one that works as desired (like the DFU bootloader in the ATMega32U4) so a custom bootloader is used on those.

The IDE itself is pretty dumb. It just has a configuration file that says "Execute this command with these parameters to upload the HEX file". It neither knows, nor cares, what the bootloader at the other end of the connection is, nor how it works. As long as there is a command-line executable to do the work it just hands over to it.


Arduino acts odd when disconnected from computer I'm building an self-navigating robot with an arduino, an ultrasonic sensor, and two DC motors. I'm currently within the process of coding the robot but I've discovered I have an unusual problem; whenever I run the project via the USB cable operations run fine, however once I take the cable out and run the system on batteries alone performance diminishes.

I have checked the code thoroughly, however I don't understand how this could be an issue that's coding related. I also (as part of the testing) built a basic program which only operated the motors, and was able to run this via USB and via batteries alone with no difference in performance.

So what possible reasons could there be for a drop in performance? I have included a link to a youtube video I had taken of it earlier below to maybe give a better understanding of how performance diminishes:

https://youtu.be/Tp5LtOKBKHw

(Also it could be important to note if I take the cable out while motors are currently moving performance stays at where it should be)

Thanks!

What seems is that you are facing an power shortage while working with on board power supply.
While running DC motors and Arduino on same battery set your Arduino is not getting enough power.

Try switching to a better power supply which can maintain a constant EMF, as eventually you'll always run out of power.
Try an adaptor to use wall socket current.
This way you'll not lose any functionality of Arduino project.


SparkFun ESP8266 find out when on battery power and when charging For one of my projects I use the SparkFun ESP8266 board with an additional LiPo battery in cases power supply goes down.

Now I would like to communicate the power loss - or the fact that the board is running on battery power via WiFi.

Is there a way to find out (in code) when the board switches from mains power to battery and back?

You can implement this software if the voltage is different in both cases.

The voltage from the power supply should be higher than the voltage of the battery, but do not exceed the permissible values.

Then you can use ESP.getVcc() :

  ESP.getVcc() may be used to measure supply voltage. ESP needs to
  reconfigure the ADC at startup in order for this feature to be
  available. Add the following line to the top of your sketch to use
  getVcc:

  ADC_MODE(ADC_VCC);

  TOUT pin has to be disconnected in this mode.

  Note that by default ADC is configured to read from TOUT pin using
  analogRead(A0), and ESP.getVCC() is not available.


A lot of "undefined reference" errors I'm trying to create a program for my robot, but something is not right.
Here's the code:

#include <SPI.h>
#include <Tone.h>
#include <Wire.h>   // standardowa biblioteka Arduino
#include <LiquidCrystal_I2C.h> // dolaczenie pobranej biblioteki I2C dla LCD

//Enums:
enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

enum State
{
    movingForward = 1,
    movingBack = 2,
    turningLeft = 3,
    turningRight = 4,
    doingNothing = 5,
    readyToMove = 6 //Potrzebne?
};

enum SpeedState
{
  slowingDown = 1,
  maxSpeed = 2,
  accelerating = 3,
  notMoving = 4
};

//Classes:
LiquidCrystal_I2C lcd1(0x27, 20, 4);

//Base class for devices
class Device
{
    public:
        virtual void Init() = 0;
};

//STEPPER::
class StepMotor: public Device
{
    public:
        int motorPin;
        int dirPin;
        int sleepPin;

        void Init ( void )
        {
            pinMode(motorPin, OUTPUT);
            pinMode(dirPin, OUTPUT);
            pinMode(sleepPin, OUTPUT);

            toneObject.begin(motorPin);
        }

        void SetSpeed ( int speed )
        {
          toneObject.play(speed);
        }

    private:
      Tone toneObject;
};

//VARIABLES:
int a = 1; //przyspieszenie (przyrost prędkości i jej ubytek przy hamowaniu
int s_accelerating = 1; //droga przyspieszania [mm]
int s_braking = 1;  //droga hamowania [mm]

class Robot
{
    public:
        static float x;
        static float y;
        static float t;
        static State state;
        static SpeedState speedState;
        static int currentSpeed;
};

class MoveOrder
{
  public:
    static Dir direction;
    static int distance;
    static int speed;
    static int distanceRemaining;
    static int distanceMade;
};

//FUNCTIONS:
void SetInterrupt ( void )
{
    noInterrupts();           // disable all interrupts
    TCCR5A = 0;
    TCCR5B = 0;
    TCNT5  = 0;
    OCR5A = 310;            // compare match register 16MHz/256/2Hz   400 okolo 6.4ms  380-6.1ms 300-4.9ms
    TCCR5B |= (1 << WGM12);   // CTC mode
    TCCR5B |= (1 << CS12);    // 256 prescaler
    TIMSK5 |= (1 << OCIE1A);  // enable timer compare interrupt
    interrupts();             // enable all interrupts
}

void SetSpeed ( int speedValue )
{
   //currently empty
}

void setup()
{
    SetInterrupt();
}

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

}

ISR(TIMER5_COMPA_vect)
{
    if (Robot::state != doingNothing)
    {
        if (Robot::state == movingForward || Robot::state == movingBack )
        {
          if (MoveOrder::distanceMade < s_accelerating)
            {

                Robot::currentSpeed += a;

                SetSpeed(4);

            }
        }
    }
}

Compilation returns this:

Arduino:1.6.10 (Windows 10), Płytka:"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_21':

ccU9OfJk.ltrans0.o:(.text+0x812): undefined reference to `Robot::state'

ccU9OfJk.ltrans0.o:(.text+0x816): undefined reference to `Robot::state'

C:\Users\Marcin\AppData\Local\Temp\ccU9OfJk.ltrans0.ltrans.o: In function `__vector_47':

ccU9OfJk.ltrans0.o:(.text+0x820): undefined reference to `MoveOrder::distanceMade'

ccU9OfJk.ltrans0.o:(.text+0x824): undefined reference to `MoveOrder::distanceMade'

ccU9OfJk.ltrans0.o:(.text+0x82e): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x832): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x838): undefined reference to `Robot::currentSpeed'

ccU9OfJk.ltrans0.o:(.text+0x83c): undefined reference to `Robot::currentSpeed'

collect2.exe: error: ld returned 1 exit status

exit status 1

I noticed that when I comment these lines:

        Robot::currentSpeed += a;

        SetSpeed(4);

errors are gone. Why?

Because you have only declared the class static variables; you never defined them.  For the Robot class, you must have:

class Robot
{
    public:
         ...
};

float      Robot::x;
float      Robot::y;
float      Robot::t;
State      Robot::state = doingNothing;
SpeedState Robot::speedState = notMoving;
int        Robot::currentSpeed;

void setup()
{

Ditto for other classes.  (Dangit, Mikael!  :) )


getting started with programming Arduino board in C/embedded c I want to move away from Arduino IDE and start directly working with avrdude. Can anyone tell me some resources and tips on starting and moving forward with using C/embedded C to access more functionality.Would appreciate some help.

Not an exhaustive answer, but one step would be to realize what the Arduino IDE does behind the scenes before it gives your source code to avr-gcc.

From https://github.com/arduino/arduino/wiki/build-process#pre-processing

  The Arduino environment performs a few transformations to your sketch
  before passing it to the avr-gcc compiler:

  All .ino files in the sketch folder (shown in the IDE as tabs with no    extension) are concatenated together, starting with the
  file that    matches the folder name followed by the others in
  alphabetical order,    and the .cpp extension is added to the
  filename.
  If not already    present, #include <Arduino.h> is added to the sketch. This header    file (found in the core folder for the
  currently selected board)    includes all the definitions needed for
  the standard Arduino core.
  Prototypes are generated for all function definitions in .ino files    that don't already have prototypes. In some rare cases
  prototype    generation may fail for some functions. To work around
  this, you can    provide your own prototypes for these functions.
  #line directives are added to make warning or error messages reflect the original sketch layout.

  No pre-processing is done to files in a sketch with any extension
  other than .ino. Additionally, .h files in the sketch are not
  automatically #included from the main sketch file. Further, if you
  want to call functions defined in a .c file from a .cpp file (like
  one generated from your sketch), you'll need to wrap its declarations
  in an extern "C" {} block that is defined only inside of C++ files.

This is handy to know if you are trying to port Arduino sketches to pure avr-gcc.

You'll also want to have the header files that define all the various registers specific to the ATMega328p that is the heart of several of the Arduino boards. They can be downloaded as part of Atmel Studio 7, which also includes avr-gcc and the various other toolchain utilities and scripts necessary.

You'll also want the processor's reference manual or datasheet. At this time, the data sheet is available at https://www.microchip.com/wwwproducts/en/ATmega328P in the "Documents" tab. This will lay out everything you ever need to know about how to use the processor, set up peripherals, rules for the order of commands, names of all the registers, etc.


How does electricity flow in an arduino? :) I know this is probably a really stupid question but I need help. I’m new to arduino and can’t figure out how to arrange my circuits. I have no idea what ground does, where the energy comes from, or how the ground rails work. Any simple explanation would be very appreciated just so I can arrange my own circuits that I make up myself. Thanks!

To expand on JRobert's answer, think of the energy as coming from the +5 pin (assuming an UNO, etc), which is like a water tower as source of pressure.  If you open a valve from the water tower, the water will flow under pressure and fall to the ground.  If you put a water wheel (electrical component) in the path, the flowing water will make it turn.  A good example component for your Arduino experiment is an LED with a resistor connected to one lead (the longer one).  A 1000 ohm resistor is a good choice.  Now connect the other lead of the LED to ground and the other end of the resistor to +5.  If the LED fails to light, reverse the LED connections.
That example didn't include a "valve" (switch) to control the flow, which is what the Arduino does. Instead of connecting to +5, connect the resistor to a digital I/O pin.  Now you can program the Arduino to make that pin an output, and to make it high (digital one, which is +5V) or low (digital zero or 0V) to turn the LED on or off.  Carry on from there!


INA219 with L298N POWER LOGGER I Have been working on a power logger with INA219 and L298N
the thing is, the voltage and current displayed on Serial Monitor is not the same on my multimeter.
the Arduino is connected to the pc to view the result on the serial
#include <Wire.h>
#include <Adafruit_INA219.h>

Adafruit_INA219 ina219;

//Adafruit_INA219 ina219_A;
//Adafruit_INA219 ina219_B(0x41);

void setup(void)
{
  Serial.begin(115200);
  while (!Serial) {
      // will pause Zero, Leonardo, etc until serial console opens
      delay(1);
  }

  uint32_t currentFrequency;

  Serial.println("Hello!");

  if (! ina219.begin()) {
    Serial.println("Failed to find INA219 chip");
    while (1) { delay(10); }
  }
  ina219.setCalibration_32V_1A();

  Serial.println("Measuring voltage and current with INA219 ...");
}

void data(void)
{
  float shuntvoltage = 0;
  float busvoltage = 0;
  float current_mA = 0;
  float loadvoltage = 0;
  float power_mW = 0;
    delay(2000);
  shuntvoltage = ina219.getShuntVoltage_mV();
  busvoltage = ina219.getBusVoltage_V();
  current_mA = ina219.getCurrent_mA();
  power_mW = ina219.getPower_mW();
  loadvoltage = busvoltage + (shuntvoltage / 1000);

  Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
  Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
  Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
  Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
  Serial.print("Power:         "); Serial.print(power_mW); Serial.println(" mW");
  Serial.println("");

  delay(2000);
}

void loop() {

    analogWrite(9, 245); //ENA pin
    digitalWrite(8, HIGH);
    digitalWrite(7, LOW);
    data();
    delay(5000);

    analogWrite(9, 200); //ENA pin
    digitalWrite(8, HIGH);
    digitalWrite(7, LOW);
    data();
    delay(5000);

    analogWrite(9, 150); //ENA pin
    digitalWrite(8, HIGH);
    digitalWrite(7, LOW);
    data();
    delay(5000);

    analogWrite(9, 0); //ENA pin
    digitalWrite(8, LOW);
    digitalWrite(7, LOW);
    data();
    delay(5000);

}

The INA219 gives you the instantaneous current and voltage at a given moment in time, whereas your DMM shows you the average over a period.
The L298N is giving out a PWM waveform that is rapidly being turned on and off.
You see where this is going?
Your Arduino detection will be giving you either full power or no power (or somewhere in between owing to the low-pass filter effect of the motor), pretty much randomly, whereas the DMM will give you the average over a number of samples.
You would need to rapidly sample the PWM signal over a period of time and calculate the average to get an idea of what the current and voltage might be.


How can i stop DC motor when button on remote is released? I am trying to control a motor using a remote with Arduino Mega. The motor turns on when I press the button on the remote but when I release the button, it continues to move. Does anyone know how to stop the motor spinning when I release the button on the remote?

For an infra-red remote control you generally can't. Those don't normally have the concept of button release.

Normally there are two kinds of buttons on a remote:

Burst code
Repeat code

The first sends a short burst of the same code. This allows for a function to be run once per button press.  The second sends the same code over and over again constantly until you release it.

For the repeat code buttons you can use that to your advantage.  You program your Arduino to run the motor for a short period. That period needs to be slightly longer than the time between each code reception. Then it can appear that it's responding to the release of the button.

For example, if your remote sends codes 5 times per second then whenever you receive a code you start the motor. If you haven't received a code for more than say 300ms then stop the motor.


handling array from post data on espwebserver I think I have a supplement question. If irrelevant , then sorry in advance.

I have nested array in post like:  from apache web server page index.php

$_POST['colorsarray'][0] = '#ff0000';
$_POST['colorsarray'][1] = '#2d67ea';
$_POST['colorsarray'][3] = '#7cf325';
$_POST['mode'] = 'none';
$_POST['singlecolour'] = '#ff0000';

Can you suggest me how to assign this array (coloursarray) directly to another array in espwebserver. In other use cases , only the list (length) of array will increase and is not know until the variable arrives from client.

Thanks in advance.

The ability for PHP to do this is special to PHP. The PHP program parses the field names as PHP arrays if they are named thus:

<form ....>
<input name="[colorsarray][0]" value="#ff0000" />
<input name="[colorsarray][1]" value="#2d67ea" />
<input name="[colorsarray][2]" value="#000000" />
<input name="[colorsarray][3]" value="#7cf325" />
[...]
</form>

But since the ESP8266's core doesn't use PHP or understand PHP arrays, you will have to use the literal field name [colorsarray][3], parse it yourself, and determine at run-time the length of the array and how much memory is needed, etc.


Osepp DS1307 RTC program error (tmElements_t tm; does not name a type) Using a basic 1307 SetTime program, and ran into a problem (first time programming a module).

#include <Wire.h>
#include <Time.h>
#include <DS1307RTC.h>

const char *monthName[12] = {
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

tmElements_t tm;

void setup() {
  bool parse=false;
  bool config=false;

  // get the date and time the compiler was run
  if (getDate(__DATE__) && getTime(__TIME__)) {
    parse = true;
    // and configure the RTC with this info
    if (RTC.write(tm)) {
      config = true;
    }
  }

  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor
  delay(200);
  if (parse && config) {
    Serial.print("DS1307 configured Time=");
    Serial.print(__TIME__);
    Serial.print(", Date=");
    Serial.println(__DATE__);
  } else if (parse) {
    Serial.println("DS1307 Communication Error :-{");
    Serial.println("Please check your circuitry");
  } else {
    Serial.print("Could not parse info from the compiler, Time=\"");
    Serial.print(__TIME__);
    Serial.print("\", Date=\"");
    Serial.print(__DATE__);
    Serial.println("\"");
  }
}

void loop() {
}

bool getTime(const char *str)
{
  int Hour, Min, Sec;

  if (sscanf(str, "%d:%d:%d", &Hour, &Min, &Sec) != 3) return false;
  tm.Hour = Hour;
  tm.Minute = Min;
  tm.Second = Sec;
  return true;
}

bool getDate(const char *str)
{
  char Month[12];
  int Day, Year;
  uint8_t monthIndex;

  if (sscanf(str, "%s %d %d", Month, &Day, &Year) != 3) return false;
  for (monthIndex = 0; monthIndex < 12; monthIndex++) {
    if (strcmp(Month, monthName[monthIndex]) == 0) break;
  }
  if (monthIndex >= 12) return false;
  tm.Day = Day;
  tm.Month = monthIndex + 1;
  tm.Year = CalendarYrToTm(Year);
  return true;
}

And I got the following

"tmElements_t tm;" does not name a type.

According to example ReadTest/ReadTest.ino, you have to include

#include <TimeLib.h>

See also comment from Alexander below (unchecked by me) that Time.h needs to be referenced.


Is it possible to use a USB camera with Arduino? It is necessary to recognize the motion and record video live.

Update
Save enough on your memory card.

PS
Maybe I'll repeat the question, but I am not guided in English.
Sorry for my English.

An Arduino is not a powerful processor and can not do much image processing.  I doubt that there is a USB camera that could be connected to the Arduino.

There are a range of OVO cameras that can connect to the Arduino, but I don't think you will be able to record live video on an Arduino with these, where would you store the file for starters?

There is a PIXY camera system, this has its own microprocessor and interfaces with an Arduino.  It can record video and do object recognition.
http://charmedlabs.com/default/pixy-cmucam5/

Hope that helps.


Can multiple Arduinos be connected to a single relay? I have a 16 channel relay that will basically manage 16 different contacts. However, each channel in the relay needs to be controlled by an individual Arduino. So in total I would have 16 different Arduino boards that will each control a single channel in the relay. Is this possible? If so, how do I make the conenctions?
 I tried it earlier using several arduinos and connecting their ground wires together but did not seem to work, the relays remained energized. I am using the SAINSMART 16-Channel 12V Relay Module

Looking at the schematic, here are some points to be kept in mind when using this relay board:

The relay board should be powered through the 12V connector
The relay board has its own 5V regulator
The optocouplers are attached in "reverse"

So, the external connections should be

Connect all the arduino grounds together, and connect them to the board ground
Do not connect any +5V wire together
Connect arduino 1 to IN1, arduino 2 to IN2 and so on
Writing a HIGH value on the INx pin will result in the relay to be de-energized (so contact goes in NC position), writing a LOW value on INx pin energizes the relay (so contact goes in NO position)

If making this connection the board does not work as expected, try to detach all the arduino boards and manually shorting IN1 and +5V, IN1 and GND, IN2 and +5V, ...


Communicating with Arduino Mega 2560 Serial ports through x2 RS232 I am trying to driver a stepper motor using an Arduino Mega 2560. There will ideally be two RS232 signals being read into / written from the Arduino, each using male USB 3.0 connectors; one of these is for configuring and controlling the driver of the motor and the other is simply getting an output torque measurement from a torque meter connected to the motor's shaft. I am simply wondering if Arduino would be able to handle these two functions, and how I might go about connecting each of the two streams of data. I have looked into this question through Arduino documentation, tutorials, and forums for hours, and finally figured I would contribute to the posts on my own.

Thank you!
- a confused college student

Your main problem seems to be confused by all the information. I will give you some more.

The Arduino speaks UART (Universal Asynchronous Receiver Transmitter) with it's Serial interfaces (there are 4 of these on the Mega). This is partly the same protocol as RS232, but it uses TTL logic levels (in this case the levels 5V and 0V), while RS232 has different voltage levels and more lines (like control lines). When you connect your Arduino to a PC, the PC is not directly talking to the Arduinos chip (here the Atmega2560). Instead every Arduino with a USB port has an extra chip. It will handle the (very complex) USB communication, so that you can see an emulated COM port on your PC. The data, that the PC sends to that COM port, get's transmitted over USB to that extra chip, which in turn will convert it to UART signals and send them to the Atmega2560.

All Arduinos, that I know of, have only 1 USB-to-UART chip. But you can add your own USB-to-UART chip to one of the other Serial interfaces. You can use a FTDI chip, an Atmega16U2 or (if you don't want to program an extra chip) simply an USB-to-UART converter cable/module, which you can buy and use directly by just connecting their pins to the Arduinos Serial pins.

By the way, it doesn't really matter here, if you use USB3.0 ports, since chips this small cannot work with speeds that high. All these chips use USB2, more is not necessary, they aren't fast enough.


16x2 LCD showing blocks under text I have a LCD connected to a Arduino Mega 2560 using the instructions in LiquidCrystal library. It is not the first time I am using a 16x2 LCD but I never have encountered a problem like this. When I first connect the Arduino Mega to PC I see a row of blocks in first row of LCD which looks like normal to me. Then after that there is a block of white under each character.

Now I have searched a little and saw whole blocks which was due to bad soldering or bad wiring or etc. I have checked soldering and wiring twice. used 3 different LCD's and 2 different Mega's and it is still the same.

Any suggestions?

These are the images from when I turn it on:

[SOLVED] Update :

Looks like the POT was broken and did not respond the way it used to. So i replaced V0 with a 2.5k resistor and connected them to GND.
Here is the updated image :

The row of white blocks is what you get before the screen's initialized. It's normal.

The shadow behind the characters is because you have the contrast turned up too high. Adjust it down a little.


guidance on Mikrobus NFC tag and connecting to arduino I've recently purchased an NFC tag reader from MikroE and ive been a little lost on connecting the reader to my arduino board.

I've also been looking online for a library that i could use for this device, and have found little to nothing, though i maybe looking in the wrong place. If you could provide any guidance to the matter please respond.

any help would be much appreciated.

link to the tag: https://www.mikroe.com/nfc-tag-click

To find an Arduino library for a device, you can search for the term combination

Arduino github <devicename>

because most libraries are hosted on github. The devicename here means the chip on the product, not the product itself. You won't find much for "Mikrobus NFC", but when you search for the chip on it - the  M24SR64 - you can find some promising results.

For example this library, which looks good to me. It was used for this blog article, which is where I found it (though that is a german site. I just wanted to link as reference for the german speakers). It has some examples, that show the usage of the library.

In general: Sometimes there might be no ready to use library for a chip or product to use with Arduino. In that case you need to write that code yourself. Let's take this product as example. It uses the I2C interface and the seller also links to the datasheet of the used chip. In the datasheet you can read, how the chip is used, including the communication protocol, that is imposes on the I2C interface. You could then write the corresponding I2C code using the Wire library.

Fortunate for you there already is a library, so you can first try that.


Multiple shift registers, 16 bit numbers Currently working on understanding shift registers and traing to display binary number from 65535 to 0 on a 16 LED's.  Below you can see schematics I am using.

The code I am using is

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;
int numberToDisplay=65535;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {

    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay);

    digitalWrite(latchPin, HIGH);
    delay(500);
  }

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 16; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (15 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

Problem is when I change numberToDisplay from 0 to 225, everything works and LEDs are lighted correspondingly (if numberToDisplay=225 all red lights are on). But if numbers are bigger than 225 everything just stops working and nothing lights up.

Thank you in advance

Your problem is entirely that you declare val to be uint8_t, instead of uint16_t. You are truncating your data to 8 bits before displaying it. One other note, the 74HC595 has a maximum total drive current of 50mA. Your circuit will draw around 90mA for each of the 74HC595's if all of the LEDs are on. You may want to change the resistors to something bigger (510 Ohm, for example) to avoid this problem. Of course that will make the LEDs dimmer, so it's a tradeoff. Here's your project in 123D Circuits. You can simulate it in the browser and look at the code running in the Arduino there.


Regain WIFI connectivity I wrote a code to be implemented in a SONOFF device (ESP8266 chip).
My question is regarding disconnection due to failure/ power fail in wifi network - when such event happens, does wifi connectivity try to reconnect or to over come this possibility - should I enter  inside void loop () to verify wifi connectivity ?

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// GPIOs on SONOFF board
int LED_SONOFF = 13;
int REL_SONOFF = 12;
int PIN_SW = 14;

const char* ssid = "Home";
const char* password = "12345678";
const char* mqtt_server = "192.168.2.113";
int last_sw_state = 0;

WiFiClient espClient;
PubSubClient client(espClient);

char msg[50];
const char* clientID = "Sonoff";
char *client_temp = "HomePi/Dvir/Windows/";
const char* outTopic = "HomePi/Dvir/Messages";
const char* outTopic2 = "HomePi/Dvir/Windows/ESP32";
const char* inTopic [strlen(client_temp) + 3];
const char* inTopic2 = "HomePi/Dvir/Windows/All";

String clock;

void start_wifi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  for (int i=0; i<3; i++){
    digitalWrite(LED_SONOFF,LOW);
    delay(50);
    digitalWrite(LED_SONOFF,HIGH);
    delay(50);
  }
}

My question is regarding disconnection due to failure/ power fail in
  wifi network - when such event happens, does wifi connectivity try to
  reconnect or to over come this possibility

use WiFi.setAutoReconnect(true); when initializing WiFi

other useful option is WiFi.setAutoConnect(). It controls if the esp8266 next time starts the WiFi connection with remembered setting, before your sketch starts.


Soldering issue with arduino I am trying to solder arduino nano onto a perfboard/solderable breadboard using rosin core solder. The connection is only working some of the time, when I check with a multimeter (+) at pin 29 (in image below) I and (-) at pin 17 there is power at the top of the pin sticking out of the via/hole but there is 0 volts if I check at the actual joint (lower portion of the pin). I see a little flux residue around pin 29 that could indicate a little burning around the area could that be causing this, it is only very minor .. anyway I can fix it?

Also is it normal  to have a little yellow residue left over on the joints? I am new to soldering so not sure if a little flux reside is a bad thing on the joint...

Fair play, that is a lot of flux residue. I am assuming you are using some quite chunky solder with lots of flux in it.

Flux is non-conductive, so the residue will be forming an insulating layer on the outside of the solder. That doesn't mean the joint is bad, only that you can't get to the joint because the flux residue is in the way.

If there is a conductive path between the tip of the pin and the pad next to it then all is fine. The fact that you can't see the signal through the outside layer of flux is neither here nor there.

If you want to clean it off you can use isopropyl alcohol (AKA PCB cleaner, AKA "rubbing alcohol") and use, for instance, a tooth brush to scrub it off.


Verifiy NTP server update - at start I have function to start an NTP service, right after obtaining wifi connection ( using ESP8266 board ).

from time to time, I get an error saying date and time is01-01-1970... which I assume is due to not reaching the server as intended.

A retry counter was added to give few more retries, but somehow I does not do the trick since I never get the expected message NTP CHECK: # and retry number ( while get an invalid date ).
I know that NTP.begin() returns a bool to describe success/ failure obtaining a NTP server

EDIT1: using NtpClientLib

How can it be done ?

void startNTP() {
        int counter = 0;
        while ( !NTP.begin("pool.ntp.org", 2, true) && counter <=2){
          Serial.print("NTP CHECK: #");
          Serial.println(counter);
          counter +=1;
          delay(1000);
        };
        NTP.setInterval(clockUpdateInt); // in seconds
}

Having read the NTPClientLib code, I would say that the first sync is not even attempted for 1 second after NTP.begin() is called anyway.

You could do this

void startNTP() {
    NTP.begin("pool.ntp.org", 2, true);
    delay(2000); // there seems to be a 1 second delay before first sync will be attempted, delay 2 seconds allows request to be made and received
    int counter = 2;
    while ( !NTP.getLastNtpSync() && counter <=2) {
        Serial.print("NTP CHECK: #");
        Serial.println(counter);
        counter +=1;
        delay(1000);
    };
    NTP.setInterval(clockUpdateInt); // in seconds
}

or, you could do this

void loop() {
    // code that doesn't rely on valid time
    //
    // lets say this bit of code requires sync'd time
    if (NTP.getLastNtpSync()) {
        // this will only run once NTP has been sync'd at least once
    }
    // more code that doesn't require sync'd time
}

Now, you may want to check how long time hasn't been sync'd for in your code and do something if it's been too long


Where is all of the Arduino Documentation? Aside from the main website, I have noticed that it is hard to find documentation for specific Arduino add-ons, such as (This is just one example):
https://www.amazon.com/gp/product/B00OGYXN8C/ref=ppx_yo_dt_b_asin_title_o04_s01?ie=UTF8&psc=1#descriptionAndDetails
Is this fairly normal or are you just expected to "just know what to do" with every Arduino component after a while? I realize that the IDE does have samples, but they don't always help.

I'd like to add to what JRobert said of finding the information the "hard way"(i.e. looking into the datasheet of the chip it used, and understand how it works from schematic).
In the Arduino world, a lot of hardware/shields are so called Open Source Hardware, meaning that many companies can produce the same hardware with the schematic that is released under Open Source hardware license. China happened to be the country where it has the complete value-chain from components, to manufacturing and cheap labour. They are good in producing such products at large quantity and selling at low price, and they are not necessary good in developing original product, and certainly not in documentation (especially in English). These products are not necessary China "knock-off" as many people call it.
Since it is open hardware products, there are multiple vendors producing it and there are many information available on the internet, and take the example you provide, it is "1602 LCD Keypad Shield", and if your google it with this phase, you will soon find this pdf which is not exactly from the same company of your shield, but it is remarkably similar that you can try.
This applied to many hardware/shields that are available in the market. I hope this provide a general guidance and an "easy way" to find the information in your tinkering journey. Of course, if you want to learn more, go dig out the datasheet and schematic as JRobert mentioned.


How can I define a port extender MCP23s17 pin in Arduino My task is to use a port extender (MCP23s17) to drive a touch keypad for which I have to define names of pins so that I can call those names in arguments of a function.

I have searched for different methods to define "PORT EXTENDER" pin but could not find any satisfactory results. Kindly help me handle the situation.

i have used the following libraries downloaded from Arduino playground
1. CapacitiveSensor.h
2. MCP23S17.h
Now I have to use MCP23S17 Pin in the following function

#define key1 2
#define key2 4
CapacitiveSensor cs_4_2=Capacitivesensor(key2,key1);  //capacitive sensor is connected to pin 4 and 2

key1 and key2 are Arduino's pins. I want some method by which I can refer key1 and key2 to the port extender's (MSP23S17) pin. The above answers are surely helpful but they doesn't fulfill my requirement.

Thanks in Advance
Sorry for English.

If you use this arduino library:

#define LED_PIN 15

mcp.pinMode(LED_PIN, LOW); //set led pin on the MCP23S17 to an OUTPUT

mcp.digitalWrite(LED_PIN, LOW)


Run 'Serial.begin(9600)' before loop() My sketch looks somehow like this:

ClassA classA;

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

    classA = ClassA();
    Serial.println("Bar")

    ...
}

void loop() {
    classA.functionFoo();
}

The constructor of ClassA however calls some internal methods that perform a Serial.println().

My problem is, that the first (implicit) call of the constructor of ClassA comes in the first line of the sketch with

ClassA classA;

This is before the Serial interface has been initialized (with Serial.begin(9600)). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.

How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

In order to be sure that your classA object doesn't use the Serial.println() function before the baudrate is defined, it is necessary to add functions in your class ClassA and to inform from setup() your classA object.

The simplest way is to add:

a boolean bool bSerialReadyto keep the status of the Serial object,
in all ClassA constructors, initialize that bSerialReady = false;,
add a function void SetSerialReady() to switch the status bSerialReady = true;. The function should be called in the setup()function just after Serial.begin(9600);,
and in all functions of ClassA, add a if-condition if (bSerialReady) before calling the Serial.println().

Your class ClassA will become:

class ClassA
{
private:
    bool bSerialReady;
public:
    ClassA() {
        // ...
        // Initialize bSerialReady
        bSerialReady = false;
    };
    void SetSerialReady() {
        bSerialReady = true;
    };
};

Your setup() function becomes:

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

And in functions of ClassA, it looks like:

if (bSerialReady) {
    Serial.println("Bar");
}


Blink only one led in a led strip I wish to blink only one led (number two in the strip) bit it does not do so, any idea why and how can I do it?
Code:
#include "FastLED.h"

//Number of LEDs
#define NUM_LEDS 9

//Define our clock and data lines
#define DATA_PIN 11
#define CLOCK_PIN 13

//Create the LED array
CRGB leds[NUM_LEDS];

void setup() {
      FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, BGR>(leds, NUM_LEDS);
      FastLED.setBrightness(5);
}

void loop() {
  leds[0] = CRGB::Blue;
  leds[1] = CRGB::Green;

  //Blink this one only
  leds[2] = CRGB::Red;
  leds[2] = CRGB::Black;
  delay(500);
  leds[2] = CRGB::Red;

  leds[3] = CRGB::White;
  leds[4] = CRGB::Purple;
  leds[5] = CRGB::Green;
  leds[6] = CRGB::Blue;
  leds[7] = CRGB::Yellow;
  leds[8] = CRGB::Red;
  FastLED.show();
}

Everytime, that you want the LEDs to change, you need to call the FastLED.show() function. You are doing that only once after you set the values multiple times. Also you need 2 delays in total (1 for the LED being on, 1 for it being off).
The workflow for blinking an LED would be:
Set LED to on
Call show function
Delay
Set LED to off
Call show function
Delay

You need to translate that to code.


Multiple buttons activating different methods for an LED strip I am trying to use different buttons to activate different methods for an LED strip. However, when one button is pressed after another has been pressed, I want it to interrupt the first buttons method and begin the second. For example: one button sends a rainbow pattern through the LED strip when pressed, however, while it is cycling through the rainbow, the second button is pressed which sends a white cycle through the LED strip. There will be 24 buttons total. I have gotten this to work with 2 buttons but am having trouble getting it to work for a third. The code is below:

     void loop(){

       if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
           stopCycle();
           theaterChaseRainbow(50);
       }
       if (digitalRead(inPin(2)) == HIGH){
           stopCycle();
           theaterChase(strip.Color(127, 127, 127), 50); // White
       }
       if (digitalRead(inPin(3)) == HIGH){
           stopCycle();
           rainbowCycle(0);
       }

     }

     //Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    if (digitalRead (inPin(1)) == LOW) { //checks that other button(s) have not been pressed
      if (digitalRead (inPin(3) == LOW)){
      for (int q=0; q < 3; q++) {
        for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, c);    //turn every third pixel on
        }
        strip.show();

        delay(wait);

        for (int i=0; i < strip.numPixels(); i=i+3) {
          strip.setPixelColor(i+q, 0);        //turn every third pixel off
        }
      }
    }
    }
  }
}

void rainbow(uint8_t wait) {
  int i, j;

  for (j=0; j < 384; j++) {
   if (digitalRead (inPin(2)) == LOW) { // 3 cycles of all 384 colors in the wheel
    if (digitalRead (inPin(3) == LOW)){
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel( (i + j) % 384));
    }
    strip.show();   // write all the pixels out
    delay(wait);
   }
   }
  }
}

uint32_t Wheel(uint16_t WheelPos)
{
  byte r, g, b;
  switch(WheelPos / 128)
  {
    case 0:
      r = 127 - WheelPos % 128;   //Red down
      g = WheelPos % 128;      // Green up
      b = 0;                  //blue off
      break;
    case 1:
      g = 127 - WheelPos % 128;  //green down
      b = WheelPos % 128;      //blue up
      r = 0;                  //red off
      break;
    case 2:
      b = 127 - WheelPos % 128;  //blue down
      r = WheelPos % 128;      //red up
      g = 0;                  //green off
      break;
  }
  return(strip.Color(r,g,b));
}

void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for (j=0; j < 384 * 5; j++) {     // 5 cycles of all 384 colors in the wheel
    if (inPin(1) == LOW) {
      if (inPin(2) == LOW) {
    for (i=0; i < strip.numPixels(); i++) {
      // tricky math! we use each pixel as a fraction of the full 384-color wheel
      // (thats the i / strip.numPixels() part)
      // Then add in j which makes the colors go around per pixel
      // the % 384 is to make the wheel cycle around
      strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) );
    }
    strip.show();   // write all the pixels out
    delay(wait);

      }
    }
  }
}

void stopCycle(){
    int i;
    for (i=0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();   // write all the pixels out
}

Inside each inner loop, just test the switches and return if they are pressed.

eg.

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<100; j++) {  //do 100 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (int i=0; i < strip.numPixels(); i=i+3)
      {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();
      delay(wait);

      // give up if switches pressed
      if (digitalRead (inPin(1)) == HIGH ||
          digitalRead (inPin(2)) == HIGH ||
          digitalRead (inPin(3)) == HIGH )
        return;

      for (int i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

  am having trouble getting it to work for a third

If that doesn't help please explain the nature of this "trouble".

You may need to debounce the switch presses. And you may need to wait for them to release the switch, eg.

 if (digitalRead(inPin(1)) == HIGH && lastState == LOW){//if button has just been pressed
           stopCycle();
           while (digitalRead(inPin(1)) == HIGH)
              {  }   // wait for switch release
           delay (10);  // debounce
           theaterChaseRainbow(50);
       }


DC motor does not work using PWN or Digital pins I have connected pin 3 to a DC motor and using analogWrite and DigitalWrite to try making it start. However, nothing happens.
If I try to move the pin from pin 3 to 5V or 3.3V the motor starts.

Q: What could be the problem since it does not start using pin 3 (or others). I am using HIGH on digitalWrite and 255 on analogWrite.

I just bought a starter kit. It has FREENOVE written on it.
Here is a link to the tutorial and software.

Thanks for any help!

The Tutorial.pdf document that describes the components in the kit does not tell you what the current draw of the motor is. Chapter 10 has 2 tutorials on how to use the motor with a relay or L293D IC. This suggests to me that the motor draws a lot more current than a digital output can provide.

The tutorial using the L293D gives you the ability to vary the speed of the motor using PWM, so it would be a good place to start.

Hopefully pin 3 was not damaged by the excess current flow when the motor was attempted to be powered from it.


Emergency stop button for arduino mega code and circuit attached I am trying to control steppers with pushbuttons and sensors.I want to add one more Pushbutton so that I can press it to stop the circuit and code running if something goes wrong in between.
Below is the code I am using to run the steppers:

int dirpin_T1 = 26;
int dirH_T1 = 28;
int steppin_T1 = 30;
int dirpin_F1 = 5;
int dirH_F1 = 6;
int steppin_F1 = 7;

int PB17ACW = 23;
int PB17ACCW = 22;
int PB17BCW = 25;
int PB17BCCW = 24;

int S01 = 34; // SENSOR INPUTS
int S02 = 35;
int S03 = 36;
int S04 = 37;

void setup()
{
  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);
  pinMode(dirpin_F1, OUTPUT);
  pinMode(dirH_F1 , OUTPUT);
  pinMode(steppin_F1, OUTPUT);

  pinMode(PB17ACW, INPUT_PULLUP);
  pinMode(PB17ACCW, INPUT_PULLUP);
  pinMode(PB17BCW, INPUT_PULLUP);
  pinMode(PB17BCCW, INPUT_PULLUP);

  pinMode(S01, INPUT);
  pinMode(S02, INPUT);
  pinMode(S03, INPUT);
  pinMode(S04, INPUT);
}

void loop()
{
  if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == LOW)
  {
    // STOP MOTOR WHEN NO KEY PRESSED
  }

  // FOR FORWARD ROTATION
  if (digitalRead(PB17ACW) == HIGH &&  digitalRead(PB17ACCW) == LOW )
  {
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }

    digitalWrite(dirpin_F1, LOW );     // Set the direction.
    digitalWrite(dirH_F1, LOW);
    delay(1000);
    do
    {
      digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    } while (digitalRead(S01) == LOW);

    delay(1000);

    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, HIGH);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
  }

  // FOR  BACKWARD ROTATION
  if (digitalRead(PB17ACW) == LOW &&  digitalRead(PB17ACCW) == HIGH)
  {
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
    digitalWrite(dirpin_F1, LOW );     // Set the direction.
    digitalWrite(dirH_F1, HIGH);
    delay(1000);
    do
    {
      digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    } while (digitalRead(S02) == LOW);

    delay(1000);
    digitalWrite(dirpin_T1, LOW );     // Set the direction.
    digitalWrite(dirH_T1, HIGH);
    delay(1000);

    for (int i = 0; i < 32767; i++)     // Iterate for 4000 microsteps.(32767)
    {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
    }
  }
//WANT CODE TO STOP CODE ANYTIME I PRESS STOP BUTTON

}

The best option is to convert the delay() based code to a millis() based state machine. That way the code will never block and always be going through the loop and the place where you check wether that button was hit.

Then when that button is hit you transition to the E_STOP state which turns off all motors until the restart button is hit which goes to recalibrate the position if needed.

A more quick and dirty solution is to replace every every delay with

unsigned long current = millis();
while(milis() - current < delay){
    if(E_Stop()){
        stopped = true;
        return;
    }
}

And add a if check to bail out to every loop.

 for (/*...*/)
  {
    //...
    delayMicroseconds(50);
    if(E_Stop()){
        stopped = true;
        return;
    }
  }

At the start of loop() you then add a

if(stopped){
    //check for restart signal if true recalibrate otherwise return
}


Arduino Uno First Program Please help with this error.
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"

Sketch uses 882 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\.\COM4": Access is denied.

Windows 10 Pro
Arduino UNO ATmeg 328P-PU
Have never been able to Upload a sketch.
Pin 13 and Orange LED blink at 1 second

Welcome to the Stack Exchange and on the Arduino World.

Just a note: Since yesterday there is a new version of Arduino IDE (the last version is now 1.8.11).

When you buy an Arduino, a default sketch is already present. This will blink your LED (pin13) with a 1 second interval. This just mean that your Arduino is working and has a bootloader.

To program it, you need to know which COM port is created for your Arduino module:

Press WIN-'R' (execute application)
Write devmgmt.msc

Check the COM port to see wich COM port was used for your Arduino.

This is the only cause, the message could appear if you use a standard USB-cable connected to your standard Arduino UNO board.


Maximum power rating for Arduino UNO revision 2 (SMD) I have located the 5V voltage regulator chip on my Arduino board which I am hoping to use to power an attached device (which draws up to 500 mA at 5V).  The chip is next to the plug for the external voltage supply.  It says: ON RUX 117-5.  It looks like it's in a SOT−223 package (body about 6.1 by 3.4mm).

I used this page to shows 3 different possible voltage regulators from ON Semiconductors: https://www.mouser.co.uk/ON-Semiconductor/Semiconductors/Power-Management-ICs/Voltage-Regulators-Voltage-Controllers/LDO-Voltage-Regulators/_/N-5cgac?P=1z0wa29Z1z0xwtvZ1z0zlrjZ1ywvc7yZ1yxz1yoZ1ywvc5z

This gives two unique data sheets for NCP1117LP and NCP1117, NCV1117.  But this is where I'm stuck.  They look pretty similar but not exactly the same data sheets.  Also I don't know what RUX stands for, perhaps this is important in figuring out what power rating the Arduino 5V line has.
Additionally the mouser.co.uk site says they're in SOT-223-3 packages but then gives dimensions which a) aren't the dimensions of the chip I have and b) are the dimensions of the SOT-223-4 package (6.3mm wide instead of the ~6.1 mm I have).

I don't care about the dimensions but I would like to correctly identify the chip on the Arduino board to be able to know what power I can draw from it before it shuts itself down.

The Arduno UNO SMD R2 uses an MCP33269 not an LM1117.  What you have is probably some cheap Chinese clone of the Arduino, and in that case the regulator will be the cheapest Chinese copy of the LM1117 available.  It's impossible to tell what the specs of that specific chip are.  Suffice it to say, though, that the specs of the chip are pretty much irrelevant since they rely on good heatsinking, which you most certainly don't have on a little Arduino board.

500mA, though, is a lot to push through a linear regulator like that, and when running from batteries the excess power loss imposed by the regulator will be a major factor in longevity.

You are better off investing in a proper switching regulator (such as a UBEC from a model aircraft supplier like Hobbyking).


Arduino or Raspberry? Self Balancing robot Here's another one, as you probably have seen before.

I'm finishing college, and I'd like, base of my subscription to be a self balancing robot that can send data to a screen. What kind of data? I am in the brain-storming zone with this question and so far I have:

Distance to other objects
Time, temperature, direction N-S-W-E, pressure (as in a car where you measure oil temp, tire pressure etc)
State of balance (as on y axix, a point going from -y to y where 0 is the balance point)
Any othet possible inte-[deleted]-resting thing you could get as a response from a little two-wheels robot
Remote control via wireless preferably

Now, the big question. Is arduino the best choice, or should I consider Raspberry Pi?

Thanks in advance!

This depends on the type of screen you want to interface. An Arduino UNO can with big effort interface a VGA signal with very low resolution and only few colors. Better are little screens (like small OLED screens or small LCD displays with integrated controller). Using a more capable Arduino (like the Mega) can extent the capabilities of your project. The RaspberryPi has of course big display capabilities (like 1080p over HDMI).

There is also another side to the problem: A self balancing robot needs to control its motors very fast (changing the direction fastly depending in sensor input). A RaspberryPi is in principle a computer, not a microcontroller. Programs in it don't have a garanteed time of execution, so especially under high load the program might have to wait for its turn, effectively destabilizing the robot. For these real time fast applications a simple microcontroller is fitted better.

Since you also want wireless control you might be interested in using an ESP (WLAN) as a microcontroller.

All in all you should use a microcontroller for driving the balancing logic and motor control. Depending in your needs you can either use only this microcontroller to do all the other things too or connect another board as a master (eg over I2C vor SPI) which tells the microcontroller what to do. For this a raspberryPi is good.

If you provide more information about the concrete target capabilities you might get a better answer. The scope of your project is too open for clear answers.


Testing Logic Gates using Arduino hello guys is there someone who can help me with my first project.
its basically about logic circuits.

by using tact switch and pull-up resistor to set the values to logical 1 or 0.
the output can be verified by using a LED as an indicator.
so the code goes like this:

//AND GATE
int pin2=1;         //set pin2=1
int pin3=1;         //set pin3=1

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)            //turn led on pin11 when pin2 =1
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)          ////turn led on pin12 when pin3 =1
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF AND

  if(pin2 && pin3)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

//OR GATE
int pin2=1;
int pin3=1;

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF OR

  if(pin2 || pin3)
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

//NAND GATE
int pin2=1;
int pin3=1;

void setup()
{
pinMode(2,INPUT);
pinMode(3,INPUT);
pinMode(4,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
}
void loop()
{
  pin2=digitalRead(2);
  pin3=digitalRead(3);

 if(pin2==1)
 {
 digitalWrite(11,HIGH);
 }
 else
 {
 digitalWrite(11,LOW);
 }

 if(pin3==1)
 {
   digitalWrite(12,HIGH);
 }
 else
 {
   digitalWrite(12,LOW);
 }

//TRUTH TABLE OF NAND

  if(!(pin2 && pin3))
  {
    digitalWrite(4,HIGH);
  }
  else
  {
  digitalWrite(4,LOW);
  }
}

can you guys help me to run this in one sketch by using tact switch  to select the logic gate to be tested or run? thank you in advance

For simulating different gates with the same program, an option is to
use the serial port to tell it what gate you want it to simulate. Here I
am also using a function pointer (called gate) to represent the
selected gate:

/* Wiring. */
const int inputA    = 2;
const int inputB    = 3;
const int outputA   = 11;
const int outputB   = 12;
const int outputRes = 4;

void setup()
{
    pinMode(inputA,    INPUT_PULLUP);
    pinMode(inputB,    INPUT_PULLUP);
    pinMode(outputA,   OUTPUT);
    pinMode(outputB,   OUTPUT);
    pinMode(outputRes, OUTPUT);
    Serial.begin(9600);
    Serial.println(F("Type 'a'(for AND), 'o' (OR) or 'n' (NAND)."));
}

/* Available gates. */
bool AND(bool a, bool b)  { return a && b; }
bool OR(bool a, bool b)   { return a || b; }
bool NAND(bool a, bool b) { return !(a && b); }

/* The gate we want to test. */
bool (*gate)(bool a, bool b) = AND;

void loop()
{
    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    digitalWrite(outputRes, gate(a, b));
}

Here is another version, that uses an enum instead of a function
pointer to identify the gate. The constants and the setup() are the
same as before, then:

void loop()
{
    // The gate we want to test.
    static enum { AND, OR, NAND } gate;

    // Select the gate through the serial port.
    switch (Serial.read()) {
        case 'a': gate = AND;  Serial.println("AND");  break;
        case 'o': gate = OR;   Serial.println("OR");   break;
        case 'n': gate = NAND; Serial.println("NAND"); break;
    }

    // Simulate the gate.
    bool a = !digitalRead(inputA);  // input is in negative logic
    bool b = !digitalRead(inputB);
    digitalWrite(outputA, a);
    digitalWrite(outputB, b);
    bool res = false;
    switch (gate) {
        case AND:  res = a && b;    break;
        case OR:   res = a || b;    break;
        case NAND: res = !(a && b); break;
    }
    digitalWrite(outputRes, res);
}


Store values in array I'm trying to implement the "BNO055 9 Axes Motion Shield".
There is an existing Arduino sketch GitHub that reads out the Euler data, I changed it a bit to print out quaternion data.

#include "NAxisMotion.h"        //Contains the bridge code between the API and the Arduino Environment
#include <Wire.h>

NAxisMotion mySensor;         //Object that for the sensor
unsigned long lastStreamTime = 0;     //To store the last streamed time stamp
const int streamPeriod = 20;          //To stream at 50Hz without using additional timers (time period(ms) =1000/frequency(Hz))

void setup() //This code is executed once
{
  //Peripheral Initialization
  Serial.begin(115200);           //Initialize the Serial Port to view information on the Serial Monitor
  I2C.begin();                    //Initialize I2C communication to the let the library communicate with the sensor.
  //Sensor Initialization
  mySensor.initSensor();          //The I2C Address can be changed here inside this function in the library
  mySensor.setOperationMode(OPERATION_MODE_NDOF);   //Can be configured to other operation modes as desired
  mySensor.setUpdateMode(MANUAL);   //The default is AUTO. Changing to MANUAL requires calling the relevant update functions prior to calling the read functions
  //Setting to MANUAL requires fewer reads to the sensor
}

void loop() //This code is looped forever
{
  if ((millis() - lastStreamTime) >= streamPeriod)
  {
    lastStreamTime = millis();
    mySensor.updateQuat();        //Update the Quat data into the structure of the object
    mySensor.updateCalibStatus();  //Update the Calibration Status

    Serial.print("Time: ");
    Serial.print(lastStreamTime);
    Serial.print("ms ");

    Serial.print(" W: ");
    Serial.print(mySensor.readQuatW());

    Serial.print(" X: ");
    Serial.print(mySensor.readQuatX());

    Serial.print(" Y: ");
    Serial.print(mySensor.readQuatY());

    Serial.print(" Z: ");
    Serial.print(mySensor.readQuatZ());

    Serial.println();
  }
}

Here is a snippet of the "NAxisMotion.h" header file:

    /*******************************************************************************************
    *Description: This function is used to return the w-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    W-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatW(void);

    /*******************************************************************************************
    *Description: This function is used to return the x-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    X-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatX(void);

    /*******************************************************************************************
    *Description: This function is used to return the y-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Y-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatY(void);

    /*******************************************************************************************
    *Description: This function is used to return the z-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Z-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatZ(void);

I understand that the output data type is signed integer, but what syntax do I need to use to store them in an array?
Because it seems the only way to access them is through "mySensor.readQuatX()"

If I understand correctly you want to store a number of signed integers in an array.  Arrays have fixed sizes so you need to know the number of values you want to store.

// Global declarations
enum QIndex {WAxis, XAxis, YAxi, ZAxis, MaxIndex};
int16_t qData[MaxValues] = {0};

// Code inside loop
qData[WAxis] = readQuatW();
qData[XAxis] = readQuatX();
qData[YAxis] = readQuatY();
qData[ZAxis] = readQuatZ();

// Pass the array  of values to another function with the declaration
// void SomeFunction (int *ar);
// or
// void SomeFunction (int ar[]);
SomeFunction (qData);

Is that what you mean?


GPS Module don't provide full data I connected my gps module (NEO-6M) with esp32doit-devkit-v1 board. The module provided data but many data are missing.

My pin configuration:

GPS ------- ESP32
VCC ------- 3v3
GND ------- GND
TX -------- RX2 (pin 16)
RX -------- TX2 (pin 17)

Baud Rate: 9600

My code:

#include <Arduino.h>
#include <TinyGPS++.h>

#define TXD2 17
#define RXD2 16

TinyGPSPlus gps;

void setup()
{
  Serial.begin(115200);
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  Serial.println("Started......");
}

void loop()
{
  while (Serial2.available())
  {
    Serial.write(Serial2.read());
    // gps.encode(Serial2.read());
    // if (gps.location.isValid())
    // {
    //   Serial.print("Latitude= ");
    //   Serial.print(gps.location.lat(), 6);
    //   Serial.print(" Longitude= ");
    //   Serial.println(gps.location.lng(), 6);
    // }
  }
}

OUTPUT

GPS seems to be working and informing you that you have no signal.  Usually happens inside buildings, when far from a window or when antenna isnt properly connected.

Testing out of doors is many times not possible, so try placing your antenna next to a window with a partial view of the sky.  Wait for a couple of minutes until you get a fix on 4 or 5 satellites.


ESP32: best way to embed certificates I'm using the Arduino framework on an ESP32 based board. The board has an SD card slot, but I'm not going to use it.
Anyway, I need to store somewhere the certificates. To the the firmware I've just hardcoded them into the code:
const char *rootCABuff = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\n" \
...
"hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq\n" \
"-----END CERTIFICATE-----\n";

const char certificateBuff[] = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIDWTCCAkGgAwIBAgIUZXjPNnJFXMntXOki9BT+QmDFciUwDQYJKoZIhvcNAQEL\n" \
...
"gGXtqlgPnenkZPTaBr9c8o+WjgQXFLM+Jwnw3/53dUI9zBcybTaptI63o3Ct\n" \
"-----END CERTIFICATE-----\n";

const char privateKeyBuff[] = \
"-----BEGIN RSA PRIVATE KEY-----\n" \
"MIIEpAIBAAKCAQEAuuKsFy98/xsJclnWo0d+qm8KImLEILB64BbH7WaYi3NnznLg\n" \
...
"uHfBLQQDrA0HDRvYpAUNw/b2H4dpUK/nGM4FFVMP7V8RM2t2923nhQ==\n" \
"-----END RSA PRIVATE KEY-----\n";

Of course this is not suitable for production where each unit will have a different set of certificates.
So wonder what is the best way to store them.
The obviously idea is into flash. So I tried to enhance my settings class, based upon the Preferences library. In the official documentation I read:

String values are currently limited to 4000 bytes. This includes the null terminator. Blob values are limited to 508000 bytes or 97.6% of the partition size - 4000 bytes, whichever is lower.

But if I do something like this:
Preferences prefs;
prefs.begin("settings", false);
Serial.println(prefs.freeEntries());

it return 460, even if I still have plenty of flash:
Flash: [=======   ]  73.8% (used 967234 bytes from 1310720 bytes)

Is there another library more suitable to store such a data that can be used with Preferences?

I don't know what you need that Preferences thing for, but I would use SPIFFS/FAT anyway. Simply store the certificate in a file in flash and read that file when you need it. The required space is no problem as you can choose the size for file system in the partition table and also you can upload the file (there is a plugin in the arduino IDE for this purpose) after flashing the firmware, so having different certificates on individual devices is no problem.
I saw that you tagged the question with 'eeprom': the esp has no eeprom but emulates it with a blob in flash, so using any flash library is just as fine. The esp also supports wear-leveling, which makes using flash an even better option as the dedicated eeprom-partition, which was used in an older version of the sdk, would wear out orherwise. The "eeprom" is just there to be consistent with the use of other arduino's eeproms.


TCCR1A and TCCR2A on Leonardo I'm trying to use the TTS library for Arduino on an Arduino Micro board, which is based on the Leonardo. When I try to compile my sketch I get some errors;

/libraries/TTS/TTS.cpp: In function 'void soundOff()':
/libraries/TTS/TTS.cpp:355: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:355: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void soundOn()':
/libraries/TTS/TTS.cpp:382: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'WGM20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'TCCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'CS20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'WGM22' was not declared in this scope
/libraries/TTS/TTS.cpp:384: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:385: error: 'TCNT2' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void sound(byte)':
/libraries/TTS/TTS.cpp:424: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:425: error: 'TCNT2' was not declared in this scope

Googling revealed that the Leonardo uses different timers. And other things I don't understand! But I couldn't piece together an answer beyond that.

What are the correct constants to use for Leonardo boards, and is there a way I can update the library to work across both?

Apparently the library in the OP's link has been updated to support the Leonardo, so this problem should now be solved.


How do I connect a vibration motor to Arduino? I'm trying to figure out how to connect a vibration motor to my Arduino.  I've come across this resource and it seems pretty straightforward though for a while my eye glazed over at how complicated the circuit was (do I really need all of that to run my vibration motor?).

My real question is that I have a vibration motor similar to the picture in the link and I'm trying to figure out how to actually connect it to my breadboard.  Do I have to solder wires onto those flimsy ends or is that a better way to get this to work?

Thanks!

Lets break down the circuit and have a look why everything in that circuit is there and what it does.

First we have the 33R resistor before the motor which limits the current to the motor. This particular motor is rated at 75mA and has a starting of 85mA. The 33R resistor limits the current to 130mA maximum through the motor. If the risk of the motor pulling too much current is an issue then stick a fuse in-line

Then there's the motor, not much to say here really. It's whatever motor you're using.

We then have both a diode and a capacitor across the motor. I find this a bit strange, I've seen the use of flyback diodes, I've seen the use of snubbers, but both? The purpose of the diode is to allow a return path for any spikes caused by switching off power to the inductive load (the motor) which stops them from damaging the transistor. For the capacitor, just remove it, it's not got any use here really.

Then comes the transistor, it might be easier to think of a transistor as a switch (especially in this example). When you put a little bit of current on the base, the transistor 'opens' allowing the motor to connect to ground. The reason we have to use a transistor is because the outputs of an arduino are only able to supply a maximum of 40mA, we need more than that to run our motor. Fortunately, the transistor is not going to need any more than 5mA on it's base which is why we use it to 'switch in' components that require more voltage/current. The 1K resistor on the base is to limit the current coming from the arduino and preventing it from killing our poor transistor.

tl;dr - You need everything except the capacitor


I2C Scanner - No devices found I connected an OLED display to SDA and SCL Pins of Arduino UNO. However, I cannot find the adress by using the Arduino I2C Scanner.
All of the wires are connected correctly and the display has power. What else could be the problem?
Edit:

Have you used the pull-up resistors SCL and SDA need to be pull uped using 5V. Try this and check if it is working have you connected SCL to A5 and SDA to A4


Control 2 ESC with a potentiometer with arduino I have 2 ESC (electronic speed controller) which control these brushless motors: Hobbyking Donkey ST3511 Brushless Motor

I would like to make them work with a poentiometer, under arduino.

I have a program but it only works with one engine. Here is the program :

#include <Servo.h>//Using servo library to control ESC

Servo esc;
Servo esc2;
//Creating a servo class with name as esc

void setup()

{

esc.attach(9); //Specify the esc signal pin,Here as D8

esc.writeMicroseconds(1000); //initialize the signal to 1000

Serial.begin(9600);

esc2.attach(9); //Specify the esc signal pin,Here as D8

esc2.writeMicroseconds(1000); //initialize the signal to 1000

Serial.begin(9600);

}

void loop()

{

int val; //Creating a variable val

val= analogRead(A0); //Read input from analog pin a0 and store in val

val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)

esc.writeMicroseconds(val); //using val as the signal to esc
esc2.writeMicroseconds(val);
}

I did not find help on the internet, thank you in advance.

If you want one potentiometer to handle BOTH ESCs' speed, you could use this code:

//Using servo library to control ESC
#include <Servo.h>

//Starting the servos
Servo esc1;
Servo esc2;

void setup() {
    esc1.attach(9); // Use a PWM pin to the Servo, in this case 9
    esc1.writeMicroseconds(1000); //initialize the signal to 1000
    esc2.attach(10); // Pick another PWM to the other, in this case 10
    esc2.writeMicroseconds(1000); //initialize the signal to 1000

    Serial.begin(9600);
}

void loop() {
    int val; //Creating a variable val
    val= analogRead(A0); //Read input from analog pin a0 and store in val
    val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(analogRead's goes from 0-1023 and analogWrite's goes from 0-255, check your servo's specs)
    esc1.writeMicroseconds(val); // write to the first ESC
    esc2.writeMicroseconds(val); // write to the second ESC
    delay(100); // We usually set a small delay to avoid excessive readings or over-heating, but thats optional...
}

If you need to use two potentiometers, one for each ESC, then you would have to start another variable to read the 2nd pot value and use it to write on the 2nd ESC, simple as that! :)


Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one? This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.

I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?

Q1:

  ... exit the input ISR and interrupts are (automatically?) re-enabled

Yes, the RETI (return from interrupt) instruction enables interrupts.  See third paragraph of section 7.7 in Atmel's document #8271 (a 650-page spec sheet for the Atmega 48, 88, 168, 328 series), which says:

  When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.

Q2:

  Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

If the timer is running a clock, set the timer control bits to automatically reload the count register upon each overflow (or underflow).  That will leave a full count period for processing each timer interrupt.

That is, you can pre-load a next-timer-count (I think it can be different from the current count if necessary), so the timer can start its next interval automatically.  If the timer is used for some purpose more complicated than that, you may need a nested interrupt.

Q3:

  Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

If indeed input2 sticks around long enough to process after input1 processing is done, no problem.  Its interrupt will occur after the first interrupted code sequence executes one more instruction after the RETI occurs.  (See paragraph 6 of section 7.7 in doc8271.)

If input2 is brief, several different things can happen.   (a) If it is shorter than a clock cycle, in general it won't trigger an interrupt.  (b) If it is a level-interrupt-triggering event on INT0 or INT1 that ends while another interrupt is being processed, it won't trigger an interrupt.  (See discussion on page 72, section 13.2.3, of doc8271 of INTF0 and INTF1 being clear for level interrupts.) (c) If it is an interrupt-flag-setting event that sets a flag and ends while another interrupt is being processed, it will trigger an interrupt after the global interrupt flag is set, unless current processing clears its flag.

I think the above accurately states what happens on Atmega devices, but I suggest you also see doc8271 – and run tests – to see for yourself.  Here is part of what paragraphs 4 and 5 of section 7.7 in doc8271 say regarding (b) and (c):

  There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag.  ... Interrupt Flags can also be cleared by
  writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the
  corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.

  The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the
  interrupt will not be triggered.


Is the MKS GEN V1.2 compatible with Arduino IDE as Arduino MEGA Board? I need to do a Servo controller using Arduino and I have a spare MKS GEN V1.2 board right now, looking at the documentation from here http://reprap.org/wiki/MKS_GEN it seems this board is actually an Arduino board which can be programmed with the Arduino IDE.

Is this a correct observation that the MKS GEN V1.2 board is, in fact, a Arduino MEGA board internally?

It features an onboard ATmega2560.

This means that it is internally compatible with the Arduino Mega 2560. This does not mean that it is completely compatible with such since of course there is no way to use Mega shields with the board. This also means that there may be a core that provides better facility with the board, supporting its connections (LCD, positioning, heater/fan, etc.) better than the generic Mega core would.


Yun did not connect to WiFi after configuration and restart When examined we find that Yun is still in master mode and 0% signal.

Any procedure known to solve this problem manually?

We can access Linux command under Mater mode AP-mode and print WiFi status

/usr/bin/pretty-wifi-info.lua

We know procedure to change REST API access

Method II:  config file

opkg update
opkg install nano
nano /etc/config/arduino

config arduino
        option password '775e9f944188a7bcb36e9ca5dc51672b44bcceeb7d56d89dfb914e$
        option wifi_reset_step 'clear'
        option secure_rest_api 'true'
...

Merhod 1:  UCI API    need access to the Linux system by YSM program

PASSWORD

uci set arduino.@arduino[0].secure_rest_api=true

OPEN:

uci commit arduino

Is there any procedure manually to perform the configuration by hand for the mode:

change to client?
then restart?
from master mode where we have access to Linux command line?

This question has been left unanswered before in all forums examined.
Maybe someone knows the answer.

The problem lies in the Linux not in the hardware or routers or PC, as proven by testing.

My wireless config is in the /etc/config/wireless, not in the /etc/config/arduino

How do you configure your Wifi ?
There is at least 4 methods  :
you can do this through OSJS, through LUCI, through ARDUINO IDE, or with UCI.


Is my ATmega broken, and would replacing it with another break that one, too? I was communicating between my computer and my Arduino Uno R3 through Bluetooth using this Bluetooth module. The connector I use has a red wire where it connects to GND, and a black wire where it connects to +5V.

                ↓        ↓  to Uno ↓       ↓
               +5V      GND       pin 0  pin 1

I forgot this one time when I connected the Bluetooth module to the Uno, so the polarity was reversed. This fried the Bluetooth module.

After getting a new module, I discovered that the Uno was apparently fried too. Plugging a USB cable into the Uno made the little green integrated LED turn on, but that was all that happened; none of the pins put out any electricity. When I tried to upload a program, it gave the infamous avrdude: stk500_getsync(): not in sync: resp=0x00 error. I could upload programs to my other Uno fine, and I could not upload to the broken Uno on my other computer.

Two of the Arduino experts I know told me that the ATmega328 chip might be the only broken part. Is this likely to be the case? I have an Uno R2 with a working ATmega328. Would temporarily replacing the R3's ATmega with that R2's ATmega have a change of damaging anything?

Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega.

However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.

If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...


I want to pour 500ml of Water in jar with Arduino water flow controller? I want to pour 500ML of water with Arduino water flow controller with maximum accuracy.
How will I get the maximum accuracy with this sensor?
Could someone can give suggestion for accuracy or any other sensor that i can use?

The flow meter you specified, YF-S201 Hall Effect Water Flow Meter (datasheet) measures the water flow rate, producing signal output frequency in range 16Hz (at 120L/H) to 90.2Hz (at 720L/H). Datasheet claims "error range +/- 10)". Note that this only measures the rate of flow, it is not a valve and so does not control the flow.

Problem with using a flow rate sensor to measure total quantity of water, is that you must constantly integrate the flow rate over time to get the total volume. Any errors in rate measurement or integration time, will accumulate; so this is generally not an accurate approach. Cumulative errors are highly undesirable, because they are difficult to detect and compensate. You have to not only measure the output frequency, but also carefully control the time between measurements, because you are integrating over time. This will be even more of a problem if you are printing out messages to the serial port.

If the water supply is well regulated and always provides a steady flow, then you will open the valve for a specific time interval. But if the supply pressure is not well regulated, then you may accumulate integration errors and dispensing will not always be accurate.

If you care about dispensing precisely 500mL of water, a more practical solution is to use a weigh scale (load cell). First, measure the tare weight of the empty container, then dispense (using a control loop) until net increase in weight is 500g. With this setup, the dispenser accuracy is determined by the load cell repeatability error (0.1% for a good quality load cell, a couple % for a fair quality load cell) and the measurement accuracy of the ADC (depends on resolution and reference voltage stability). You could try using the Arduino's on-chip ADC which is only 10 bits, or for best accuracy use a real 24-bit weigh scale ADC. The load sensor's offset error is set to zero by measuring the tare weight of the empty jug, so you only need to be concerned about gain error at 500mL and repeatability of the load sensor. This approach does not have cumulative errors.

You have not specified what kind of valve you will use to control the flow. If you use a solenoid value, the valve is only on-or-off, there may be some overshoot due to valve reaction time (10ms), so you will need to experiment and determine an "off threshold" before reaching 500g.

Since you have no way to compensate if the system overfills the jar, you will need to dampen the system response so that it slows down as it approaches the target level, without overfill. I'd therefore suggest using a proportional valve instead of a solenoid valve. Start with a fast flow rate when net weight <400g and then switch to a slower rate as the jar reaches its target weight.


Testing tri-state pin - erroneous results with internal pullup I'm using an MPC73831 - a LiPo charging IC - in my Arduino project. It has a status pin to allow interface to a microcontroller, which uses a tri-state operation to convey three possible states of charging. I don't have the IC and battery yet, but I wanted to write a quick program to test a generic tri-state pin for HI, LO, and HiZ while I'm waiting for it to arrive.

The algorithm I wrote is very simple:

Set pinTest to input, no pullup.
Is pinTest high?
    Yes - pinTriState is HIGH, done.
Set pinTest to input with pullup.
Is pinTest high?
    Yes - pinTriState is HiZ, internal pullup causes high reading.
    No - pinTriState is LOW, 'cancelling out' internal pullup.

However, I'm not getting the expected results when using the internal pullup resistor - my board is showing correct analysis for HI and LO, but HiZ returns a mixture of HiZ and HIGH. I have tried this on an Uno, a Pro-Micro (32u4) and Uno->Micro and Micro->Uno. All give the same spurious results. I am baffled, therefore some advice would be appreciated. The full code is as below. I have left in code which randomises the time pinTriState stays at in a given state to keep pinTest guessing, but it's ultimately only an elaborate way of cycling through the three states.

#define pinTest 2
#define pinTriState 3

int state = 0;
char stateCh = '?';

int sect1;
int sect2;
int sectMax;

void setup()
{
    Serial.begin(9600);
    randomSeed(analogRead(A0));
    sect1 = random(1, 20);
    sect2 = random(sect1 + 1, random(sect1 + 2, sect1 + 20));
    sectMax = random(sect2 + 1, random(sect2 + 2, sect2 + 20));
}

void loop()
{
    // PART (1) Code to toggle three states of a tri-state pin
    if (state == 0)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, HIGH);
        stateCh = 'H';
    }
    if (state == sect1)
    {
        pinMode(pinTriState, OUTPUT);
        digitalWrite(pinTriState, LOW);
        stateCh = 'L'
    }
    if (state == sect2)
    {
        pinMode(pinTriState, INPUT);
        stateCh = 'Z';
    }

    // PART (2) Code to determine state of tri-state pin
    Serial.print(stateCh);     // Shows what it *should* be
    pinMode(pinTest, INPUT);
    if (digitalRead(pinTest))
        Serial.println(" - HIGH");
    else
    {
        pinMode(pinTest, INPUT_PULLUP);
        if (digitalRead(pinTest))
            Serial.println(" - HiZ");
        else
            Serial.println(" - LOW");
    }

    (state == sectMax ? state = 0 : state++);
}

The necessary pins are connected with a single wire. If I upload the code to two boards I remove PART (2) on the 'triState' board and PART (1) on the 'testing' board. In this case, stateCh has no function.

For a single-board setup, I get the following output:

H - HIGH
H - HIGH
...
L - LOW
L - LOW
...
Z - HiZ        <-- the first Z is correct 95% of the time
Z - HIGH
Z - HIGH       <-- the remaining Zs are a mixture, biased heavily towards HIGH.
Z - HiZ
...
H - HIGH       <-- H always gives HIGH
...

It makes no difference if I change the operating order of pinState. I've thrown in delay(100); between almost every other line, again to no avail.

I tried with a 22k, a 33k, and a 47k external pullup resistor. The results are perfect. However, this requires an extra Arduino pin to make sure that the pullup is only active when necessary. Part (2) becomes:

// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be
pinMode(pinTest, INPUT);
pinMode(pinPullup, INPUT);    // connected to pinTest via resistor
if (digitalRead(pinTest))
    Serial.println(" - HIGH");
else
{
    //pinMode(pinTest, INPUT_PULLUP);   <-- not anymore
    pinMode(pinPullup, OUTPUT);
    digitalWrite(pinPullup, HIGH);    // pulls pinTest to Vdd
    if (digitalRead(pinTest))
        Serial.println(" - HiZ");
    else
        Serial.println(" - LOW");
}

Using the extra pin to provide the pullup is a real pain in the ar...duino. I'm cripplingly short of spare pins and I don't see why this is not resolvable with internal pullups. Help?!

The internal pull-up is around 50k. So, install an external pull-down (to ground) of a somewhat higher value, like 1M.

Now:

Go to input mode, no pull-up. Get a reading. Turn on the internal pull-up. This should overpower the pull-down. If the reading changes, it was tri-state. Otherwise, if the reading doesn't change the external device is overpowering both pull-up and pull-down and you have the actual reading.

You may need a slight delay to allow the low-value pull-down to change the pin state.

Amended code to demonstrate:

// PART (2) Code to determine state of tri-state pin
Serial.print(stateCh);     // Shows what it *should* be

pinMode(pinTest, INPUT);
delayMicroseconds (100);
byte firstReading = digitalRead(pinTest);
pinMode(pinTest, INPUT_PULLUP);
delayMicroseconds (10);
byte secondReading =  digitalRead(pinTest);

if (firstReading != secondReading)
  Serial.println(" - HiZ");
else if (secondReading == HIGH)
  Serial.println(" - HIGH");
else
  Serial.println(" - LOW");

(Only showing the part that detects the pin state, the rest is the same).

Output:

H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
H - HIGH
L - LOW
Z - HiZ
Z - HiZ
Z - HiZ
H - HIGH
H - HIGH
H - HIGH

As you can see, working perfectly. I needed a longer delay after turning the internal pullup off because the fall time was around 100 µs. This actually sounds reasonable, because the 1 megohm resistor will take time to discharge the capacitance on the pin.

So:

10 µs delay after turning the internal pull-up on
100 µs delay after turning the internal pull-up off

Theory for the delays

The Atmega328 pin is specified as having a maximum capacitance of 10 pF (10e-12). It is considered charged/discharged after 5 time-constants, where T = R.C.

Thus for an internal pull-up resistance of 50k and a capacitance of 10 pF, charging should take:

50e3 * 10e-12 * 5 = 2.5e-006 (0.0000025) -> 2.5 µs

And to discharge through 1M (1e6) ohms, discharging should take:

1e6 * 10e-12 * 5 = 5e-005 (0.00005) -> 50 µs

My observed results were about 2.5 µS for the charge, but more like 100 µs for the discharge, however I probably had considerable stray capacitance in the wires used in the test circuit.


While loop not breaking I'm trying to build a circuit that buzzes until a button is pressed, or it buzzes 5 times:

void alarm()
{
  int AlarmState = 0; //Just to get while loop going
  int count = 1;
  while(AlarmState==0)
  {
    int count = 1;
    AlarmState = digitalRead(alarmStop);
    digitalWrite(buzz,HIGH);
    AlarmState = digitalRead(alarmStop);
    delay(500);
    AlarmState = digitalRead(alarmStop);
    digitalWrite(buzz,LOW);
    AlarmState = digitalRead(alarmStop);
    delay(500);
    count++;
    if(count>=5){
       break;
    }
  }

I put a bunch of digitalRead's  so it has a better chance of catching the button press while the loop is going, there's a better way to do that I'm sure but it's not my main concern right now.

This is part of a larger project, but I hope I've posted only the necessary code. The function runs, but does not break after count equals 5. Why?

The problem with your code is your using delay(). This is a function
that should most of the time be avoided for one simple reason: when the
Arduino is executing the delay() instruction, it does nothing but
wait. This means, among other things, that it cannot be reactive to user
input. As outlined by ARK in his answer, interrupts could be used to
overcome this problem. But you actually do not need them: the standard
way to avoid delays is to use instead the millis() function to control
timings. This approach is well described in the Blink without
delay Arduino
tutorial.

Here is how you can apply this technique to your alarm() function: In
a nutshell, you can think of delay() to be roughly equivalent to this:

void naiveDelay(uint32_t ms)
{
    uint32_t start = millis();
    while (millis() - start < ms) {
        // do nothing
    }
}

The problem here is the “do nothing” part. You do not want your program
to do nothing, you want it to monitor the “alarm stop” button. So the
simple solution to your problem is to replace delay() by the code
above, and then change it so that it monitors the button instead of
doing nothing. Then you get something like this:

void alarm()
{
    for (int count = 0; count < 5; count++) {

        // start the buzzer
        digitalWrite(buzz, HIGH);

        // first delay
        uint32_t start = millis();
        while (millis() - start < 500) {
            if (digitalRead(alarmStop) == HIGH) {
                digitalWrite(buzz, LOW);  // stop the buzzer
                return;
            }
        }

        // stop the buzzer
        digitalWrite(buzz, LOW);

        // second delay
        start = millis();
        while (millis() - start < 500) {
            if (digitalRead(alarmStop) == HIGH) {
                return;  // buzzer already off
            }
        }
    }
}