Is Sparkfun's MicroView OLED Arduino module a shield? I'm getting confused by the Arduino terminologies:  shield, breakout, module.

Is this MicroView an Arduino compatible shield that will plug into Arduino's or Adafruit's Uno?

No, MicroView is not an Arduino shield, so you can't plug that into any Arduino. Arduino Uno and MicroView are developed based on Atmega328 controller. So it is 100% code compatible with Arduino Uno, means the code that runs on an Arduino Uno will also be able to run on the MicroView.


I2C communication is not working I have been working on my project but I get an error and I need some advice or correction.

I use I2C method to communicate between master and slave. I've got two questions:

I send 7 inputs (from master) to the slave but only receives 6
Will my coding make an output like this video

Master Code

// Master Code
#include <Wire.h>
byte nChar =0;
char input[7];

void setup () {

  Serial.begin(9600);
  Wire.begin();
}

void loop()
{
  if (nChar < 7) {if (Serial.available()) { input[nChar++] = Serial.read();}}

    else {

      Wire.beginTransmission(1);

      //a
      Wire.write(input[0]);
      Serial.print("Drawer : ");
      Serial.println(input[0]);

      //x
      Wire.write(input[1]);
      Serial.print("Output : ");
      Serial.println(input[1]);

      //00
      Wire.write(input[2]);
      Wire.write(input[3]);
      Serial.print("Output : ");
      Serial.print(input[2]);
      Serial.println(input[3]);

      //y
      Wire.write(input[4]);
      Serial.print("Output : ");
      Serial.println(input[4]);

      //00
      Wire.write(input[5]);
      Wire.write(input[6]);
      Serial.print("Output : ");
      Serial.print(input[5]);
      Serial.println(input[6]);

      delay(15);

      while (Serial.available())
      {
        //Remove extra
        Serial.read();
      }
      Wire.endTransmission();
        nChar = 0;
    }
  }

Slave Code

#include <Wire.h>
byte ledPins[] = {12, 11, 10, 9, 8, 7, 6};
byte ledPins2[] = {12, 11, 10, 9, 8, 7, 6};
byte count;
byte nChar;
char c;
char input[8];
char data[30] = "";
int n;
#define nBits sizeof(ledPins)/sizeof(ledPins[0])
#define nBits sizeof(ledPins2)/sizeof(ledPins[0])

void setup()
{
  Wire.begin(1);
  Serial.begin(9600);
  for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
for (byte i = 0; i < nBits; i++) {
    pinMode(ledPins2[i], OUTPUT);
    }
  Serial.begin(9600);
}

void loop()
{
  if (nChar < 8) {                    //accumulate three characters
    if (Serial.available()) {
      c = Serial.read();
      input[nChar++] = c;
    }
  }
  else {
    input[8] = 1;                   //atoi() expects string terminator
    n = atoi(input);                //convert the input characters to integer
    dispBinary(n);
    delay(100);                     //wait for any additional characters
    while (Serial.available()) {    //ignore them
      c = Serial.read();
    }
    nChar = 1;
  }
}

void receiveEvent(int howMany)
{
  while (1 < Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

void dispBinary(int n) //Vertical
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins[i], n & 1);
      n /= 2;
    }
  }
}

void dispBinary2(int n) //Horizontal
{
  if (n >= 0 && n <= 5) {
    for (byte i = 0; i < nBits; i++) {
      digitalWrite (ledPins2[i], n & 1);
      n /= 2;
    }
  }

}

void b()
{
  if (data[0] != 'a')
  {
    dispBinary(atoi("00"));
    delay(100);
    dispBinary2(atoi("00"));
    delay(100);
    goto fin;
  }
  if (data[1] = 'x')
  {
    char xdata[2] = {data[2], data[3]};//(data[2], data[3]);
    dispBinary2(atoi(xdata));
    delay(100);
  }
  if (data[4] = 'y')
  {
    char ydata[2] = {data[5], data[6]};//(data[5], data[6]);
    dispBinary(atoi(ydata));
    delay(100);
  }

fin:;
}

Most coders would your while (1 < Wire.available()) { write as while ( Wire.available() > 1) { and read it "repeat while there is more the 1 byte available". but wait, why leave that one byte there? you want "repeat while there is no more byte available".

you need while (0 < Wire.available())


Split Power supply in voltage and gnd? I am new to electronics and arduino in general. I need to split a power supply in gnd and voltage. Basically, the power supply has one single wire (with the voltage and the gnd passing through it i think), and I need them to be separated. Sorry if this is a noob question, but I am really new to this whole thing.

Do you have a image of this? Logically, and as far as I know, One wire will not carry both GND and Positive.

Are you talking of a DC jack kind of thing?

BTW, I'm starting out here too!


Why isn't DigiSpark automatically recognized on other computers? I bought a DigiSpark (it is a development board based on the ATtiny85 microcontroller) yesterday and I wrote my first script.

I have no problems to run it on my personal PC (which I am using to program my DigiSpark). The problem is when I try to plug my DigiSpark to another PC, which doesn't have DigiSpark drivers installed. I tried to run it on two different PCs (Windows 7) and Windows just can not find DigiSpark drivers so my script does not run.

Of course I tried to plug in to different USB ports - unfortunately it did not help.

Any ideas what can I do to make my DigiSpark run on other PC without installing drivers by myself?

Thank you.

You will need to install the drivers before you can use it on other computers.
The drivers tell a Windows PC how to talk to the device.  The device is not a generic device so Windows can't use a fall back driver, like it could with a keyboard or monitor.


Arduino IDE in conflict with pyserial for use of serial port in OSX Yosemite I'm trying to communicate with an Arduino Uno via pyserial using a code that I wrote for Ubuntu. However, when I try to use the same code in OSX Yosemite after identifying the serial port for the case of OSX, it doesn't work. This is the offending line:

In [32]: ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

If I run the above line when the Arduino IDE is not running there is no error message, but the Arduino doesn't do anything (the Arduino IDE Serial Monitor must be open in order for the code to work). However, if I open the Arduino IDE and use the Serial Monitor (which works fine, i.e. it shows data that the Arduino is sending), I get the following error message:

SerialException: [Errno 16] could not open port /dev/cu.usbmodem1421: [Errno 16] Resource busy: '/dev/cu.usbmodem1421'

If I run lsof | grep /dev/cu.usbmodem1421 then I get that the only program using said port is Arduino IDE:

Arduino   2012 germanchaparro   94u     CHR               18,7   0t15249    1285 /dev/cu.usbmodem1421

Clearly OSX is not letting Arduino IDE and pyserial to use the serial port (to which the Arduino UNO is connected) at the same time. I don't know how to fix this, and it's especially frustrating since Ubuntu doesn't put up a fight.

Any ideas?

Ok, I solved it. First I stopped using the IDE serial monitor as Majenko suggested, and focused on getting the Arduino readings within the python code. Besides trying to use the python code and the IDE monitor at the same time (which apparently you can do in Ubuntu but not in OSX), the original problem was that my python code was not clearing the serial buffer in the r/w process. In order to do this, I wrote the following function to be called before and after a serial write:

 ser = serial.Serial('/dev/cu.usbmodem1421', 9600)

 def readarduino(ser):
    did=True
    while ser.inWaiting(): # Check number of characters left in buffer
        if did and ser.inWaiting() < 490: # Select last 500 characters in buffer
            for i in range(6):
                print ser.readline() # Print 6 lines in buffer
            did = False
        ser.readline()  # Clear buffer line by line until ser.inWaiting goes to 0

This ensures that the buffer is clear whenever I am writing to the Arduino.

This solution works for OSX Yosemite and Ubuntu 14.04


How to declare char array[] using integers? Can anyone please tell me how to declare a char variable using a few integers?
I need to declare a byte information for shiftOut() function as char.
int a = 0;
int b = 1;
int c = 0;
int d = 1;
int e = 1;
int f = 0;
int e = 0;
int f = 1;

char information[] = {"B" + a + b + c + d + e + f};

void setup() {
  Serial.println(information);
}

void loop() {
  shiftOut(pin, pin, MSBFIRST, information);
}

In command Serial.println(information); I want to get back B01011001
Now the output I am getting ⸮⸮
Of course the simpliest way to create that will be:
char information[] = "B01011001";
But I need to change the individual bits in int bit = variable.
Please note that substition int bit = with char bit = is unable for my code, using int of value of individual bits is necessarily. Because I am using my project with blynk, and there is function a = param.asInt(); ,  param.asChar(); does not exist.
How to do that?
Thank you for responses!

I think you are getting something wrong about shiftOut(). It will transfer exactly 1 byte (or 1 char). It does not take an array as parameter. I guess you want to write the 8 bits, that you are defining with your ints, as one byte out. Defining at byte directly would look like this:
byte information = 0b00101100;

The 0b tells the compiler, that the following number is encoded in binary. So you have one single byte, that contains all your information (all the bits). Then you can do
shiftOut(data_pin, clock_pin, MSBFIRST, information);

(Please note, that the data_pin and the clock pin need to be different).
If you want to print the information variable to Serial, showing the binary representation, you can use the corresponding parameter of the print() function.
Serial.print(information, BIN);

Will print the binary representation (zeros and ones as text) of the variable. So, to get "B1011001", you would do:
Serial.print("B");
Serial.println(information, BIN);

Note, that the print()/println() function will remove all leading zeros.

How to put the information byte with your ints? Each of them is either zero or one and represents one bit. So you can use the bitwise operators to put them together:
information = (a << 7) | (b << 6) | (c << 5) | (d << 4) | (e << 3) | (f << 2) | (g << 1) | h;

For each int only the first (Least significant) bit is important, since the others are always zero (because the int can be only one or zero). So we shift the int value to the left by the number of the corresponding bit minus 1 (so shifting a 7 places to the left to put its least significant bit to the most significant bit of information. We are doing that for all our int values. Then we put them all together into one byte by using the | (bitwise OR) operator.
Note: We don't know, where these ints are coming from. Even when stating, that you absolutely need those ints, you could organize them in an array instead of single variables. That would look like this:
int int_data[8] = {0, 0, 1, 0, 1, 1, 0, 0};
...
// in a function (like loop() or setup())
byte information = 0;
for(int i=0;i<8;i++) information |= int_data[7-i] << i;

It's up to you, if you want to do that.


Digispark Micro (ATTINY85) not working on Macbook Pro 2016 I just bought 2 Digispark Micro to start learning some Arduino things.

But when I try to upload the code to my Digispark, it just send me an "Device search timed out" error.

My Digispark is plugged with an USB-C to USB connector and the Red dot on the Digispark is working. The connector is working well with any other device.

Arduino app (1.8.9) settings:

Tools

Board → Digispark (Default - 16.5 mhz)
Programmer → Micronucleus

I tried using the micronucleus CLI, but, even if I try plug/unplug several times (~10s between each unplug/plug) I got this :

> Please plug in the device ...
> Press CTRL+C to terminate the program.

Digisparks are known to have problems with USB3 ports (which your USB-C adaptor probably provides). Try using a cheap USB2 hub between the DigiSpark and the adaptor.

It's always a good idea to use a cheap USB hub between whatever experimental device you want to connect and your machine, so that if you wire something up incorrectly you don't end up frying an expensive laptop. This is particularly true for a device such as the digispark which does not have a real USB interface but really bit-bangs the protocol out of ordinary I/O pins.

There is no guarantee that the hub will protect you from all wiring mistakes, but it's an added level of protection.


Windows 10 problem installing driver So the arduino shows up as "Unknown device" when connected to my computer. Followed somr guides on google but still failed, this error came up, what should I do? I've tried "Disable Driver Signature Enforcement" and the regedit thing..

Install the latest Arduino IDE with windows administrator rights.


Why my Arduino Uno R3 doesn't work with a recompiled optiboot with BAUD_RATE=57600 This is a follow on question from How to reduce serial speed on Arduino bootloader (optiboot) and on the IDE?

I did manage recompile optiboot bootloader to work at 57600 bps and uploaded it to a couple of ATmega328-PUs. I just changed the BAUD_RATE to 57600L in Makefile and recompiled it.

They worked just fine with my Arduino Single Sided Serial (Severino) and a couple of custom standalone Arduino boards with FTDI-like header.

However, I couldn't program the same MCUs using my Arduino Uno R3. When I try to upload a sketch, avrdude just sits there waiting for a response that doesn't come. The output I got is something like this:

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\Users\Ricardo\arduino-1.0.5\hardware/tools/avr/etc/avrdude.conf"

         Using Port                    : \\.\COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Recv:
avrdude: stk500_getsync(): not in sync: resp=0x00

avrdude done.  Thank you.

Would that have anything to do with the 2nd MCU that acts as the USB driver on the Uno - the ATmega16U2? Do I have to patch it, too?

So, my questions are:

1. Why my recompiled optiboot didn't work with my Arduino Uno R3?

2. What can I do to check what's wrong with the upload process using my new bootloader?

Chris Stratton's comments helped me find a workaround for my problem. It looks like the version of optiboot I was working with (see source-code here) doesn't work properly at 57600 BAUD with Arduino Uno without modifications (that I don't know how to make). So I compiled the bootloader with 76800 BAUD, configured the IDE accordingly, and all my boards started to work fine with it.

It is still unclear to me the reason I one can't use 57600 BAUD, but I'm too pragmatic and too little knowledgeable to go after the true answer. So, I'll take Chris' word for it. He said this:

  Basically, 57600 does not divide in 16 MHz nicely when the 8x or 16x oversampling of the hardware UART is taken into account. My gut feeling is that different implementation are using different approximations. If they used the same approximation then even if "wrong" things would be basically fine (especially as the hardware design is similar), but if they are are off in opposite directions it could be unreliable. If you post the exact bootloader source you used we can see for sure - some optiboot source I just looked at seems to actually be using a software UART for 57600.

That's the end of it for me.


Combining code for multiple sensors (Current and Voltage Sensors) in one program I need to operate 2 different sensors (Current and Voltage) simultaneously. I have managed to run each one of them separately and I don't know how to manipulate the code so they could work together. My background in coding is basic and I'm not the one who wrote these codes.

Here are the sketches:

1. Current Sensor Code

void setup() {

  Serial.begin(9600);
}

void loop() {

  float average = 0;
  for(int i = 0; i < 1000; i++) {
    average = average + (.0264 * analogRead(A0) -13.385) / 1000;//this is
    //for the 5A mode, if 20A or 30A mode, need to modify this formula to
    //(.19 * analogRead(A0) -25) for 20A mode and
    //(.044 * analogRead(A0) -3.78) for 30A mode
    delay(3);
  }
  Serial.println(average);
}

2. Voltage Sensor Code

/*
DC Voltmeter Using a Voltage Divider
Based on Code Created By
T.K.Hareendran
*/

int analogInput = A1;
float vout = 0.0;
float vin = 0.0;
float R1 = 30000.0; //
float R2 = 7500.0; //
int value = 0;
void setup(){
   pinMode(analogInput, INPUT);
   Serial.begin(9600);
   Serial.print("DC VOLTMETER");
}
void loop(){
   // read the value at analog input
   value = analogRead(analogInput);
   vout = (value * 5.0) / 1024.0; // see text
   vin = vout / (R2/(R1+R2));

Serial.print("INPUT V= ");
Serial.println(vin,2);
delay(500);
}

How to combine two sketches.

First, make sure every global variable and function name is unique (except setup and loop). Choose the smallest sketch and rename its. variables, function names and any other named items (like DEFINE).

Is convenient to refactor things. I extract the code for reading Voltage and Current to separate functions, to reduce the count of global variable and length of each function, making things easier by reducing the side of setup() and loop().

Now, combine the code inside the setup and loop:

const int analogInput = A1;

void setup() {
  Serial.begin(9600);
  pinMode(analogInput, INPUT);
}

void loop(){
  Serial.print(getCurrent());
  Serial.print(" ");
  Serial.println(getVoltage(),2);
  delay(500);
}

float getCurrent() {
  float average = 0;
  for(int i = 0; i < 1000; i++) {
    average = average + (.0264 * analogRead(A0) -13.385) / 1000;//this is
    //for the 5A mode, if 20A or 30A mode, need to modify this formula to
    //(.19 * analogRead(A0) -25) for 20A mode and
    //(.044 * analogRead(A0) -3.78) for 30A mode
    delay(3);
  }
return average;
}

float getVoltage() {
   const float R1 = 30000.0; //
   const float R2 = 7500.0; //
   float value = analogRead(analogInput);
   float vout = (value * 5.0) / 1024.0; // see text
   float vin = vout / (R2/(R1+R2));
  return vin;
}


rfid reading function returning null I have a function that reads rfid card and return rfid string. Function reads string well but.
I am using ArduinoJson libray to generate json .
this is the function that i am using to read rfid cards.
String rfidOku(){
  String kartid= "";
  if( mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()){
    for (byte i = 0; i < mfrc522.uid.size; i++)
    {
        kartid.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
        kartid.concat(String(mfrc522.uid.uidByte[i], HEX));
    }
    kartid.toUpperCase();
    //Serial.println(kartid);
  }
  kartid.trim();
  return kartid;
}

and in the loop function , if button pressed i am getting an rfid and ı am creating json using it
    const size_t capacity = JSON_OBJECT_SIZE(4);
    DynamicJsonDocument doc(capacity);
    const String str_rfid = rfidOku();
    doc["id"] = odeme.id;
    doc["fiyat"] = odeme.fiyat;
    doc["rfid"] = str_rfid;

    serializeJson(doc, Serial);

When i look to serial monitor rfid field is null. Why it happens. I tried to write other string there it works well with other string but why it does not with str_rfid.
I also print value of str_rfid using Serial.print str_rfid getting rfid card id from function well.

It could be your JSON object capacity is too small because of string duplication when you deserialise it to print it.
You should try a capacity like JSON_OBJECT_SIZE(3) + 500 for deserialising, and see what happens.
Also, try: doc["rfid"] = str_rfid.c_str(); to see if that works better (CString instead of String object).
More information on object capacity can be found here; there's a calculator here.


I want to build a radar alert system with Arduino I'm new to all this. I bought an Arduino Uno recently and an Ultrasonic distance sensor. My mom's cats keep walking down into the basement and doing their... business. Anyhow, I want to create a radar system which detects movement past this door. I'd like to have an alert sent to my computer or Android. Is this within a basic Arduino level? Other than the Arduino what else might I need?

I think that's quite possible. As mentioned, not technically radar. I don't know if cats could hear it, but then if it scares them off, job done, right?

I don't know if sending the alert to a PC would help or not - you might just consider an audible alarm using a cheap 8-ohm speaker. Otherwise, USB, bluetooth, wifi, or SMS for notification. A PC or phone (on all the time) to receive the data. Some thought about what you will do with it.

As a deterrent, a water pistol is ideal, you'd need a motor - solenoid? - to fire the water pistol. Harmless, but very distasteful to cats.

https://www.youtube.com/watch?v=lxmRYRlgreo

Update: Inspired by @SDSolar, I checked it out - yes, cats can hear that frequency.

  Cats have excellent hearing and can detect an extremely broad range of frequencies. They can hear higher-pitched sounds than humans or most dogs, detecting frequencies from 55 Hz up to 79 kHz.

(from https://en.wikipedia.org/wiki/Hearing_range#Cats )

This means they will probably learn to associate the sound with the water pistol (yes, cats CAN be trained, if they are motivated). This means if you remove your device, they will probably come back, but if you leave the sensor (active), but remove the water, then it will continue to work!


How to Sort Elements of Array in Arduino Code? /How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.

lt[6]={35,15,80,2,40,110};

As mentioned in the comments, qsort is a good option:

// qsort requires you to create a sort function
int sort_desc(const void *cmp1, const void *cmp2)
{
  // Need to cast the void * to int *
  int a = *((int *)cmp1);
  int b = *((int *)cmp2);
  // The comparison
  return a > b ? -1 : (a < b ? 1 : 0);
  // A simpler, probably faster way:
  //return b - a;
}

void setup() {
  // The array
  int lt[6] = {35, 15, 80, 2, 40, 110};
  // Number of items in the array
  int lt_length = sizeof(lt) / sizeof(lt[0]);
  // qsort - last parameter is a function pointer to the sort function
  qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
  // lt is now sorted
}

void loop()
{
}


Multiple Buttons on Single Analog Pin and Trigger Pin Arduino Uno I've researched how to attach multiple buttons to a single analog input using a resistor network. Instructables has a good lesson on this: http://www.instructables.com/id/How-to-access-5-buttons-through-1-Arduino-input/?ALLSTEPS

My requirement is that I need to attach an interrupt to buttons (ie the analog input) before reading the analog value, so that all the buttons can act as a trigger.

This works for voltages in the higher range, but not in the lower range (the trigger input waits for a RISING edge).

Can any one suggest a circuit that steps a >0V+ to +5V input to a +5V output so that any button push would trigger the input?

Otherwise, does anyone have other suggestions on how to use triggers for each button?

Use the analog comparator in the ATmega328P to trigger an interrupt once the input voltage rises enough to indicate a button press.

Connect the analog network to both the analog input and D6.

If your lowest analog voltage is not greater than 1.2V then apply a voltage greater than 0V but more than 40mV less than your lowest analog voltage to D7. If you have not connected the voltage then configure the comparator to use the internal bandgap reference (ACSR |= _BV(ACBG)).

Enable the comparator interrupt and capture on a rising edge (ACSR |= _BV(ACIE) | _BV(ACIS1) | _BV(ACIS0)).

Disable the digital input on D6 (AIN0), and on D7 (AIN1) if connected to a voltage reference (DIDR1 |= _BV(AIN0D), DIDR1 |= _BV(AIN1D)).

Write an ISR that does what you want on comparator trigger (ISR(ANALOG_COMP_vect) { ... }).

Now go back and read all that three more times until you understand it. As always, see the ATmega328P datasheet for details.


Compilation Error in nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C) I am using nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C). I am using Arduino IDE to program nodeMCU. I am getting a compilation error:

C:\Program Files (x86)\Arduino\libraries\OneWire/OneWire.h:108:2: error: #error "Please define I/O register types here"
#error "Please define I/O register types here"
^
exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

What is meant by: "Please define I/O register types here"? Thank you for the help.

It appears you're using an outdated version of the OneWire library that does not support ESP8266. Please follow these instructions to upgrade to the latest release of the library:

Sketch > Include library > Manage libraries...
Wait for the download to finish.
In the "Filter your search..." box, type "onewire".
Click on the "OneWire" entry.
Click the "Update" button.
Wait for the installation to finish.
Click the "Close button.

The recent releases of the OneWire library have support for ESP8266 so this should solve your compilation issue.


What would be the Western / American equivalent of the Troyka Shield and modules? I'm taking an online course on Arduino robotics, produced by the Moscow Institute of Physics and Technology. The lectures are translated into English, but all of the parts referenced are by the Russian company Amperka.

It seems the key parts I need to follow along are

The Troyka Shield
Troyka modules, like the potentiometer, Hall sensor, etc
Matryoshka Z set

As fun as it would be to order from the Russian store, there are several practical reasons I'd prefer an American (or Western) equivalent. If they even ship to the US, payment would be difficult, shipping slow, instructions in Russian, etc, etc.

I've spent time and money shopping around Adafruit and SparkFun, but as an Arduino beginner, I'm not 100% sure which parts are analogous to these Russian ones. If a more experienced hobbyist recognizes any of these and can help me identify it, that would be most appreciated.

I think the Troyka components are a necessity, but the Matryoshka Z is a "nice to have" bundle of components. I'm using Arduino Uno, so compatibility with that would be preferable, but I think one of his Russian controllers is supposed to be a clone of the Leonardo, so if these parts only work with a Leonardo that's fine too.

The shield is shown here:

In this view it's combined with its modules using this special snap-together PVC:

The instructor said that he helped invent the PVC components, so I guess there may not be an American version of that yet (or is there)?

This probably has no complete, general solution.

The Troyka Shield looks to be just a prototype shield with footprints for ground/power/data cables.  Likely you can just use a different mechanism to connect things, solder some additions to an everyday proto shield, or you could relatively quickly duplicate this in a PCB design program and have boards made.

There are probably many alternatives for the mechanical structure, ranging from cardboard and foam tape or hot glue to various toy building block sets, or you could try to duplicate their idea by making some grids on an everyday 3D printer.  Likely none of these satisfy formal ESD concerns - but then, Arduino projects are usually considered disposable enought that people rarely worry about this.

The modules are going to be the most problematic part.  They seem to encompass many of the peripheral parts and chips usually used in Arduino projects, and most of those are already available in canonical modules from a range of vendors like Adafruit, Sparkfun, Seeed, etc on down to clones and simple executions of chipmaker's recommended circuits.  So for most of these, you'll probably have no problem finding a substitute, the possible complication is if you have enough understanding of the details of each assignment to make any necessary changes to accommodate for differences in pinouts, components values, etc between the specified Troyka module and the chosen substitute.

You may in the end find it's better to just follow tutorials written around the specific parts and modules you find more readily available for purchase, and thus avoid the needs to translate the details.

Do beware however, that there are some really bad tutorials out there on the Internet - some in places like Instructibles are simply terrible engineering to the point where it is a minor miracle if they even worked once for their authors, and even some on the Arduino site cut corners in ways that can't be recommended.


Why does static member std::map reset ESP8266 when outside the .ino file? Here's an example of a class which crashes the ESP8266-03 causing it to reset:

Test.hpp file:

#include <map>

class Test {
public:
    int data() const;

    Test(int x);
    ~Test();
protected:
    int _data;

    static std::map<int, Test const *>thing;

    static void _Reserve(Test const * const t);
};

Test.cpp file:

std::map<int, Test const *> Test::thing;

int Test::data() const
{
    return this->_data;
}

void Test::_Reserve(Test const * const t) {
    Test::thing[t->data()] = t; // Works fine if this line is removed.
}

Test::Test(int x): _data(x)
{
    Test::_Reserve(this);
}

Test::~Test() {};

Project.ino:

#include "ESP8266WiFi.h"
#include "Test.hpp"

Test test(2);

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

void loop() {
    Serial.print("Timer: ");
    Serial.println(millis());
    delay(1000);
}

The following does NOT crash the ESP8266-03 and prints the time as it should:

#include "ESP8266WiFi.h"
#include <map>

class Test {
public:
    int data() const
    {
        return this->_data;
    }

    Test(int x): _data(x)
    {
        Test::_Reserve(this);
    }
    ~Test() {};
protected:
    int _data;

    static std::map<int, Test const *>thing;

    static bool _Reserve(Test const * const t) {
        Test::thing[t->data()] = t;
    }
};

std::map<int, Test const *> Test::thing;

Test test(2);

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

void loop() {
    Serial.print("Timer: ");
    Serial.println(millis());
    delay(1000);
}

When the first version is uploaded to the board, I get the following in the serial monitor:

 ets Jan  8 2013,rst cause:1, boot mode:(1,7)

 ets Jan  8 2013,rst cause:4, boot mode:(1,7)

wdt reset

When I reset it and boot it regularly, no upload mode, the following repeats every ~1 second:

 ets Jan  8 2013,rst cause:1, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

Why does static member std::map reset ESP8266 when outside the .ino file?

What happens if the Test() constructor is run before the map constructor? This is the problem: you are assuming order of execution.

Use a Singleton pattern or init() member function to force the ordering that is required.

Cheers!


Is volatile qualifier needed if shared variable cannot be changed externally during complete function call? Consider the following example:

int i { 0 };

void incInt() {
    ++i;
}

int readInt() {
    return i;
}

setup() {
    Serial.begin(9600);
    attachInterrupt(digitalPinToInterrupt(D1), incInt, CHANGE);
}

loop() {
    noInterrupts();
    int currI = readInt();
    interrupts();

    Serial.println(currI);
}

By wrapping the call to readInt() with noInterrupts() and interrupts() it is ensured that i cannot be changed externally during the execution of readInt(). i also cannot be changed externally during the execution of incInt(), as long as it is only called as ISR (interrupt service routine). Do I still need to declare i as volatile?

Does the situation change if i is accessed directly in the main loop:

loop() {
    noInterrupts();
    int currI = i;
    interrupts();

    Serial.println(currI);
}

In other words: What is the context in which the compiler expects a variable to not be changed externally if it is not declared volatile?

Declaring a variable as volatile tells the compiler, that it always has to read the real variable and that it cannot use a cached value. Also the compiler cannot optimize this variable, since it is unknown, when the variable will change. For this it is irrelevant, how you actually read the variable in the main sketch, it only matters, that it get's read. Also this has nothing directly to do with doing the read atomically (with noInterrupts()) (though you only garantee correct values, when doing it)

So yes, you need to declare it volatile, or the compiler might think, that the value doesn't change and optimize it out in some way.

  What is the context in which the compiler expects a variable to not be changed externally if it is not declared volatile?

Externally here means outside of the main routine. This covers variables, that get changed in ISRs and also registers, that are changed by hardware (so the register definition in the used core are also volatile). The compiler cannot know, when these changes happen, because they are triggered by the hardware, not by the code. It will try to optimize your sketch (which is a rather complex procedure), and might see, that your variable is never changing in the code (the ISR does not get called from the main sketch, thus the compiler does not see it getting called) and will try to optimize it. To ensure, that your sketch works properly, it is your task to tell the compiler, that this variable can change at any time (so that it does not think the other way). You are doing this by declaring it as volatile


How can I rename how my Arduino shows up on the computer? I have a clone of a Mega 2560, and the Chinese manufacture apparently had a broken shift key. To my annoyance, whenever I connect it to my computer it reads, arduino compatible mega 2560. With my extreme annoyance with slightly misspelled or incorrectly capitalised English, it has been very distracting to me.

However, the reason that I'm asking this question is for more than how to rename it to be capitalised. Think of how many projects could be simplified by this! Or for many Arduinos, you can label they physically and then rename them Arduino #1, etc. so you can tell which port it is on using device manager. If you designed a product with Arduino, then you can even rename it to your product name.

I would imagine that there would be an easy way to do this by reburning the firmware to the [Insert USB chip model #### here]. I've seen it done for keyboards on the Uno, so I would imagine that you could modify it somehow.

This string is contained in the FT232 USB to UART interface chip and the manufacturer has released the FT_PROG tool to reprogram it. But do take note of the warning on their website: "PLEASE NOTE - The use of some of these utilities by an end user may result in a device being rendered useless". Another word of warning is to ensure there is only one device connected with an FTDI-chip.

Here is a screenshot of the MProg tool:


Propane injection software compiles, uploads, doesn't work Looking for some help here. I have written out some code to add propane injection for my forklift. It is supposed to read three analog inputs, add them together and multiply the sum by three. There is an interrupt which is triggered by a hall effect sensor which is supposed to fire a solenoid valve for a duration of microseconds. I have mocked this up on a breadboard with a attiny85 pulsing the hall effect pin and nothing happens. Would appreciate some one having a look at the code and letting me know where I went wrong. Thanks.

const byte interruptPin = 2; //this is the interrupt pin hall sensor//
int mpPin = A3; //manifold pressure sensor//
int tpsPin = A4; //throttle position sensor//
int tunePin = A5; //tune pot 10k//
volatile byte inj; //this will end up being the duration of the injector pulse//
int mpValue = 0; //setting manifold variable to zero//
int tpsValue = 0; //setting throttle positon sensor value to zero//
int tuneValue = 0; //setting tune value sensor variable to zero//
int injValue = 0; //setting injection variable to zero//

void setup() {
    pinMode(12, OUTPUT);  //this is the pin that fires the injector//
    pinMode(interruptPin, INPUT_PULLUP); //set the interrupt pin to high pull up //
    attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);  //set the interrupt to trigger shot isr on low//
}

void loop() {
    tpsValue = analogRead(tpsPin); //read the throttle positon sensor//
    mpValue = analogRead(mpPin);//read the manifold pressure sensor//
    tuneValue = analogRead(tunePin); //read the tune sensor//
    injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
}

void shot() {
    digitalWrite, 12, HIGH; // initilize injector powerup//
    delayMicroseconds(inj); //delay the calculated value  in microseconds//
    digitalWrite, 12, LOW; //shut down the injector//
}

I can see two things wrong with your code at first glance.  First is the kind of interrupt you're using:

attachInterrupt(digitalPinToInterrupt(interruptPin), shot, LOW);

A LOW interrupt keeps triggering over and over again all the time the input is low.  It's a special interrupt type that is seldom used for anything except waking up the MCU or handling external peripherals with persistent interrupt indication.  Instead you should be using FALLING which will trigger once and once only when the input transitions from HIGH to LOW.

attachInterrupt(digitalPinToInterrupt(interruptPin), shot, FALLING);

Secondly you have two variables that seem to be intended to do the same thing - store the delay time for your output pulse.  And that's caused confusion:

injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

... and then later ...

delayMicroseconds(inj); //delay the calculated value  in microseconds//

In your comments you reference the second variable, but the code uses the first one. Change that so it uses just one (volatile) variable:

inj = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//

Alternatively, and perhaps much safer, is to assign the result of the calculation inside a critical section, in which case having two variables is useful:

injValue = (tpsValue + mpValue + tuneValue) * 4; // add the three sensors together and assign the value to inj//
noInterrupts();
inj = injValue;
interrupts();

This will prevent your interrupt triggering whilst the value is being calculated and placed into the inj variable which could result in the inj variable containing gibberish, which could cause your engine to explode.


New to Arduino and I have a WIP code for a class. ERROR with LEDs working? (EDIT) My goal with this code is to use two potentiometers, pot0 and pot1 respectively, to control 8 leds. Pot0 controls which sequence the leds are running (1, 2, or 3) and pot1 controls which LEDs within each sequence are active. Currently, I am having a problem because I am running Sequence 1 (the first if statement) to my arduino, but I can't seem to make the LEDs light up when being called out by the potentiometer. The only LED that works is LED 0, and that's only if both potentiometers were in the proper positions when the code begins running.

int pot0 = 0;
int pot1 = 1;
int led[] = {7, 6, 5, 4, 3, 2, 1, 0};

void setup() {

for (int i = 0; i < led; i++){
  pinMode(led, OUTPUT)
;}
}
void loop() {
  int potread = analogRead(pot0);
  int val = analogRead(pot1);
  int potR = map(val, 0, 1023, 0, 7);

if (potread <= 341) {
  for (int i; i == potR;)
  digitalWrite(led[i], HIGH);

}

else if (potread <= 682) {

}
else {

}
}

For this, you should be using map(). Instead of int potR = val % 8; try int potR = map(val, [minimum pot value], [maximum pot value], 0, 7). Also, I'm pretty sure you don't need the for loop if all you're doing is led[i]. In that case, you could use led[potR].


Can I use my phone's charger to connect arduino M0 pro R3 with computer? I found out that the arduino M0 pro R3 needs either micro HDMI or micro USB.

Since I don't have any micro USB or HDMI adapters, can I use the Samsung galaxy USB/micro adapter to connect?

Echoing what Gerben said, in order to wrap up this question:

If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.
You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.
The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.


How to control android app with arduino I'm trying to connect Arduino Leonardo to an Android tablet. I would like to make the Arduino send commands (using pushbuttons or a slider for example) to the tablet to switch between pages, to select a file on the desktop, to scroll up and down the screen, etc.

Thanks. I will really appreciate your help.

Perhaps this is not exactly what you are looking for, but from your examples it seems like using navigational commands from the keayboard/mouse would accomplish a lot of what you are requesting.

Android has USB HID support from honecomb, so you should be able to create a sketch to emulate a keyboard and mouse based on the IO data and it should work with your android device just by plugging the USB cable (if emulating a mouse, it will display the mouse cursor as soon as it is connected).


GSM incoming bytes from UART not complete I have used AT commands to read incoming bytes from serial buffer from SIM900A but I cannot get the complete message using the code below:

while(ss.available()>0)
{
 inChar=ss.read();
 inString+=inChar;
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

However this one below works:

if(ss.available()>0)
{
  inString=ss.readString();
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

I wonder what is the difference?

The data arrive over serial very slow compared to MCU speed. In the first snippet you stop reading at first gap between bytes (available is 0). In the second snippet the function readString will wait for the next byte until a second (at default).


How to accept user input (array, variables,...) I am working on a project using my Arduino mega2560 that triggers a solenoid (maximum of three solenoids), my camera and my flash (maximum of two flashes). The core routine is there, and working.

Now I want to refine this by adding a menu and 16x2 LCD with 6 buttons (up/down/left/right/select/reset). This is meant to be so the user can change the default values for:
- the amount of solenoids to be used (max 3),
- the amount of drops per solenoid (max 3),
- the time between drops and
- the time between active solenoids.
The layout of the menu is there, but not yet coded.

My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array. Through the menu the default values will be presented to the user. He can accept (select button) or change the value within certain limits using the up/down buttons.

The question is, what is an easy (for a beginner like me) to program way to accept user input and store this in the array, overwriting the presented default value? I also would like to have the possibility for the user to back out of a menu option and leave the default setting of the specific submenu value.

I was thinking of creating a shadow array with blanks, to be filled in by the user and copy all the values to the array that will be used by the core routine. Another line of thinking leads me to just abandoning the array and making use of a bunch of variables. As you will probably see, I need some advice here.

Thanks very much for reading and your advice, happy to answer questions that may help clarify the issue.

Regards, Kiezel

Your hardware side for the user to use can be based on an ADC type keypad pictured below, this only uses one pin and is pretty reliable. Note that not all code is given or design as it would be useless for learning and I also put effort into the code this came from, logic helps with the rest of each part...

The code is pretty simple:

You would write a function like so~

char keypad(int in){

if(in < 949){
    if(in > 935){
        return 's'; //select
    }
}

//......

else return = 0;
}

Next would be the code for the menu, you could hold the default values in an array and then modify them in the code, with set positions for defaults, considering

  My default values for solenoids used, droplet size, droplet timing, solenoid timing, camera delay and flash(es) delay(s) are put in an array.

Example from one of my projects

//Menu levels
#define level0 0
#define level1 1
#define level2 2
//master level of current point
#define mlevel 6
#define msub_level 7
//\\\\\\\\\\\\\\\\\\\\
#define sub_level1 0
#define sub_level2 1
#define sub_level3 2
#define sub_level4 3
#define sub_level5 4
// default level on boot
uint8_t current_level = mlevel;

Next would be to push the data to

int navigate(char key){
if(key == 'u'){
        if(current_level == mlevel){
        if(count == 3){ //roll-over

            count = 0;
            //update LCD....
        }
        else count++;
        //update LCD....
    }

    if(current_level == msub_level){

        if(count == 5){//roll-over

            count = 0;
            //update LCD....
        }
        else count++;
        //update LCD....
    }
}

//..... other ones here

    return count;
}

You would use the returned count to find the relative place in your array. e.g:

int default[n] ={x,y,z,...};

  get the key > put into navigate() > put into dafault[count];

You would also change the default after

It has been changed or,
The key has been debounced, i.e. use logic to determine if the key has changed state or,
The user has chosen 'accept'

Update of the LCD can be done at the points you want it done


Read OUTPUT pin value in Arduino Due I am trying to read the value of an output pin. online forums say that digitalRead(pinNum); should work, but that is not the case here. digitalRead always returns 0 (LOW).
This is the code:

int pin = 22; // or 13, or 3 ...
void setup()
{
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
}
void loop()
{
  digitalWrite(pin,HIGH);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
  digitalWrite(pin,LOW);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
}

printed values:

0
0
0
...

That method only works on AVR based systems.  It exploits a "feature" whereby the IO pin, when in OUTPUT mode, is also in INPUT mode at the same time, and reading the pin reads the value that the pin is being driven to by the digitalWrite function.

The same is not true of the Due, which is an ARM based system.  The IO pins function completely differently and the same "feature" cannot be used.

You will have to remember the state of the pin yourself.


Is EEPROM's location relocated on sketch compile? I assumed the microcontroller has 3 components as per storing data:
- flash memory for the program
- RAM for variables
- EEPROM for non-volatile user-storage

And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.

I compiled this program:

#include <EEPROM.h>

struct SettingsStruct {
  String server;
  String port;
  String user;
  String password;
  String description;
} gSettings = {
  "192.168.1.6",
  "8080",
  "fci blah vlak",
  "zangazang4",
  "Extra string here"
};

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

  //saveConfig();

  Serial.print(F("EEPROM size is: "));
  Serial.print(EEPROM.length());
  Serial.print(F(" bytes"));
  Serial.println("");

  loadConfig();
  Serial.print(F("Server: "));
  Serial.print(gSettings.server);
  Serial.println("");
  Serial.print(F("Port: "));
  Serial.print(gSettings.port);
  Serial.println("");
  Serial.print(F("Username: "));
  Serial.print(gSettings.user);
  Serial.println("");
  Serial.print(F("Password: "));
  Serial.print(gSettings.password);
  Serial.println("");
  Serial.print(F("Description: "));
  Serial.print(gSettings.description);
}

void loop()
{
  // nope
}

void loadConfig() {
    for (unsigned int t=0; t<sizeof(gSettings); t++)
      *((char*)&gSettings + t) = EEPROM.read(t);
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(gSettings); t++)
    EEPROM.write(t, *((char*)&gSettings + t));
}

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.

This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.

Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.

The EEPROM is a completely separate part of the silicon inside the chip. It has no address of its own.

You are making a fundamental error in what you are doing, though - you cannot directly store the contents of strings by looking at the addresses of those strings. The data in them is dynamically allocated in RAM and is completely separate from the object. You will have to come up with a different way to store your data.


Stepper motor release L298N I'm Driving a stepper using a L298N driver and an arduino mega. I want to release the stepper after the movement so it can swing freely, because it gets hot, and it doesn't need to hold position.

Anyone know how to do it? I'm using just the basic stepper library.

Thank you.

Usually you should set Enable (A and B) pins on L298 to LOW, effectively turning off the driver.


Can I make the BT module disconnect with a BT module and connect with another in the code? I am working on a project that requires a connection between two BT modules (HC-05) and a mobile phone. Later on, I encountered a problem: I can't connect two BT modules to one at the same time, So I thought about the possibility of ending a connection and starting the other one when needed. If that was possible, how can I do that in an arduino code?

One of the BT modules is a master which means it can't connect to the phone and it has to be a master because it must be connected to the other slave BT module.

Send AT+ROLE=1 to BT module to set module into master role.
To set module back to slave mode, send AT+ROLE=0

Also check this video, you have source code in the description. It will help you understand how to do it.


How can I make ultrasonic sensors resistent to splashes and dirt? I wasn't sure where to ask this question, but since it's actually an Arduino project, I'll try it here.

I want to upgrade my old car with ultrasonic parking sensors: I've already bought HC-SR04s as sensors and started to play on my breadboard.

But what I'm still unsure about: if I place them in my car's rear bumber, how can I make them resistent to rain or dirt or something like that?
As pictured on Wikipedia, the sensor is covered with a small piece. But what could I use to cover the holes in the bumper, without interfering with the ultrasonic measuring?

I don't think you'll be able to cover that sensor in a way that will still allow it to work. There are waterproof ultrasonic sensors out there, here's one on Amazon, for example.

The other thing you might want to look at is IR instead of ultrasonic. That's easier to weatherproof since the IR emitter/receiver are already covered. You'll probably have less range with IR, though.


Switching from one color to another I'm using ws2812b 2x2 LEDs and have it switching between green and red, but only one of my LEDs on my 2x2 is lighting up.
I'm using the "blink" FastLED sketch with Data pin 3 on my Arduino Uno, define led 4.
void loop() {
 // Turn the LED on, then pause
 leds[0] = CRGB::Red;
 FastLED.show();
 delay(5000);
 // Now turn the LED off, then pause
 leds[0] = CRGB::Green;
 FastLED.show();
 delay(5000);
}

For changing the led color or making any other led to glow you have to put the led number instead of leds[led number]  in this case so your code will basically look like.
void loop() {
 // Turn the LED on, then pause
 leds[0] = CRGB::Red;
 leds[1] = CRGB::Red;
 leds[2] = CRGB::Red;
 leds[3] = CRGB::Red;
 FastLED.show();
 delay(5000);
 // Now turn the LED off, then pause
 leds[0] = CRGB::Green;
 leds[1] = CRGB::Green;
 leds[2] = CRGB::Green;
 leds[3] = CRGB::Green;
 FastLED.show();
 delay(5000);
}

Hope this helps


Using delay(1000); without influence on analogWrite? So, I'm trying to read the voltage on analog pin A0 and make a "regulation", where if the voltage will be lower than 2.5V (analog value 512), then it should be output pin 9 used as PWM with duty cycle of 50% ( analogWrite(ledPin, 128); ) unless the voltage rises again higher than 2.5V.

Where/how am I supposed to use mentioned line ( analogWrite(ledPin, 128); in IF sentence, so it will be used continuous untill it is reached the limit?

PS: I just want to refresh LCD with frequency of 1 Hz while PWM works independently of delay(1000). How is that even possible?

How am I able to do that?

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const int numRows = 2;
const int numCols = 16;

void setup() {
  lcd.begin(numCols, numRows);
}

void loop() {

    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
        lcd.setCursor(0, 0);
        lcd.write(voltage);

        delay(1000);
}

The PWM started by analogWrite will not be influenced be the delay, because the analogWrite function only sets the registers and starts the PWM. The PWM generator is independent from the CPU on AVR microcontrollers. On esp8266 for example the PWM is generated with use of interrupt and it is too not influenced by the delay function. To stop the PWM you must call analogWrite with 0 or change the pin mode.


Turn Arduino on with timer every 24h I'm currently working on an Arduino project that sends the charge of my car battery once a day via an ESP8266 to me. During the winter I don't drive my car, and I would like to get informed when the battery drops beyond a critical value, so I can charge it and prevent damage.

So energy efficiency is important for the project, so it doesn't discharge the battery itself. I read a lot about sleep mode, efficient drop down regulators etc. These all have in common that the voltage regulator is always running, which is not what I want.

I'm looking for some kind of "swich-on-timer circuit". It should count down 24 hours and then turn on a relay or MOSFET, which connects the voltage regulator to power and with that turns on the Arduino and the ESP8266. When the Arduino has finished with the transmission, it resets the timer, which disconnects the voltage regulator from power, and so on. Of course, the timer circuit should use only very little power.

Does anybody know a circuit like that? I searched on AliExpress with all variations of words that came to my mind, without success. Or maybe an IC which can be used (easily) to create such a circuit?

One approach would be use of a DS3231 (Precision Real Time Clock) module.  Such modules sell on Ebay for under $1.  Search for ds3231 arduino.

Typically, these modules have a six-pin connector, with pins labeled 32K, SQW, SCL, SDA, VCC, and GND.  As noted in DS3231 specs, the INT/SQW pin is used either for square-wave output or for interrupt output.  On page 13 of specs, in the Control Register section, it says:

  Bit 2: Interrupt Control (INTCN). This bit controls the INT/SQW signal. When the INTCN bit is set to logic 0, a square wave is output on the INT/SQW pin. When the INTCN bit is set to logic 1, then a match between the time-keeping registers and either of the alarm registers activates the INT/SQW output (if the alarm is also enabled).

Initially, you would run a sketch to set up the DS3231: turn on a daily alarm, enable an interrupt rather than square wave, set the current time, etc.  Then, load an operational program that reads car-battery voltage each time it runs, and acts appropriately.

The DS3231 INT/SQW pin would be wired to the gate of a P-channel mosfet that switches 12V power to the Arduino.  The P-fet would turn on when the alarm's open-drain output pin INT/SQW turns on.  The operational program does its business and then clears the DS3231 interrupt flag, to shut down power until the next alarm occurs.  (For debugging, set briefer intervals than a day; for example, once a minute, as described in Table 2, Alarm Mask Bits, on page 12 of specs.)

Typically, the DS3231 draws 0.84 μA when running from a 3.3V battery, or 1 μA from 5V.  See Electrical Characteristics, page 3 of specs.


When does the ADC start reading again in interupt mode? Simple question, I have set my ADC to read in "continuous"/interrupt mode and I take the reading the following way:

ISR(ADC_vect) {
   int val = ADCL;
   val += ADCH << 8;
   ... //Code to do stuff with reading here.
   }

My question is does the ADC start the new reading as soon as I have read the ADCH register or does it wait for the code inside the interrupt to finish? Basically I need to know if having more instructions in the interrupt will slow down my reading rate.

I don't have an oscilloscope or any good way to measure my reading rate accurately enough to know if a few extra lines of codes is affecting the rate or not.

Your answer is correct. The ADC does indeed keep going independently of
what the ISR does. There is, however, a point I would like to make
clearer. You asked:

  My question is does the ADC start the new reading as soon as I have
  read the ADCH register or does it wait for the code inside the
  interrupt to finish?

The ADC starts a new reading as soon as it is done taking the previous
one, irrespective of whether you read ADCH or not. When your ISR
starts, the ADC is already busy making the following conversion. This
guarantees a steady conversion rate, at one A/D conversion every
13 ADC clock cycles exactly.

As a side note, you can read the result with

int val = ADC;

No need to read the bytes separately unless you are using a very ancient
version of gcc that does not know how to read a 16-bit register.


High Speed Thermocouple Readings I'm currently attempting to take readings from 10 thermocouples using an Arduino Mega. I've been using MAX31850 1Wire Thermocouple Modules (with the Adafruit breakout) to perform the readings, but their response time has been very slow (~500ms each). I'm not sure if most of this latency is coming from the IC, or from the communications protocol, or perhaps even the DallasTemperature library.

For my application, I need to be able to read all 10 thermocouples in at most 250 ms (and faster would be better) and so I can afford up to 25ms per thermocouple. I would also like to be measuring with a precision of about 1-2 F.

I assume I will probably have to use a different amplifier, and I've seen recommendations online of using an external ADC to achieve higher speeds, which I would be happy to do, but I don't understand why that would make a substantial difference on speed since the onboard ADC can already sample at about 1/10 ms.

I would greatly appreciate any recommendations on how to achieve these speeds.

1-wire transmission takes ~100us/1bit so 1ms/byte. so unless the adc is that slow, it shouldn't take you anywhere close to 500ms to take 1 reading, even if you factor in the overhead / reset.

there are dedicated chips but as you mentioned putting an amplifier (instrumentation amps for example) isn't that difficult. simpler with chips with built-in PGA + differential adc. My favorite here are some of the AVR chips (ATtiny85 or ATmega32U for example). But lots of Freescale / STM32F3 chips also work, so long as you are willing to dive into their and roll your own. Lots of fun.


Can someone check my code? My Arduino isn't doing a consistent count cycle I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.

The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.

The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.

The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position.
The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.

It then repeats this sub cycle about 20 times.

After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.

It then does this whole complete cycle 20 times before stopping.

There's a momentary switch as well, which when pushed, is supposed to restart everything again.

It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.

I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.

Any ideas what I could try?

int Relay_1 = 10;           //first Relay
int Relay_2 = 11;           //second Relay
int Prox_Input = 12;        //input signal from proximity sensor
int Switch_Input = 13;      //the switch

int Cycle_Number = 20;      //number of repeating number of "complete" cycle
int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

bool Button_Pushed = true ; //the state required for the button
int i, j;

void setup() {
  /*configurate the output relays to be begin "low"*/
  pinMode(Relay_1 , OUTPUT);
  digitalWrite(Relay_1, LOW);

  pinMode(Relay_2 , OUTPUT);
  digitalWrite(Relay_2 , LOW);
  /*===========================================================*/
  /*configurate the input switch and sensor*/
  pinMode(Prox_Input , INPUT);
  pinMode(Switch_Input , INPUT_PULLUP);
  /*===========================================================*/
  /*configurate Serial port if you want it*/
  Serial.begin(9600);
  /*===========================================================*/
}

void loop() {
  if (Check_Button() == Button_Pushed) { //check the button
    for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
      for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
        digitalWrite(Relay_1 , HIGH);
        delay(Delay_Sub_Cycle);
        digitalWrite(Relay_1 , LOW);
        while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
      }
      digitalWrite(Relay_2 , HIGH);
      delay(Delay_Sub_Cycle);
      digitalWrite(Relay_2 , LOW);
      delay(Delay_Cycle);
    }
  }
}

bool Check_Button()  {
  int Reading_1;
  int Reading_2;

  Reading_1 = digitalRead(Switch_Input);
  delay(20);
  Reading_2 = digitalRead(Switch_Input);
  if ((Reading_1 == 1) && (Reading_2 == 1))
    return true;
  else
    return false;
}

The only reason it might "jump the gun" would be this line:

         while(digitalRead(Prox_Input) == HIGH){}          // waiting the sensor signal

I suggest you check for a transition, that is, make sure the proximity switch has become LOW, and then wait for it to become HIGH again. So for example, if sending HIGH to the relay should make the proximity sensor read LOW, then put a loop in to make sure it does that, before proceeding.


Error in sending AT commands in esp8266 connecting to arduino IDE I am working on esp8266 with Arduino.

I have connected pins like arduino-esp 3.3-vcc
gnd-gnd 3.3-CH_PD RX-TX TX-RX  and reset to gnd using 3k resistor.

I couldn't send AT commands in serial monitor in Arduino IDE.

Later I connected a capacitor between Vcc and Gnd. Now I could send AT commands and I am getting same commands back. Whatever I entered, I am getting the same back.

I didn't get reply as OK. And I got some random characters too. Can anyone help me with this?

Looks like your connection is somewhere missing.

Connect CH_PD and reset pin to high--i.e. 3.3v.


Can I change the USB device name of Arduino? I have several Arduinos connected to my Windows PC, and they appear as follows:

  COM7 (Arduino Uno)
  COM11 (Arduino Uno)
  COM13 (Arduino Uno)

So there's no way to tell which is which, and when I want to upload a sketch to one, I have to unplug the others to make sure my code goes to the right one.

Is there a way to change the "Arduino Uno" description?

(I found a similar question but that was about Mac specifically).

You'll have to change the software on the Arduino USB chip itself, and you may need to modify the drivers for the Arduino USB interface on the computer side.  It's not trivial, and probably not worth it.

However, Windows attempts to use the same serial port for the same devices in the same USB positions, so if you figure out which is which (blinking the LED at different frequencies) then you can mark the USB port itself with the com number that Windows uses when you plug an arduino into it.

If you use a hub, and you move that hub to a different port, the com numbers will change, but if you keep it in the same port, then it too will try to have them match what they have been in the past.

It's an annoyance, but it's a design decision by arduino.cc.  The old FTDI chips kept their assigned com port numbers because they have individual serial numbers and windows would attempt to reassign the same com port to the same chip each time it was plugged in, regardless of its location.  When Arduino.cc moved to a programmed MCU for the USB interface, they chose not to provide USB serial numbers, and thus windows has little option but to try to keep things straight by determining the location in the USB hierarchy that the device is connected, and try to keep com port assignments the same using that method.


Building Arduino Nano from components At this stage, my finalized design includes Arduino Nano 3.0, a breakout board and a few electrical components on a breadboard.

Will there be an appreciable cost savings from not buying a ready-made Arduino? The Arduino Nano clone being used costs $17.20.

And is it a good idea if everything is soldered on to a custom fabricated PCB board, including the components of Arduino Nano 3.0? The PCB board will cost around $10 at the quantities I'm starting with.

You can probably do a lot better than $17 but not much better than $8:

http://www.ebay.com/itm/Mini-USB-Nano-V3-0-ATmega328P-5V-Micro-controller-Board-For-Arduino-compatible-/130977189883?pt=LH_DefaultDomain_0&hash=item1e7ed94ffb

If you don't need USB, you can use a Pro Mini and they go for about $4 and that's really hard to beat.


How to externally power HC-05 module with Arduino Pro Mini? guys, I am new to arduino. I am trying to power my HC-05 (5v with regulator to 3.3v) from Arduino Pro Mini 3.3v but I can't get it to power on.

There is a problem: The site I bought HC-05 from says that it needs 3.3-6 volts to power on but the back of HC-05 shows only 5v pin. To confirm that it runs only on 5v I need to connect it to external 5v supply.

But how do I make the connection? What do I connect to negative of the battery if I choose to externally power it?

Second Problem: If my HC-05 turns out to need only 3.3v input voltage, how many coins cells do I connect in series to power both pro mini and HC-05 module.

I am using a coin cell (3.3v) for powering the pro mini.

Thanks...

The HC-05 (the PCB that is mounted on the PCB of the module) itself runs on 3.3V. Many microcontrollers run on 5V, so people are selling the HC-05 mounted on a PCB with extra components, for example a voltage regulator from 5V to 3.3V.

Voltage regulators have a minimum input voltage for which they can hold the output voltage at the specified value. Refer to this question for more information about this. So supplying the module with 3.3V instead of 5V will result in a supply voltage for the HC-05, that is significantly lower than 3.3V, so it most likely won't work correctly.

If you want to use the HC-05 module as it is, you have to provide 5V supply voltage from another source. In this case be sure to connect the grounds of both power supplies, so that they have a common ground.

If you don't want to use an extra power supply, than you may bridge the voltage regulator on your modules PCB and provide the 3.3V as supply voltage, that are used by the Arduino. Doing so would not be an easy task for a beginner, since you would have to solder small SMD components. Also the outlay of the modules PCBs are very different (depending on manufacturer). Note that in this case you should never ever put 5V on the Vcc pin of the module again, since it is then directly passed on to the HC-05 chip, which would be destroyed from the 5V supply.


How to prevent the garbage data when the serial port is initialised? I use Arduino Uno. I get garbage in Serial Monitor or HyperTerminal right after I connect to the port. Here is an example code:

void setup() {
  // initialize serial:
  Serial.begin(57600);

}

void loop() {

    Serial.println("Test");
}

An example screenshot of the output. When port is re-connected the first received data is not Test:

So my problem is when the port is initialised the first data received is garbage. Is there a way to prevent this happening? Is that something to do with bootloader baud rate? I tried other baud rates and get same issue and I really want to use 57600 or 115200 baud rate.

There are probably a number of reasons that might contribute to the problem that you are observing:

You are trying to send the string "Text" within the main loop without any delay between println calls. So the microprocessor is running at full speed and trying to send the string "Text" much faster than the baud rate can accommodate. The serial interface has a finite I/O buffer, which is probably filling very fast and overwriting old values in the middle of serial transmission. Hence potentially garbage characters.
Even when HyperTerminal is not running, the PC and Arduino are exchanging serial messages. So when you start HyperTerminal at some arbitrary time, the data in the serial buffer might not correspond cleanly to the start or end of a transmission.

As an alternative, you may want Arduino wait for a serial command from the PC before starting to send the serial data. For example, when using the Serial Monitor, you may send a key press to Arduino, which would then start sending data so that no data is lost while there is no body listening on the PC side or while a terminal program is not running.

Finally, flushing the serial buffers on either side of the serial connection might help you clear partial serial messages.


Multiple SPI reads slows down read time dramatically I have a two channel 24bit ADC(LTC2402- http://cds.linear.com/docs/en/datasheet/24012f.pdf) that I am communicating with via Arduino Leonardo(Leonardo because it was free!). If I attempt to do multiple reads the SPI becomes very slow while if I do a single read the time to send is what is expected. I have have integrated with python and timed the different transactions. A single read takes around 170ms( this is for both channels and the datasheet of the ADC indicates about 65ms per conversion(table 3 arduino as external sck etc.)) BUT if I do 5 reads the time taken is about 1.5s(expected about 0.65s) 10 reads take about 3s and 20 about 6.5s. Doing no ADC conversions and just serial comm to python is less than 2ms.

The relevant python code is as follows:

def getdata(ser,code):#ser is the arduino that has been connected, code is for writting to arduino
    ser.write(code)
    ch0=float(ser.readline().decode()[:-2])
    ch1=float(ser.readline().decode()[:-2])
    return ch0,ch1

code='1'
code=code.encode()

a=datetime.datetime.now()
ch0,ch1=getdata(ser,code)
b=datetime.datetime.now()
print(b-a)

The arduino code is as follows. The code has been simplified to just the necessary byte reads from the ADC, all other code has been removed to ensure the delays are coming from the SPI.transfer(0x00). The full code retrieves 4 bytes per channel and converts this to voltage and returns these values.

#include <SPI.h>

const int ltcs = 3; //active low ADC enable

float ch0=0.0;
float ch1=0.0;
byte b0;

void setup() {
SPI.begin();
SPI.beginTransaction(SPISettings(200000, MSBFIRST, SPI_MODE0));

Serial.begin(9600); // set the baud rate

pinMode(ltcs, OUTPUT);
digitalWrite(ltcs, LOW);
}

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

   int data = Serial.read() - '0';
   if(data>0){

   getdata2(ch0,ch1);
    //getdata2(ch0,ch1); //run multiple getdata2 to test multiple conversions
   //getdata2(ch0,ch1);
    //getdata2(ch0,ch1);
   //getdata2(ch0,ch1);

    Serial.println(0.2);
    Serial.println(0.4);

  }
  }
  }

 void getdata2(float &ch0, float &ch1) {
   ch0 = 0.0;
   ch1 = 0.0;

   for (int i = 0; i < 2; i++) { //Do twice to retrieve both Channels
     while (digitalRead(MISO) == HIGH) {
     }

       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
       b0 = SPI.transfer(0x00);
   }
   }

Can anyone help me? I have tried different SPISettings with no change. Interestingly I also find that the Baud rate does not change either.

Thanks for the help if any

I found the error. Unfortunately I was so busy blaming the code and assuming it was my lack of arduino knowledge that I forgot to check the hardware specs. I thought I was using the maximum external oscillator frequency(f_EOSC) of 300KHz, but in fact was using the 50Hz internal oscillator frequency with an external f_sck from the arduino. This means that the conversions where in fact running at expected times. The thing that threw me off was that the first reading was much faster than the rest. This was most likely because at first read I only had to wait for one channel conversion as the other was already done before I request the data and so the first readings wait time is only as long as a single channels conversion. I would need to implement a 300KHz external clk if I want faster conversion speeds. Thanks for the help for those who tried:)


Extremely cheap "Arduino" for single tasks? I have been thinking of a million things to do with my Arduino, but those things are extremely simple and it would leave my Arduino as a $25 waste.

For example, programming Arduino to control my living room lights with my smartphone ... I was thinking of connecting the Arduino in the wall, onto the light switch wires. I am looking for a "permanent" solution, but I figure this would leave me with a $25 waste of circuitry inside my wall.

Are there any "Arduino" types of electronics that perhaps have many less ports, JUST enough to get a single task done?

Digispark comes to mind, or any of the ATTiny breakout boards at Tindie. Or, make your own PCBs, I just now finished soldering a few ATMega328p circuits to boards I designed. Microcontroller is $1.50, PCBs range from $2 to $8 each, time is "free."

Also consider "compatible with" designs; while you're not directly supporting the ecosystem, if you've already paid full price once and your conscience is clear, eBay has plenty.


problem on implementation of the ultrasonic circuitry I used an Arduino Uno on my project to produce a frequency greater than 35000Hz and the output of digital pin was connected to the ultrasonic transmitter circuitry:

However, it's not working on the transmitting side. Here's the Arduino code:

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

void loop()
{
    pinMode(13,OUTPUT);
    pinMode(12,OUTPUT);
    int pirSenses = analogRead(A1);
    int pirOuts=11;
    pinMode(pirOuts,INPUT); /*PIR sensor 1*/
    int pirSense = analogRead(A0);
    int pirOut = 10;
    pinMode(pirOut,INPUT); /*PIR sensor 2*/
    Serial.println(pirSense);Serial.println(pirSenses);

    if (pirOut || pirOuts == HIGH)
    { /*tone produces ultrasonic frequency*/
        delay(8000);
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else if (pirOut||pirOuts==LOW)
    {
        tone(13, 50132); delay(100); noTone(13); delay(10);
        tone(13,54621);  delay(50);  noTone(13); delay(50);
        tone(13,35689);  delay(60);  noTone(13);
    }
    else
    {}
}

And the transmitter (model "MCPCT-G5100-4139") specification:

Please help me with this problem. Thanks!

Your ultrasonic Transducer driver circuit isn't doing a very good job. At most you are getting only a few milliwatts output to the transducer. Your circuit is applying 12 volts through a 2.2K resistor to the transducer, and your Q1 transistor is merely shorting out the Transducer.

From viewing the data sheet on your transducer, it looks like a tiny loud speaker and not a Piezo device. But that is OK.

Try the following push pull driver circuit.  I have tried to keep it simple, but you would need to come up with a PNP transistor (in addition to your existing NPN transistor).

The V2 square wave is your 5 volt output from Arduino.

Also, notice that I have shown the driver circuit using 5 volts, not 12 volts. Using this circuit, if you use 12 volts supply, the output doesn't get any more powerful, and just causes more heating in the transistors.

EDIT 1  :  IMPORTANT :  Don't leave your output pin in the HIGH state.  This turns on transistor Q1 and causes sustained current in the Transducer.  To alleviate this, insert a 47uf capacitor in series with the transducer.

EDIT 2 :  Changed schematic to include output capacitor.


Reduce PWM Frequency Arduino DUE I'm newbie in arduino due. I need to reduce the default PWM frequency of arduino Due. Anyone have any tutorial to do this? (Frequencys like 25hz, 50Hz for example)

I read in some posts, if i change the PWM frequency, i make changes in internal timers of arduino and i loss functions like delay(), millis(), etc.

Exits any form to not lose these functions?

Thanks a lot!

The Palatis Softpwm library can generate PWM on any digital pin with (almost) any frequency. Example for 25Hz:

#include <SoftPWM.h>
SOFTPWM_DEFINE_CHANNEL(0, DDRB, PORTB, PORTB2);  //Arduino pin 10
void setup() {
  // begin with 25Hz pwm frequency
  Palatis::SoftPWM.begin(25);
  Palatis::SoftPWM.set(0, value); // value is 0 to 255 just like normal Arduino analogWrite
}


Programmatically Change Arduino Com Port Name I have some devices that, when I plug in, will display a unique name, usually a serial number, as opposed to "COM #" is there any way I can have my Arduino Uno (or Mega) give itself a different name in my program's set up structure?

Edit: My purpose here is that I'm writing a program on the computer side that needs to find the Arduino among multiple possible COM ports. I'm deploying this program over multiple computers that I don't have admin access to so changing the registry is likely a non-starter.

Right now, I'm going through each port and sending a *idn?\n (which my program responds to with a specific string). For another device I have, I can search the possible connections for a port named [device serial number] and test that one first.

On Windows you can change the "Friendly names" assigned to devices and COM ports are devices.  The process is basically open the device manager, open the device properties, find the 'Device Key' and then locate that in the registry and change the 'Friendly Name' value.

See this page for more details:
https://www.eightforums.com/customization/15321-tutorial-how-change-device-names-device-manager.html


How do send sketch updates to devices without the editor? I'd like to update the sketch of a device that a friend out of state is testing. I could have them install the full editor and send the source code but I'd rather not require them to do something so technical.

Is there a way to compile the firmware binary and push that out to a device over the COM port more directly?

In general, yes.

The compile routine creates a .hex file in a temporary directory that contains the flash image for the device. One can use AVRDUDE to upload this .hex file to the Arduino from the command line. It is simply a matter of getting the command arguments correct in order to tell it where and how to upload the image. Enabling verbose output in the IDE will tell you both exactly where the .hex file is located and what arguments are required for the board selected.


Can I jump the delay in loop? #include <Servo.h>

Servo myservo;
int pos = 0;
int servo_pin = 3;
int led_pin = 4;

void setup() {
  myservo.attach(servo_pin);
  Serial.begin(9600);
  pinMode(led_pin,OUTPUT);
}

void loop() {
  if (Serial.available()) {
    char serial = Serial.read();
    if (serial == '2') {
      servo();
    }
    if (serial == '1') {
      digitalWrite(led_pin,HIGH);
    } else if (serial == '0') {
      digitalWrite(led_pin,LOW);
    }
  }
  delay(100);
}

void servo() {
  for (pos = 0; pos <= 180; pos += 1) {
    myservo.write(pos);
    delay(5);
  }
  delay(5000);  // problem is here
  for (pos = 180; pos >= 0; pos -= 1)
    myservo.write(pos);
  delay(5);
}

When I run this code, and send 2 servo functions start but there is an delay function. Now I want to send 2 then send 1. When I do this, the first servo starts but the LED starts after the servo function. I want to start this too at the same time.

Make little task using millis function.
// GLOBAL VARIABLE
uint32_t taskMillis = 0;

....

// IN LOOP
if (taskMillis && millis() - taskMillis >= 5000)
{ /* SWITCHES DIRECTION */ }

With that code you can make two tasks(one to switch direction, second to move Servo by X deg).
Here is video about this topic.
https://www.youtube.com/watch?v=v5SpPXMmHJE
I hope this anwser will help you.


9x servo on Arduino Nano? I saw this project with multiple servos: In Servo We Trust! Let's control 135 servos with a single Arduino! I wanted to miniaturize this project.

BUT instead of triangles i will use SQUARES.

:EDIT: summing UP

For now project stops, not forever. I bought 9 servos on aliexpress and im waiting for them to be delivered. Also, im making a 3D project in AutoDesk Maya 2018, planning and will sbow you the results soon how im gonna make it work.
I was thinking about adding 1 more servo and hc sr06 distance sensor. I was thinking about the sensor will detect person, servos and mirrors will also follow the person. But idk if im gonna make it to the final project.

I bought arduino nano that will be powered from the battery
All servos will be powered with electricity from the wall 5V 5A.The servos wont be on heavy load so it will be enough i think.If any problem occurs I will use 10A.

ALSO SORRY for not editing this POST earlier.

I would like to thank everybody for giving me such a great advices, I will post my AutoDesk project soon.

I'm afraid that with PWM controler I won't be able to do that.

Chances are that any PWM controller is going to let you control each output independently.

According the the servo library documentation, the library can handle up to 12 servos on a single Arduino, so your project should be feasible. It will however reduce the number of PWM pins available from 6 down to 4.

  Will a 9V battery power all these servos?

No! Not a chance.

Typical 9g servos consume 150 mA without any load, and stall at ~700-900 mA. A typical 9v has ~500 mAh capacity, and most data sheets show loads of ~100-150 mA max. Your 9v might be able to supply a few amps for a few seconds before they heat up and slow down.

If your load is very light 9 servos will consume ~900 mA; an ideal 9v would last at most 30 min with this load, but real batteries aren't ideal and will heat up and loose efficiency.

Near maximum load your 9 servos will draw ~7000-9000 mA, well beyond the capabilities of a 9v. However those numbers are for 5v so you could cut them all in half.

If you used an appropriate 5v step-down DC-DC supply you might be able to power all 9 servos for a few seconds before the batter overheats and gives up.

If you powered them directly, the servos will have to dissipate more heat, and will draw extra power, could damage the servos if the batter could supply enough juice.


Maximum Capacity Debugging 1. Example

Check the program below for an Arduino Nano, Old Bootloader, for variable values of N.

For low values (N<=1857), the program outputs "[FFFFFFFF]",
For higher values (1858<=N<=1953), the program outputs unpredictable variations of this string,
For higher values (1954<=N<=1955), the program outputs fails flooding the symbol "[",
Over a certain value (1956<=N), the programs does not output any character.

I didn't check extensively these results, which could be very different actually, and totally platform dependent, but I guess, reproducible.

Note that no dynamic allocation is being used.

Note that everything is initialized, first 4 values to 0xFF, next N-3 values to 0x00 (Ref.).

The compilation do not show any relevant alert, showing a modest 10% capacity usage.

Sketch uses 3206 bytes (10%) of program storage space. Maximum is 30720 bytes.
Global variables use 196 bytes (9%) of dynamic memory, leaving 1852 bytes for local variables. Maximum is 2048 bytes.

It is evident from this example how to figure the proper value of N, indeed a capacity related issue could be expected (Ref.).

Note these values are by far less than the "guess" value of N=32767 for 1 byte variables (?) (Ref.).

2. Problem

Now, with a considerably huge, real program, I am having the same issue regarding those unexpected results, so I am almost sure (few moments ago) than this is the cause.

When exceeding some "~maximum~" level, the program starts failing, and when "~releasing~" this capacity, the program starts working well (without those deleted functionality of course!).

3. Question

How should I debug, measure, dimension, or prevent this situation, and specify when it is the proper time to keep this processor, and when should I move into a bigger one, when clearly the compiler is not a reasonable guess?.

// CAPACITY TEST
#include <SoftwareSerial.h>

// SET THE PROPER N VALUE
// N<=1857: Last Valid Result
// 1858<=N<=1953: Last Observable Output - Single Char
//     PC=0x0444. [AVR MEMORY] Writing to memory location 0x0948 outside of memory size 0x0900. [UP0]
// 1954<=N<=1955: Last Observable Output - Flood
//     Invalid opcode 0xFFFF at PC=0xA402
//     PC=0x0444. [AVR MEMORY] Writing to memory location 0x0948 outside of memory size 0x0900. [UP0]
// 1956<=N: No Output
//     Invalid opcode 0xFFFF at PC=0xA402
#define N 1857

void setup()
{
    Serial.begin(38400);while (!Serial){;}

    byte a[N+1]={0xFF,0xFF,0xFF,0xFF};

    char si[3];
    Serial.print("[");
    for (int i1=0;i1<=N-1&&a[i1]!=0;i1++){
        sprintf(si,"%02X",a[i1]);
        Serial.print(si);
    }
    Serial.print("]");
}

void loop(){}

From the bottom to the top of the RAM, you have:

the .data section (statically allocated initialized variables)
the .bss section (statically allocated non initialized variables)
the heap (dynamic allocations with malloc() and new)
free space
the stack (return addresses and automatic local-variable allocations)

See the memories of an Arduino for a more lengthy
discussion.

The sizes of the .data and .bss sections are known at build time. This
is the “Global variables” memory usage reported at the end of the
compilation. The rest of the RAM is available for the heap and the
stack. This is the amount reported as “leaving 1852 bytes for local
variables”, where “local variables” is a slight oversimplification.

Your example program doesn't use heap allocation. It does use some
static allocation, mostly for the Serial buffers, and a lot of stack
for:

the return addresses from the calls to main() and setup() (4
bytes)
the local arrays a and si (N+4 bytes)
the memory needed by sprintf() or Serial.print() (unknown)

Even ignoring the last item, you can see that the whole RAM will be
consumed when 4 + N + 4 = 1852, i.e. N = 1844. As you make N larger than
this value, the stack bumps into the .bss section, and you start
corrupting your global variables. The behavior you describe is
consistent with the program corrupting the internal data structures of
the Serial object.

  How should I debug, measure, dimension, or prevent this situation

There is no easy way to determine beforehand the amount of heap and
stack your program will consume. The usual solution is to measure and
report it at run time. See for example the MemoryFree library
(there are many similar to this).


Analog pins as output by using digitalWrite I am making a triac-controlled light dimmer. To control the triac I want to use pins A4 or A5, because others are occupied. I have tried the following functions and methods, but nothing seems to put the pins to HIGH state:

 1. pinMode(A4, OUTPUT);
    digitalWrite(A4, HIGH);
 2. pinMode(18,OUTPUT);
    digitalWrite(18,HIGH);
 3. DDRC |= (1 << DDC4);
    PORTC |= (1 << PC4);

I have tried the same things with A5 and other A# pins to no avail. The only pin that works is A0. Only when the triac is connected to it, the lamp lights on.

Is this a valid way to set analog pins?

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

void loop(){
  digitalWrite(A4, HIGH);
}

Edit: My code was quite messy, it appears that some other functions prevented from using pins A4 or A5. It is working now.
It was the DS1307Emulator library. After initialization I had to use DS1307Emulator.busDisconnect();
Didn't know it uses I2C.


Read all relay output (high or low) from Bluetooth through Android app I have written the following code for Arduino:

#define relay2 2
#define relay3 3
#define relay4 4
#define relay5 5
#define relay6 6
#define relay7 7
#define relay8 8
#define relay9 9
byte val;
void setup() {
  Serial.begin(9600);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  pinMode(relay5, OUTPUT);
  pinMode(relay6, OUTPUT);
  pinMode(relay7, OUTPUT);
  pinMode(relay8, OUTPUT);
}

void loop() {
  int a = 0;
  if (Serial.available()) {
    val = Serial.read();
    Serial.println(int(val));
    //Display received value on Serial Monitor
    //ASCII VALUES
    if (int(val) == 49) //Turn Light1 ON 1
      digitalWrite(relay2, HIGH);
    else if (int(val) == 50) //Turn Light1 OFF 2
      digitalWrite(relay2, LOW);
    if (int(val) == 51) //Turn Light2 ON
      digitalWrite(relay3, HIGH);
    else if (int(val) == 52) //Turn Light2 OFF
      digitalWrite(relay3, LOW);
    if (int(val) == 53) //Turn Light3 ON
      digitalWrite(relay4, HIGH);
    else if (int(val) == 54) //Turn Light3 OFF
      digitalWrite(relay4, LOW);
    if (int(val) == 55) //Turn AC ON
      digitalWrite(relay5, HIGH);
    else if (int(val) == 56) //Turn AC OFF
      digitalWrite(relay5, LOW);
    if (int(val) == 57) //Lock the DOOR
      digitalWrite(relay6, HIGH);
    else if (int(val) == 48) //Unlock the DOOR
      digitalWrite(relay6, LOW);
  }
}

Now on the Android side I have written the following code:

 //Bluetooth connection code ....
  mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

  mmSocket.connect();
  mmOutputStream = mmSocket.getOutputStream();
  mmInputStream = mmSocket.getInputStream();

  int byteCount = mmInputStream.available();
  if (byteCount > 0) {
    byte[] rawBytes = new byte[byteCount];
    mmInputStream.read(rawBytes);
    String string = new String(rawBytes);
    Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
  }

Now it works perfectly when I press a button to turn the light on/off. But I want to read all relay current status (high/low) when a Bluetooth connection is made.

So basically after connecting to the Bluetooth module I want all relay status.

How can I do that?

It's rather undocumented, but you can actually use digitalRead(relay2); on a pin (ex relay2) that is set to OUTPUT. I discovered it accidentally, and it worked exactly as expected, so i looked it up and it's legit. This is very handy to check an output pin's hi/lo state from a non-connected part of the code.

There is a tiny performance dip compared to reading just a variable, but it usually won't be noticed. If you need top performance, wrap the digitalWrite() with your own function, and set a variable with the new state:

int myState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void digitalWrite2(int pin, int value){
   myState[pin] = value; // copy setting to a global array
   digitalWrite(pin, value); // apply the setting as intended
}

Now, you can instantly get all the relay states from the myState array, provided they've been set with digitalWrite2. The other advantage to an array is that you can easily persist it to SPIFFs or EEPROM as-needed and recover the relay states on the next boot.


what is good practice around initializing variables Should vars be initialed when declared or in setup fuction?
Safe to assume compiler will initialze?
Boolean x;      --- init to true/false here?
Void setup()
.
.            --- or init here?
.
Void loop()
If (x)       --- x is unknown state if not initialized.

Initializing a global is appropriate if you know in advance that it should always have a given value at startup. The compiler will generate a globals image in ROM that will be copied into RAM before any of your code is executed.

Safe to assume compiler will initialze?

The compiler will initialize to 0, a global not specifically initialized by you. Let's take the case of your Boolean. '0' means 'false', right? So 'x' is pre-initialized to 'false'. But I, as the reader (or yourself, six months later) may not know whether you intended this to be initialized to 'false' (the default value) or forgot to initialize it. Specifying it to be 'false' may not have any different effect on the code, but it does inform me or your future self, that you meant it to be set 'false' at startup. Remember that your code communicates to people as well as to the compiler. Write it so you or I will not only be able to understand it, but won't be able to misunderstand it.
If you initialize it in setup(), the compiler generates code in setup() specifically to do that. If the setup() function needs to decide during startup, what the initial value of that variable should be, then this is the place to do it. Otherwise, the extra code just takes up space in Flash. It's not any more harmful than wasting those few extra bytes of code-space, but it doesn't accomplish anything more than letting the globals image do it.
Whatever you did or didn't do with 'x' at load time or in 'setup()', it will persist into 'loop()', so 'x's state isn't unknown when you get there. (If I misunderstood that part of your question, please edit it in your question.)