DMX dimmer appears to receive data from Arduino but connected lights do not respond I'm trying to control a DMX dimmer (eurolite ES-12 IEC DMX Switchback) through an Arduino Mega. In an earlier test, we were able to make one RGB DMX light run through the color spectrum. Now, a technician has installed this ES-12 dimmer pack with 12 1-channel DMX lights attached to it. The dimmer has some kind of built-in testing program and all the lights work.

The documentation on the dimmer is very sparse regarding the programming side of things. The dimmer is set to mode d--- and when the Arduino is running its program, a little green light flickers next to the d---, apparently responding to the signals it's receiving, like so: d---. Unfortunately, that the only light that responds.

I've tried using the DMXSimple library (the DMX is connected to pin 3), but even the example code (after correcting the brightness-- to ++) does not get any response -- none at all, not even the little green light. The only thing the little green light responds to is an analogWrite() on pin 3.

I'm guessing it's an addressing issue, but I don't know enough to fix it. As I understand it, the dimmer is seen as the controller and is sent a LOW on channel 0 as the Start Code (SC): http://www.dmx512-online.com/packt.html. The first light on the dimmer will then be channel 1, the second light channel 2, etc. (since, the technician tells me, they are 1-channel lights). Is this correct? Or is the dimmer its own universe that should be addressed in some other way?

The light technician, Toby Peperkamp, came with the solution. I'm not sure exactly where he found the information, but apparently the protocol for non-RGB DMX lights requires that the lights be switched on to maximum (255) at the beginning of the connection. So I added that to the setUp() and all the lights started to respond.


Use the stepper motor library with the A4988 driver? I want to use this library: https://www.arduino.cc/en/Reference/Stepper
#include <Stepper.h>

The wiring for my driver is shown here:

https://www.pololu.com/product/1182
From the library, I'm stuck at the motor pins:
#define motorSteps 200
#define motorPin1 2    // STEP pin
#define motorPin2 3    // DIR pin

Stepper myStepper(motorSteps, motorPin1, motorPin2);

Is this library not compatible with this stepper motor driver? Or what needs to be defined for it to work?
More details on the library are here: http://www.tigoe.com/pcomp/code/circuits/motors/stepper-motors
The basic section of my code that works without the library is this:
digitalWrite(stepPin, HIGH);
delay(wait);
digitalWrite(stepPin, LOW);
delay(wait);

Yet, the two-wire circuit part of the library uses motorPin1 and motorPin2 in a way I don't understand:
switch (thisStep) {
  case 0:  // 01
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 1:  // 11
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 2:  // 10
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, LOW);
  break;
  case 3:  // 00
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, LOW);
  break;
}

https://github.com/arduino-libraries/Stepper/blob/master/src/Stepper.cpp
How should motorPin1 and motorPin2 be defined?

That library is not compatible with the A4988. It is intended to do the same job that the A4988 does. You provide a step direction and an instruction to step, and it does the stepping for you.
To use the A4988 you just set a pin HIGH or LOW for the direction, then toggle another pin to make it step. You don't really need a library for that.
However if you do want to abstract it with a library and add lots of cool extra features then you should look at AccelStepper which supports 2-wire drivers like the A4988.


Can you use an input pin instead of ground in Arduino circuitry? Beginner here: Would the circuit in the picture work or do input pins not absorb the energy as ground does? I know setting the pin as an input makes the direct 5V connection safe but maybe I'm mistaken. I'm trying to understand the nature of how these connections are made. Thank you in advance!

An input pin can only sense the voltage that is applied to it - whether it is above or below a pair of thresholds.

In your existing circuit when the button is not pressed the voltage sensed by the pin is 0V because it is connected to 0V (also known as Ground) through the resistor. When you press the button the input pin is connected directly to +5V, so the pin senses 5V.

If you remove the resistor or the connection to ground the pin can still sense 5V on it when the button connects it to 5V, but when you release the button the input pin then isn't connected to anything at all. It's not connected to 0V, so it can't sense what voltage is there - there simply isn't any voltage connected to it (no voltage isn't the same as 0V).

In this case the pin is said to be "floating". It's neither HIGH (5V) nor LOW (0V), it's just dangling around not knowing what it's doing.

If you want to get more technical and look at the mechanics of it, it's helpful to know that the gate of a MOSFET (which is what the input pin actually is) looks to all intents and purposes like a small capacitor.  When you connect the input pin to +5V the capacitor is charged up (current flows into it from 5V to charge it). When you connect the input pin to 0V it discharges (current flows out of the capacitor down to 0V). When charged you have a HIGH and when discharged you have a LOW.

However when a charged capacitor has no connection it (for a certain amount of time, due to self discharge) keeps hold of its charge. So if you charge it with +5V and then disconnect it you will still get +5V on the capacitor. That is until it discharges through internal leakage currents.

Those leakage currents though are so small and the capacitor is so sensitive that the input pin acts like a radio antenna. It picks up noise from the surrounding area (electromagnetic waves) which can charge and discharge the capacitor pretty much at random. So at times you may see the input as HIGH and at other times as LOW, purely depending on chance. And the longer your wires the more noise it will pick up.

The worst source of noise is the 50/60Hz mains hum that is all around you. You can see this in reality if you graph the voltage on a disconnected ADC pin and bring your hand close to it - you act like a capacitively coupled antenna and you can see the mains waveform on your graph.

It's the same on a digital input pin, except that it converts it to a square wave as it passes the thresholds (you might like to look at schmitt triggers for more detail about how it does that).

So adding the pull down (or pull up if you prefer) resistor is critical to making the input pin see what you want it to see, and not just random noise.

Since the input is like a capacitor selecting the right value of resistor can be quite important in some situations. For a simple button like this there's nothing to worry about, but for something like a rotary encoder where the input signal may change more rapidly the resistor value does become more of a concern.  Have too high a value and the gate will take too long to discharge (or charge if it's a pull up resistor). Too low and too much current could be wasted through the resistor when the button (or encoder) is active (potentially damaging the button if it's a low current sensitive device).


Using LDR and RGB Led to get R,G,B values Has anyone tried using a setup of RGB LED directed to cuvette and the LDR on the opposite side? using arduino to and get the RGB values..

Currently having problems with calibration... I was able to get R,G,B values of colored papers... however with colored liquids inside a cuvette I'm not getting any good results (i.e the Red/Blue/Green values goes way up like 5000++)

Used white and black paper for callibration..

No idea for liquid...

Your are probably doing the white calibration with some clear liquid,
like water. The LDR is then lit directly by the LEDs, and is getting too
much light. It's resistance is then very low compared to the pull-down
resistor in series with it. You end up measuring something very close to
5 V.

You should try to reduce the amount of light hitting the LDR. A neutral
density filter (the kind used in photography) would be ideal.
Alternatively, you could increase the distance between the LEDs and the
LDR, and put some translucent paper in between. You could also add a
diaphragm (a small hole). Then, you can also lower the resistance of the
pull-down in order to get lower voltage readings, but beware not to draw
too much current.

A comment about the instructable you linked to: owing to the highly
non-linear characteristic of the readings you get, it is quite likely
that you get unequal RGB vales from a neutral grey. Some kind of
linearization (estimating actual light fluxes) would be needed if you
want neutral greys to be measured as neutral greys.


Barcode not logged in SD card UART After trying for a good month.. looking like a Newbie I have not managed to log the result of barcode scanner , using rtc SD module and a waveshare scanner connected via UART to ports 2 and 3 from the arduino.
Main idea was being able to log into the SD card under the header Barcode and time, the barcode scanned and time of scan.
I know how to create files with current date + int. CSV , consecutively if one was already created, deleted them...etc
However as by not reaching the desired result I reduced and further reduce the code so at the end I am happy that the barcode I scan is logged into the SD card.
It follows mess--code..not messy enough I have some more ...honestly..anyway
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <Wire.h>
#include "RTClib.h"
#define rxPin 2
#define txPin 3
SoftwareSerial mySerial = SoftwareSerial (rxPin, txPin);

RTC_DS1307 RTC;
File myFile; // file to be created and where data is to be to stored

char c = ' ';         // stores the latest character from the serial input  buffer
int length = 30;      // Max. lenght of te buffer
char buffer [31];     // Char Array to store theincoming data
char termChar = 10;   // terminating character
byte index = 0;       // index position of the bufffer, so where the next character t come shall be copied to
boolean haveNewData = false; // Flag to tell the sketch we have data
const int chipSelect = 10; //CS pin For SD card.

void setup()  {

  Serial.begin(9600);

  mySerial.begin(9600);

  Wire.begin();

  if (!RTC.begin()) {
    return;
  }

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    return;
  }
  myFile = SD.open("test.CSV", FILE_WRITE);
  if (myFile) {
    Serial.print("Writing to file...");
    myFile.println("Hello BarWorld");
    myFile.close();
  }
}

// right now I scann a barcode

void loop()
{
  readmySerial();
  if ( haveNewData ) {  processNewData();  }
}

void readmySerial()
{
     if (mySerial.available())
    {
      c = mySerial.read();
      if (c != termChar)
      {
        buffer[index] = c;
        index = index + 1;
      }
      else
      {
        buffer[index] = '\0';
        index = 0;
        haveNewData = true;
      }
  }
}

void processNewData()
{
  myFile = SD.open("test.CSV", FILE_WRITE);
  if (myFile) {
  myFile.println(buffer);
  myFile.close();}
  }

I found the way:
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>
#include <Wire.h>
#include "RTClib.h"
#define rxPin 2
#define txPin 3
RTC_DS1307 RTC;
SoftwareSerial mySerial = SoftwareSerial (rxPin, txPin);
File main_folder; // initialize folder for saving
File dataFile; // initialize sd file
const int chipSelect = 10; // CS pin on sd card module
int prev_file_indx = 0; // used for file naming
String fileName = "000";
char timestamp[30];

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 50;

void dateTime(uint16_t* date, uint16_t* time) {
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
  // return date using FAT_DATE macro to format fields
  *date = FAT_DATE(now.year(), now.month(), now.day());

  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(now.hour(), now.minute(), now.second());
}

void setup ()
{
  Serial.begin (115200);
  mySerial.begin (115200);
  Wire.begin();
  if (!RTC.begin()) {
    return;
  }

  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
      return;
    }

    main_folder = SD.open("/");
    fileName = sd_saver(main_folder);
 // end of setup
    delay(1500);
    dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println(dataFile);
    Serial.println("Writing Headers...");
    dataFile.println("FA,  Zeit");
    dataFile.close(); // close the file
    Serial.println("File closed, Headers written");
  }
 }

void process_data (const char * data)
// here to process incoming serial data after a terminator received
{ delay(500);
    SdFile::dateTimeCallback(dateTime);
  DateTime now = RTC.now();
  sprintf(timestamp, "%02d:%02d:%02d %2d/%2d/%2d \n", now.hour(), now.minute(), now.second(), now.month(), now.day(), now.year() - 2000);
     dataFile = SD.open("DATA"+fileName+".csv",FILE_WRITE);
  if (dataFile) {
    Serial.println("Writing to file...");
    dataFile.print (data);
    dataFile.print(",");
    dataFile.println (timestamp);
    Serial.println (data);
    Serial.println (timestamp);
    Serial.println("Done.");
    dataFile.close();
  } else {
    Serial.println("error opening test.txt");
    delay(1000);
  }

}

void processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
  {

    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of switch

} // end of processIncomingByte

void loop() {
  delay(2000);

  // if serial data available, process it
  while (mySerial.available () > 0)
  processIncomingByte (mySerial.read ());
  mySerial.write(processIncomingByte);
  delay(1000);

  // do other stuff here like testing digital input (button presses) ...

}  // end of loop

String sd_saver(File dir){
  while(true){
    // iterate all files to ensure no overwrites
    File entry = dir.openNextFile();
    if (!entry){
      break;
    }
    // naming routine
    String entry_name = entry.name();
    if ((entry_name.substring(4,7)).toInt()>=prev_file_indx){
      prev_file_indx = (entry_name.substring(4,7)).toInt()+1;
      if (prev_file_indx>=100){
        fileName = String(prev_file_indx);
      } else if (prev_file_indx>=10){
        fileName = "0"+String(prev_file_indx);
      } else{
        fileName = "00"+String(prev_file_indx);
      }
    }
    entry.close();
  }
  return fileName;
}


How does one get the correct serial port? I don't have a correct serial port from the resource I'm working from - Getting Started with Arduino by Massimo Banzi and Micheal Shiloh. I'm using the Arduino Uno. I'm a complete noob to Arduino. In this image below, from the resource I'm working from, it specifies to use either of the ports: /dev/cu.usbmodemfa141 or /dev/tty.usbmodem.

Getting started with Arduino by Massimo Banzi and Michael Shiloh - Figure 3-2 shows a list of available serial ports.

I only have two available: /dev/cu.SSDC and /dev/cu.Bluetooth-Incoming-port.

How do I get the 'correct' serial port? Correct being: /dev/cu.usbmodemfa141 or /dev/tty.usbmodem.

Here's some possibly useful information:

I'm using Mac OS - which I'm new to - Sierra version 10.13.2.

I only have two ports on the computer a USB type - C and a headphone jack. So I have an 'adapter' that allows me to 'daisy chain' the USB - B and USB - A for the Arduino cable into the port of my computer. If any additional information is required, feel free to ask for it and I'll try and get back to you ASAP. Thanks.

I had the same problem and had even fewer options under my Tools > Port menu. Looked at the user forums but most answers did not work for me. After watching a YouTube video, I fixed the problem by following its suggestion of installing the CH34X driver. There are some other suggested drivers if you search for some other related StackOverflow and StackExchange posts, but I did not test them (once the Mac-Arduino communication worked, I did not want to spend more time on this) and nor can I explain why this solution works.

I wrote a short article on this for myself. If you are interested, please take a quick look.

Best luck! :)


Trying to draw a bitmap to an LED matrix only draws the left half I'm EXTREMELY new to Arduino and fairly new to programming as a whole, but I thought it would be fun to try and write a program that draws arbitrary 1-bit bitmaps to an LED matrix using the Adafruit RGBMatrixPanel library. I'm trying to draw this image to the screen:

But it conks out after 16 pixels each row...

Below is my code in full. It seems like the bit mask only works for the first 16 columns, but I can't seem to figure out why it stops at that point. I'm using an Arduino Nano, if that helps.

#define CLK  8
#define OE   9
#define LAT 10
#define A   A0
#define B   A1
#define C   A2

RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false);
unsigned long int pixelGrid[] = {
  0x00000000,
  0x31CEFDCE,
  0x78CCFCCC,
  0x78CC84CC,
  0x78CC04CC,
  0x78CC04CC,
  0x78CC24CC,
  0x78783CFC,
  0x783024FC,
  0x303004CC,
  0x303004CC,
  0x303004CC,
  0x003084CC,
  0x3030FCCC,
  0x3078FDCE,
  0x00000000
};
unsigned long int bitMask = 0x00000001;
void setup() {
  matrix.begin();
  uint8_t r=0, g=0, b=0;

  for(uint8_t y=0; y<16; y++) {
    unsigned long data = pixelGrid[y]; // select row of bits from image
      for (byte x = 0; x <32; x++) { //iterate through columns
        if (data & (bitMask << x)) {// works!
          r = 1; // set LED to ON
        }
        else {
          r = 0; // LED is OFF
        }
      matrix.drawPixel(x, y, matrix.Color333(r, g, b));
    }
  }
}

void loop() {
}

Here's the part of the code that's probably messing up, isolated:

for (byte x = 0; x <32; x++) {
        if (data & (1 << x)) {
          r = 1;
        }
        else {
          r = 0;
        }

Thanks for your help!

Edit: Changing the data variable from int to long to avoid it being truncated lead adds another column of pixels, but it kind of looks like they're all squished into column 16 for some reason:

Note: I tried drawing a rectangle from (0,0) to (31, 15) to make sure that all the LEDs worked, and I was able to do that.

Edit 2: Instead of the bitmask being 1, I made it so that:

unsigned long int bitMask = 0x00000001;
// ...
 if (data & (bitMask << x)) { // works!
          r = 1; // set LED to ON
        }
        else {
          r = 0; // LED is OFF
        }

I'm guessing regular numbers default to 16-bit unsigned ints.
The issue is fixed, woo! I edited the big code block to match.

'pixelGrid[]' are longs but your temp inside the for() loop, 'data', is an int. Thus, it gets only half the data. Easy mistake to make (and they can be so hard to spot when you know perfectly well what you meant... :)

Update:

  By switching the int to long, I've successfully unlocked a seventeenth
  column! Unfortunately, it looks like all the pixels are bunched up in
  that seventeenth column.

Another error of the same kind (I missed it the first time around):
Change (1 << x) to (1L << x). The original expression is calculated as int and the result is widened in the assignment to 'data' (and I think there was compiler bug int the code that did that, besides). The corrected expression is calculated as a long in the first place, which is what I think you intended.

Update 2:

From your question Edit 2:

  I'm guessing regular numbers default to 16-bit unsigned ints.

You are correct - ints of unspecified size default to 16-bits in the Arduino gcc compiler used by the Arduino IDE (and just about everywhere else in the Arduino domain that I know of). The language standard leaves the compiler writer free to choose the size of an int that best fits the target-machine's architecture. 16-bits is the most common, but by no means the only - size implemented in most compilers. For this reason, most compilers' pre-processors implement specific-sized data types, and application writers - you & I - are advised to use these wherever data-size matters. For the Arduino's gcc compiler, there are predefined types such as int8_t (signed 8-bit int), uint32_t (unsigned long int), etc.
int is an ok "I don't care, just as long as it works" option. When you do care - specify.

(If my answer helped you, please upvote it or select as best answer. The latter has the important function on this site of marking the question as "completed" so it doesn't keep re-appearing as an unanswered question.)


2 way switch with Arduino? Hey I'm working on a home automation system where I can replace one of my 2 way switches to an Arduino Or node MCU controlled one but I want to avoid normal relays because as of what I know they can be unreliable and tend to fail. So is there any way I can replace my switch with an Arduino controlled switch and also I cannot use solid state relay as it has only two terminals and it cannot replace my two way switch.

Like Gil said, it sounds like what you are calling a two-way switch is actually a three-way switch. These are typically wired like this (but not always, make sure to double check!):

To replace one of the two switches with a relay, you can simply connect a SPDT relay with the load/hot wire (depending on which side you're adding the relay from) to the common contact, and then the two traveler wires to the normally open and normally closed contacts. This effectively takes your existing wiring and directly swaps in a relay -- after all, the relay is literally a switch, just electrically activated instead of manually.
I can't speak to the reliability or lack thereof of a specific model of relay, but a normal power relay is more than adequate for home automation in almost all cases; you don't need anything too fancy. Yes, there will be a mechanical point of failure, but they are typically rated for 100,000+ actuations minimum on a decent relay (like this one from SparkFun, for example) which will take quite some time to reach. Avoid the super cheap relays both for safety and reliability, and you should be fine.


ESP12E motorshield analogWrite issue when powering DC motor I am relatively new to adruino and this whole space. I am currently trying to power a DC motor using an ESP12E motor shield and an ESP8266 Module

Motor Shield - https://www.amazon.com/gp/product/B078CPZDW1/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

ESP8266 - https://www.amazon.com/gp/product/B010O1G1ES/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

DC Motor - https://www.amazon.com/gp/product/B07MTT7B88/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

Here is my code

#define DIRA 0
#define PWMA 5
#define LED 2

void setup() {
  Serial.begin(9600);
  Serial.println();
  Serial.println("Starting...");

  Serial.println("Preparing motor...");
  pinMode(DIRA, OUTPUT);
  pinMode(PWMA, OUTPUT);
  analogWrite(PWMA,0);
  digitalWrite(DIRA,1);
  delay(5000);

  Serial.println("Starting motor...");
  analogWrite(PWMA,5);
  delay(5000);

}

void loop() {
}

Here is how I have wired it up

Note: This setup is similar to what I have but not exactly, I have 4 AA batteries connected and only 2 motors

I am expecting the motor to start once I upload this code but nothing is happening. If I change the analogWrite to digitalWrite, the motor runs but I want to be able to control the speed, rather than just having it run at one speed.

I have tested using analogWrite by changing the intensity of an LED and it was working, although the output pin was not the same as the one I use for the motor.

Would greatly appreciate any help as I have already gone through pages of google searches without any luck. I have been using this example as a reference, https://hackaday.io/project/8856-incubator-controller/log/29291-node-mcu-motor-shield.

This answer is the summary of the comments of the question. The idea of the solution was originally mentioned by @Majenko.

You powered the shield with about 6 Volts. The statement analogWrite(PWMA, 5); gives you (5/1024) ~ 0.5% of this 6 Volts at the output pin PWMA. This 0.03V are not enough to drive the motor.

You should use at least 3 Volts to drive the motor (as of the specs).
This can be achieved by using a duty cycle of the PWM signal of about 50%.  analogWrite(PWMA, 512); should do the trick.


How do I connect a PS4 controller connected to an Arduino that's connected to a laptop to another Arduino? My high school is entering an ROV competition and for next year's competition we want to try and set it up so that we can control it using a PS4 controller. I have done research and found this shield for Arduino and this library that allows you to connect it to an Arduino. I plan to then connect the Arduino to a computer via USB and then send each button press to a Processing program via serial. Would it then be possible to send this from Processing to another Arduino out of the laptop? I'm just wondering how feasible this project is.

We initially had just a single Arduino at the top with the Ethernet shield and took inputs from standard joystick potentiometers. We want to add in using the PS4 controller this year for easier control. We found the USB Host Shield that gives us that capability, but uses the same pins as the Ethernet shield. So we added another Arduino, connecting the laptop as the bridge also allows to have a GUI. The Ethernet is wired, by the way. We need the laptop, it's not just for a bridge.

this is possible, but the processig bridge can add a lot of delay if not correctly handled, also wifi has a low range, almost 100m by default hardware.

zigbee module has better range (xbee pro are up to 1km) and are microcontroller friendly, you use the as you are using a serial, they will hide their complexity once you set them up, and this can be done by PC.

That mens less code, that mena less error and more ram/flash/cpu so you can do a smarter robot :)

zigbee use the serial protocol to communicate, exactly as you do with the pc. Also arduino can use, with the library SoftSerial, any pin as Serial. So you can keep the HardwareSerial to communicate with pc, and any 2 free pin to communicate with the xbee. So you can use the arduino stand alone, only with the controller, and when needed connect the pc. Then arduino can act as a bridge between xbee and pc, so pc can excange data with the rover. But even without pc your project will be fun.
The same apply for bluetoot or 400/800mhz rxtx module, but not for wifi shield


Vacuum pressure sensor for Arduino I have an application that is being controlled by an Arduino. At one point in the process, it needs to determine the level of vacuum in a chamber and adjust it to within a range of values.

I can control the vacuum pumps easily enough, but it is hard to find a vacuum sensor for the Arduino. I need a sensor that can be reasonably accurate down to roughly 28 inches mercury and would connect by a tube. I can't put the sensor directly into the chamber.

Does anyone know of an Arduino sensor that would work? If not, could someone suggest a sensor component that may work with an Arduino. I would prefer to not have to engineer a solution from the sensor component up but I can if I need to.

Industrial pressure/vacuum sensors are sturdy and rigid. They have extra protection, for example to use it submersible. The manufacturer often make them for certain voltages (for example 24v) and with different outputs (0..5v output, or 5-20ma output, and so on).
There are cheap versions of those sensors. They are between 5 and 20 dollars on Ebay and Aliexpress.
The manufacturers do not tell which sensor they use inside, and it can be hard to find a sensor that is exactly the one that you need.

The bare sensor is often a piezoresistive sensor in a wheatstone bride configuration. The output voltage span of those sensors is very low and not suitable to connect directly to an arduino board.
The advantage can be that they do not have a operating voltage. Only a maximum voltage.

The ideal pressure/vacuum sensor has a temperature compensation and a gain and a output span that is near 5v. You find most of them at nxp.com.
Luckely they have also a vacuum sensor with a large range, for example the MPXV6115V.

Those sensors are ratiometric. Power them with the arduino 5v and use the arduino 5v as analog reference (that is the Arduino default setting). When the 5v changes, the resulting measured pressure does not change and is still accurate.

Never solder something to the unused pins. Those pins can be connected to something inside.

There are a few ways to calculate the pressure. One way is to use the formula from the datasheet, the other way is to map the output voltage span to the pressure span and correct for the offset of the output voltage.


Grove sensors without a Grove shield There exists a large variety of sensors in the Grove System. Usually these are accessed via a special shield (Grove base shield).

Can I access these sensor directly without a shield. In particular I am interested in using them with an Arduino Pro Mini. My guess is that one definitely needs the 5V version of the Mini, but other than this? How fiddly is it to use these sensors directly?

I am interested in using the Grove dust sensor, but I am also would like to operate a Grove 4 digit display.

From the wiki.
Above is a schematic of a Groove shield. You can see that each of the connectors has two digital pins connected to it and then V (5V) and G (GND). The last two you can connect normally to an Arduino. The first two you connect to the pins that are used in your sketch.
Say it says to connect the connector to the top left DIGITAL pin on the board (D6/D7). You'll 7want to connect the pins as followed: Black → GND, Red → 5V, White → D7, and Yellow → D6.

Notes:

The shield overlaps the pins (i.e. 3-4, 4-5), so that might make things confusing. I think that is a design flaw. If it needs two pins, it should have two connectors. In the current state, you can connect two things together. I don't really know how to figure out if it uses all of the ports attached or not. If you don't have to, I would try not to overlap any two grooves. You would do this by using two digital ports for every groove "module."
You'll also need to have a adapter cable (Link from TheDoctor's Answer.)
For analog connections, it applies the same way as digital. G is ground, V is 5v, and A# is an analog pin.

Inferencing it:
There's no real cookie cutter way to connect to them. However, the wiki seems to be a decent resource once you figure out how to navigate it. The dust sensor you mentioned seems to ONLY use digital pin 8. It was connected to the D7/D8 connector on the Groove shield, so the yellow wire could be ignored since it was never used in the sketch.
It's hard to do much with this system: it's poorly documented and not uniform at all. Plus, some boards could cause problems that could even lead to damaging components. I would say look at something else.

This dust sensor seems pretty good, minus the documentation. On this blog, they say to do this:

Sharp pin 1 (V-LED)   => 5V (connected to 150ohm resister) Sharp pin 2
(LED-GND) => Arduino GND pin Sharp pin 3 (LED)     => Arduino pin 2
Sharp pin 4 (S-GND)   => Arduino GND pin Sharp pin 5 (Vo)      =>
Arduino A0 pin Sharp pin 6 (Vcc)     => 5V

I can't seem to find the cord for it, but I'm sure there are many others like this online. (It lists the cable needed: a 6-pin, 1.5mm pitch connector. That doesn't seem too hard to find).

Here is a 4x7 segment display for much cheaper. It does use a lot of pins and need resistors, but multiplexing and resistors aren't that hard to figure out. That's outside of the scope of this question. There might be some other board with a built in IC for controlling a display like that, but I can't seem to find one now.


Including an arduino library in Eclipse Neon (undefined reference to) I'm trying for the first time to use Arduino Libraries (Servo.h & Servo.cpp in this case) in Eclipse IDE.

So far I've managed to compile and run Arduino code using this tutorial (I suppose many of you already know it).

The problem comes when I add the Servo.cpp and Servo.h files and try to run the program:

    13:35:08 **** Incremental Build of configuration Release for project Servo ****
make all
arduinoEclipse/subdir.mk:268: warning: overriding commands for target `arduinoEclipse/wiring_pulse.o'
arduinoEclipse/subdir.mk:261: warning: ignoring old commands for target `arduinoEclipse/wiring_pulse.o'
Building file: ../ServoTest.cpp
Invoking: AVR C++ Compiler
avr-g++ -I"C:\arduino\arduinoEclipse" -Wall -Os -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -funsigned-char -funsigned-bitfields -fno-exceptions -mmcu=atmega328p -DF_CPU=1600000UL -MMD -MP -MF"ServoTest.d" -MT"ServoTest.o" -c -o "ServoTest.o" "../ServoTest.cpp"
Finished building: ../ServoTest.cpp

Building target: Servo.elf
Invoking: AVR C++ Linker
avr-g++ -Wl,-Map,Servo.map,--cref -mrelax -Wl,--gc-sections -mmcu=atmega328p -o "Servo.elf"  ./arduinoEclipse/CDC.o ./arduinoEclipse/HardwareSerial.o ./arduinoEclipse/HardwareSerial0.o ./arduinoEclipse/HardwareSerial1.o ./arduinoEclipse/HardwareSerial2.o ./arduinoEclipse/HardwareSerial3.o ./arduinoEclipse/IPAddress.o ./arduinoEclipse/PluggableUSB.o ./arduinoEclipse/Print.o ./arduinoEclipse/Servo.o ./arduinoEclipse/Stream.o ./arduinoEclipse/Tone.o ./arduinoEclipse/USBCore.o ./arduinoEclipse/WInterrupts.o ./arduinoEclipse/WMath.o ./arduinoEclipse/WString.o ./arduinoEclipse/abi.o ./arduinoEclipse/hooks.o ./arduinoEclipse/main.o ./arduinoEclipse/new.o ./arduinoEclipse/wiring.o ./arduinoEclipse/wiring_analog.o ./arduinoEclipse/wiring_digital.o ./arduinoEclipse/wiring_pulse.o ./arduinoEclipse/wiring_shift.o  ./ServoTest.o
./ServoTest.o: In function `setup':
ServoTest.cpp:(.text.setup+0x8): undefined reference to `Servo::attach(int)'
./ServoTest.o: In function `loop':
ServoTest.cpp:(.text.loop+0x20): undefined reference to `Servo::writeMicroseconds(int)'
ServoTest.cpp:(.text.loop+0x5a): undefined reference to `Servo::writeMicroseconds(int)'
ServoTest.cpp:(.text.loop+0xbc): undefined reference to `Servo::write(int)'
./ServoTest.o: In function `_GLOBAL__sub_I_myservo':
ServoTest.cpp:(.text.startup._GLOBAL__sub_I_myservo+0x4): undefined reference to `Servo::Servo()'
collect2.exe: error: ld returned 1 exit status
make: *** [Servo.elf] Error 1

As you can see in the console output, it compiles correctly, but when it comes to the linker, it doesn't find the function references from the Servo.cpp.

As I have seen in this post, the problem comes from the fact that I need also to generate an .a (static library) file in order to link both .h and .cpp files. Still, I have no idea how I am supposed to generate this file.

For this project, I have just added in arduinoEclipse folder all the .cpp and .h files from C:\arduino\hardware\arduino\avr\cores\arduino, C:\arduino\hardware\arduino\avr\variants\standard & C:\arduino\libraries\Servo.

Do you see what I could be missing?

Thank you in advance

I don't have eclipse handy right now, so I may not have the menu options verbatim here, but with eclipse there are more steps to including a library than just writing the line in the code.  Go to the project in the project explorer and right click the project name.  Hit import and select the option for importing Arduino libraries into the sketch.  It should bring up a dialog with a list of all the libraries you have installed and you can choose from there.  Then there will be a folder in your project called includes IIRC and it will have a link to the library that you imported.  Now when you compile it will find the library.


HTTPS Client with MKR1000 I am making an IoT device with the MKR1000.

As a part of the process, I would like to set up an HTTPS connection to https://hit.tl8.co/api/ping (This is a website I have made and control).

The problem is that client.connect(url, 443) is returning false. I have tried normal HTTP and the URL works on a browser. I can also access https://www.google.com. The code is a small variation of the example HTTP client.

As such, I believe that the TLS cert I am using is not accessible by the MKR1000. Running this report shows that it is a RSA 2048 bits (e 65537) with SHA256withRSA cert.

Is there a way to get the MKR1000 to accept this cert? Failing that, what changes do I need to make to this cert for it to work?

Is there a software solution to get this cert working?

You need to use connectSSL() instead of connect(). And possibly add your certificate to mkr1000 as described on Hackster


What Ohm Termination Resistor is needed for this schema ? What, Where and How? I'm building a Master-Slave system using some arduino pro mini as slaves and a Mega 2560 as Master to communicate over RS485 config via MAX485. Since i'm newbie in RS485 i know that i need to put some termination resistor somewhere is the line but i don't know where and how, also i don't know how much ohm should it be. My Baud rate is 9600 and i'm using twisted pair cable (CAT5) and it's 120 meters long.

UPDATE 1:
My goal is to get data from each slave time to time, every slave is connected to a temperature sensor and sends temperature value to master on demand (when master asks for it.) The master asks for temperature value from all slaves separately (of course!) and repeatedly every 500 ms. First it asks slave 1 to send data and then slave 1 sends data to master, then master asks slave 2 to send data and slave 2 sends data to master and so on. after 500 ms, it does this again.

UPDATE 2:

Master side code (Mega 2560):

#include <AltSoftSerial.h>
#define DE 2 //RS485 Data enable pin. HIGH=Transmit, LOW=Receive
String inputS = "";
boolean stringComplete = false;
AltSoftSerial altSerial;

void setup() {
 altSerial.begin(9600);
 Serial.begin(9600);
 pinMode(DE, OUTPUT);
}

void loop() {
 digitalWrite(DE, HIGH); //Transmit
 altSerial.println("MEGA:ProMini1");
 altSerial.flush();
 digitalWrite(DE, LOW); //Receive
 CheckAndReceiveFromMax(); //Check if data received
 if(stringComplete){
   inputS.trim();
   if(inputS.equals("ProMini1:ACK"))
    Serial.println("MEGA: ProMini1 Acknowledged: " + inputS);
   else
    Serial.println("MEGA: Not valid On ProMini1: " + inputS);
   stringComplete = false;
   inputS = "";
 }
delay(100);
digitalWrite(DE, HIGH); //Transmit
altSerial.println("MEGA:ProMini2");
altSerial.flush();
digitalWrite(DE, LOW); //Receive
CheckAndReceiveFromMax();
if(stringComplete){
  inputS.trim();
  if(inputS.equals("ProMini2:ACK"))
    Serial.println("MEGA: ProMini2 Acknowleged: " + inputS);
  else
    Serial.println("MEGA: Not valid On ProMini2: " + inputS);
  stringComplete = false;
  inputS = "";
}
delay(500);
}

void CheckAndReceiveFromMax()
{
 while (altSerial.available()) {
 char inChar = (char)altSerial.read();
 inputS1 += inChar;
 if (inChar == '\n')
  stringComplete1 = true;
 }
}

Slave side code (Pro Mini1):

#include <AltSoftSerial.h>
#define DE 7
String inputS = "";
boolean stringComplete = false;
AltSoftSerial altSerial;

void setup() {
 altSerial.begin(9600);
 Serial.begin(9600);
 pinMode(DE, OUTPUT);
}

void loop() {
 digitalWrite(DE, LOW); //Receive
 CheckAndReceiveFromMax(); //Check if data received
 if(stringComplete){
  Serial.print("String received: ");
  inputS.trim();
  Serial.println(inputS);
  if(inputS.equals("MEGA:ProMini1")){
   Serial.println("ProMini1: Mega called me!");
   digitalWrite(DE, HIGH); //Transmit
   altSerial.println("ProMini1:ACK");
   altSerial.flush();
   digitalWrite(DE, LOW);
  }
 stringComplete = false;
 inputS = "";
 }
}

void CheckAndReceiveFromMax()
{
 while (altSerial.available()) {
 char inChar = (char)altSerial.read();
 inputS += inChar;
 if (inChar == '\n')
  stringComplete1 = true;
 }
}

And the same code for ProMini2, ProMini3 and so on.

OUTPUTS:
When master calls ProMini1, the ProMini2 answers, and when master calls ProMini2, ProMini1 aswers. Also, received data is not always in correct format.

Server Serial Monitor:

 MEGA: Not valid On ProMini1:  roMini1:ACK
  :
MEGA: Not valid On ProMini2: ProMini1:ACK
MEGA: Not valid On ProMini1:  roMini1:ACK

MEGA: Not valid On ProMini2: ProMini1:ACK

MEGA: Not valid On ProMini2:  roMini1:ACK

.
.
.

For low data speeds, like 9600bps, termination is usually not necessary.


Arduino Mega vs. RasPi Pro Cons in 3D Printing Recently I tooked a look at cheaper China 3D Printers and noticed they're all based on RepRap (mostly using Ramps for the electronics part) and the next day i saw a 2d Plotter based in the pi. Then I asked myself why the Pi isnt used in 3d printers.

Question:
Why is the Arduino Mega/Due more used in 3D Printing than the RasPi? What are the Pro's and Con's for 3D Printing on the two systems?

A mutli-tasking operating system such as the Linux normally run on the pi is not particularly suited to doing hard real-time control such as coordinated pulse generation for multiple stepper motor axis trying to move as quickly as the rigidity and motor power will permit.

It is possible to use realtime extensions to the Linux kernel to get reasonable performance.  And it is also possible to run something simpler than Linux on the pi.

However, it is also possible to use a far cheaper processor to get the actual G-code execution done (you don't really pay the Arduino cost premium when buying an ATmega on a dedicated board, so it's only a  dollar or three more expensive than it "should be").  If one were to design printer electronics from scratch today, there are probably better choices, such as as ARM Cortex M0, M3 or M4 - but most of the printer designs came out of the same community where Arduino was a familiar choice, and there are probably more people willing to try to make small personal customizations to an Arduino codebase than there are willing to install the toolchain for a perhaps technically better, but less familiar solution. .

People do use Raspberry Pi's with 3d printers quite frequently though - they just use them for a different job: that of slicing and motion planning and potentially functioning as a network print server, which then drip-feeds the G code to the simpler (ATmega or whatever) based realtime executive.  In effect, they use a pi as a cheap PC to host the ATmega-based printer, rather than dedicating an old PC to that job.

Ultimately, the rarely taken alternative of using a realtime Linux kernel extensions to control motion directly from a pi, vs the more common one of using an ATmega as a realtime motion delegate for the pi, are conceptually similar - it's just that in one case the realtime executive engine is a highest priority task on the main processor, and in the other it runs on a dedicated motion co-processor.


LCD Display hangs the computer I'm trying to connect 16x2 LCD screen to clone Arduino UNO via PF8574T backpack. 4 cables are connected to +5V, GND, SDA and SDL pins.

When I tried this I2C scanner code from arduino.cc. It returned strange characters in serial monitor at first couple of tries. And now, when I try computer hangs.

When I use A4 A5 pins on the Arduino instead of SDA and SDL, i2c reported the device is on 0x27. It is ok. But if i keep LCD connected to Arduino, my iMac shutdowns after for a while. In error log i see there was a problem regarding USB serial device. I assume it as a power problem.

I'm on OS X Yosemite. Why this can be happening and how can I fix?

Note: Computer is hanging as soon as the Arduino usb cable connected.

Sometimes my system hangs in the way you describe  ("hanging as soon as the Arduino usb cable connected")  if I mistakenly connect  the +ve and -ve supply lines to an i2c device the wrong way round.


Store TinyGPS++ latitude value into a variable of type string or float I want to get the GPS ordinates in degrees with 6 decimal accuracy. I can obtain this by creating a gps object with TinyGPS library. but In the TinyGPS example codes, its written

Serial.println(gps.location.lat(), 6);

But I actually want to store this latitude degrees in a variable of type string or float. when i write this;

double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude);

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600.
How do I do that ?

it returns me Tiny lat:33.55 on serial monitor. But i want 33.546600. How do I do that?

The issue is simply the number of decimal places. That can be added to the Serial.println().

double Tiny_latitude = (gps.location.lat());
Serial.print("Tiny lat:");
Serial.println(Tiny_latitude, 6);

  Now if i want to make a String "your location is \nlat:33.546600 \nlong: 75.456912" , i.e. my String variable are stored in Tiny_latitude and Tiny_longitude and want to make a string my_Location. How do i do that?

I would use sprintf() for that but as that requires some additional build parameters the easiest way is to use String. Some special care is needed to increase the number of decimal places.

void loop()
{
  ...
  float latitude = 33.546600;
  float longitude = 75.456912;
  String buf;
  buf += F("your location is \nlat:");
  buf += String(latitude, 6);
  buf += F("\nlong:");
  buf += String(longitude, 6);
  Serial.println(buf);
  ...
}

Cheers!


Blank output in serial monitor So my SIM900 GSM Shield is working fine with Netlight LED blinking and Status LED solid light, after I upload the code nothing happens about mySerial() in my serial monitor. Can I take your time for you to check this code out? I wonder if the problem lies here.

#include<SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

/*void SIM900power()
{
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  delay(3000);
}*/
void setup() {
  // put your setup code here, to run once:
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+COPS?"); // Check that you're connected to the network;
  updateSerial();
}

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

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

Output:

Step 1) Check RX TX connections
Step 2) Change your baud rate to 115200. Turn off your arduino. Turn off gsm. Start your gsm first and then your arduino.

or
Step 3) Upload Software Serial code and just send "AT" without quotes using serial monitor. If your connections are correct you should get reply as AT.
Also make sure to set the baud rates to 115200.
Most of the GSM modules have default baud rate at 115200 or have auto baud adjustment enabled but need to be power cycled.


Connect Two Arduino Uno's Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.

You wouldn't be able process (acquire, store, resize, output) any sensible video signal with the Uno (or any other Atmega-based board). The amount of memory and clock speed is way too low. Peripherals and instruction set are also lacking - no DMA, FPU, DSP instructions. Arduinos barely cope with audio - any kind of video is out of question, except if you want something like a 5fps 32x32 raw feed. Uncompressed, of course.

If you want another hobby-friendly open source solution, I'd look at something with at least an ARM M4 core, with DMA of course. For communication, regular IEEE 802.11 Wifi is your best bet (high throughput) - those 433Mhz RF modules only transmit 4800bps or so.

There may be better solutions, but I've only used stm32f429 for video: they have DMA(2D), display interface (RGB, 8080 memory interface, ...), DCMI (digital camera interface). Wifi could be handled by something like WifiMCU.

You could use the STM32F429DISCOVERY board with LCD for you remote controller, another STM32F4 board with a camera (ex http://hackaday.com/2014/12/04/serial-camera-courtesy-of-the-stm32f4/) and pair them with two WifiMCUs, if You want to do it with off-the-shelf boards.


arduino rfid with led, code is compiling but not working as expected! code is compiling, what I want is that when rfid tag kept led should get on but instead its getting to the else loop.

int count = 0;
char input[12]; // rfid input
int led = 3; // led pin
char first[20] = {"270059204B15"}; //rfid tag no
char a[24];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) // code for rfid input
  { count = 0;
    while (Serial.available() && count < 12)
    {
      input[count] = Serial.read();
      count++;
      delay(10);
    }
    Serial.print(input);
  }

  if (strcmp(input, first) == 0) /*comparing two string rfid tag no and input
   if matches led is on*/
  {
    digitalWrite(led, LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
    delay(500);
    Serial.print("led is on\n");
  }

  else
  { digitalWrite(led, HIGH);
    delay(500);
    Serial.print("led is off\n");
  }
}

Your unespecified problems are consecuence of a collection of small details.

You are not putting a binary zero to end the input string.
That's not the way to read serial input.
Code doesn't filter out control caracteres (LF, CR).

Here is your code cleaned up:

#define ID_SIZE 12

int count=0;
char input[ID_SIZE + 1]; // rfid input
int led=3; // led pin
char first[ID_SIZE + 1]= {"270059204B15"}; //rfid tag no

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(led,OUTPUT);
}

void loop()
{

    // put your main code here, to run repeatedly:
    while(Serial.available() > 0 && count < 12) {  // code for rfid input
       char c = Serial.read();
       if (isAlphaNumeric(c)) {
          input[count++]=c;
          }
      }

    input[count] = 0;
    if(count >= 12) {
        Serial.print(input);
    }

    if(strcmp(input,first)==0) /*comparing two string rfid tag no and input
   if matches led is on*/
    {
        digitalWrite(led,LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
        delay(500);
        Serial.println("led is on\n");
        input[0] = count = 0;
    }

    else {
        digitalWrite(led,HIGH);
        delay(500);
        Serial.println("led is off\n");
    }
}

And here is the result:

Edit:

The C strings are char arrays of undefined lenght. To signal the end of the string, put a binary zero next to the (effective) last element. Then, if you want to store a 10 chars string, you need an 11 elements arrays (10 for the string itself, 1 for the binary zero).

Failure to put a binary zero at the end of a string is a very common cause of program failure.

Control characters. In general, when you type "TEST" in the Serial Monitor and press SEND, what Arduino receive is the word TEST itself, plus a Line Feed/Carriage Return pair (LF/CR) to mark the end of the line.

In real world, your serial input can be contaminated with tabs, spaces, LF/CR and other valid chars. You need to discard them (unless they are valid for your app).


make servo stay at the current position when attach() is called I use a small SG90 servo with arduino.
When I call attach() servo moves to its default position or whatever I set with write() before it.

I’d like to make servo stay at the current position when I call attach() in setup().

How can I achieve it?

I believe I can simply store last position in EEPROM. It’ll help a little. However, I’m afraid that EEPROM won’t last long.

You can't read the servo's position, so your sketch has no chance to know the real current position.

And you found that you have to set up the initial value of the servo "driver" to the one your sketch thinks is the last known position of the servo.

So your problem boils down to these questions: "How do I store a value during power-down times?" This leads to the common solution of storing the value in the EEPROM. This is a well-known and widely accepted solution, but you already found a problem: "How could a value be stored in the EEPROM without over-stressing it?"

You need to look up the guaranteed number of write cycles for a EEPROM cell. Then you need to think about the rate you would like to save the value. Divide the values and you know how long this will work. However, in reality the EEPROM will have much better endurance.

Some ideas how to "get better":

Reduce the rate of saving. I see at least two factors: The refresh rate of the servo controlling pulse is just 50 Hz. And a servo will move between (extreme) positions only a few times per second. There might be no need to save more than once per second, or even slower, depending on your application.
Don't save if the value has not changed. Well, this should be done already at the driver level of the EEPROM. It won't hurt to read its documentation and/or its source code.
Use an as large as possible array to store the value. You will store a marker for "invalid" in all but one cell, and only this cell holds the real value. This will put the "load" of two writes per save on the EEPROM, but distribution over more than two cells will lower the average load. If you select an all-1s value as "invalid", it is actually just the same value as the erased value of the EEPROM, which is necessary the next time anyway.
Add a circuit that detects the power loss before the CPU stops. This is the most chosen solution, but only usable when the hardware can do it. You need just a few milliseconds to save the value, look up the documentation. If you implement an ISR that catches the coming power loss, save the value and await the end.


Sensor to measure distance on inverted pyramid filled with maize I'm struggling with the following problem:

I have an inverted pyramid, supported in four points, filled with maize up to 600KG.

I want to keep track of the level of maize inside the inverted pyramid.

I've thought about using a load cell but this can be expensive and I need a cheap solution to implement. I also thought about using a sensor centred on top of the inverted pyramid.

The problem here is that I really dont't know what kind of sensor can be used to get correct values.
Can ultrasonic sensors give me bad values? The pyramid form is tricky...

PS: Theoricly can mill be too reflective and influence the result of measures?

I'm sorry for the English :P. I'm still learning.

If anyone can help I really appreciate.

Best Regards

The surface of corn is hard enough to reflect sound from an ultrasonic sensor. It reflects from fabric, skin and of course, plastic, and corn fits into the realm of reflectivity.

An Arduino with an ultrasonic sensor may scatter a good bit of the reflection, but some of it will get back to the receiver in sufficient condition to be registered.

The components necessary to test this are low enough cost to suggest a prototype. A simple pail or bucket filled with the grain and attached to a rope and pulley will give you distance information, and that would be for a relatively small surface area.

Ultrasonic sensors typically have a minimum distance and of course, a maximum distance. If your concern is for both full and empty conditions, dual sensors placed a sufficient distance apart with suitable range considerations are likely to work. The code would be written to avoid cross-pulse readings, which is likely to be trivial, as these devices operate at the speed of sound.

Lasers are point devices and may not necessarily reflect to the sensor for reading.

I have constructed a DME (distance measuring equipment) that displayed passing vehicles within a range of ten feet (~3 meters) down to slightly less than three feet (<1 meter) with good results. There was tremendous lag in the reading, but that's due to code ignorance, not hardware problems. I suspect the depth finder is not going to have much lag in determining its value to this application.


compilation error when changing variable from char to String I have a code with these two lines:

  char handshakecode = "S"; // Capital S
  char receive;

The lines of code are placed in a separate void, and not setup or loop.
When i change the two variables from char to String i get a error(complete error at bottom) when compiling to the arduino or verifying the code.

  String handshakecode = "S"; // Capital S
  String receive;

When i snippes out partial code for just that particular void, it compiles fine, so it must be in combination with the rest of the code, which i have left out from this post at the moment.

Is this a known error or am I doing something wrong?

  In function 'global constructors keyed to 65535_0_WFS_v0.3.ino.cpp.o':

  lto1.exe: internal compiler error: Segmentation fault

  Please submit a full bug report,

  with preprocessed source if appropriate.

  See http://gcc.gnu.org/bugs.html for instructions.

  lto-wrapper.exe: fatal error: C:\Program
  Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.15.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc
  returned 1 exit status

  compilation terminated.

  c:/program
  files/windowsapps/arduinollc.arduinoide_1.8.15.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe:
  error: lto-wrapper failed

  collect2.exe: error: ld returned 1 exit status

  exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
  2560.

This bug is specific to the 5.4.0-atmel3.6.1-arduino2 version of avr-gcc used by Arduino AVR Boards 1.6.22 and newer. It has been reported here:

https://github.com/arduino/Arduino/issues/7949

Here's the workaround:

Tools > Board > Boards Manager
Wait for downloads to finish.
When you move the mouse pointer over "Arduino AVR Boards", you will see a "Select version" dropdown menu appear. Select "1.6.21".
Click "Install".
Wait for installation to finish.
Click "Close".

Due to a bug, this workaround doesn't work with Arduino IDE 1.8.6, but it will work with any other version of the Arduino IDE.

If you have File > Preferences > Check for updates on startup checked, the Arduino IDE may occasionally notify you that a new version of Arduino AVR Boards is available, you'll need to refrain from updating back to the new Arduino AVR Boards version, otherwise you'll be back to seeing the segmentation fault error again.


I2C to UART bridge as breakout or in DIP package For a project, I need to connect more than one device to an Arduino through a serial port with hardware flow control (RTS/CTS).

Sparkfun used to make breakout boards for the SC16IS750, but this product is discontinued and I can't find any place to order it. There are also plenty of ICs doing what I need, but I am not keen on soldering SMD components and I cannot find any products coming in e.g. an old fashioned DIP package.

Does someone know about an available breakout board or a DIP packages I2C to UART bridge? Since the device will be battery powered, I would prefer a dedicated low-power circuit instead of a programmed microcontroller as suggested by majenko.

Perhaps what you're looking for:

http://sandboxelectronics.com/?product=sc16is750-i2cspi-to-uart-bridge-module

From that page:

  SC16IS750 I2C/SPI to UART Bridge Module

  This module is designed to enable I2C/SPI to UART conversion. It works in I2C/SPI slave mode and interfaces with devices working in I2C/SPI master mode. There are also 4 extra GPIOs for IO expansion. NXP SC16IS750 is used as the key component on this module. Flow control and modem signals are also supported.

  This module is useful when extra UART interface is needed. Due to the multi-slave characteristics of I2C and SPI, many UART interfaces could be added to the system at the same time.


Arduino FFT noobie question How do you obtain the real and imaginary parts of a signal using FFT in arduino?
I could not find a particular tutorial with code for this purpose in the internet.

Most libraries will either take one array of samples as input and then fill two other arrays of real and imaginary data, or it will take one array of samples and one empty array as input, and the sample data will be replaced by the real data and the empty array filled with the imaginary data.

You will have to first choose a library to use and then read the examples or documentation to see what the format of the functions are.


Porting the FastNoise c++ library to Due I'm trying to use the FastNoise library with a Due, however, I get something like the following errors, when I try to complie.

error: 'abs' was not declared in this scope
error: 'mt19937' is not a member of 'std'
error: 'uniform_int_distribution' is not a member of 'std'

so I added the following:

#include <cstdlib>
#include <cmath>
#include <random>

which solved most of the problems, however it still says printf hasn't been declared. So I tried to edit cstdio to comment out the #undef printf, but it just brought back the full list of error messages, so that's not the solution. I googled some solutions but none of these seem to work. Do you have any suggestions I should try?

I'm not trying to use printf, just want to use the library.

Thanks for any help.

The FastNoise library compiles as it is for the Arduino MKR and Arduino Zero, but there is a "not cool" issue for the Due: https://github.com/arduino/ArduinoCore-samd/issues/308

A issue with assert can easily be solved, but the #include <algorithm> and #include <random> are somehow linked to a printf function.
I thought it was very hard, but then @Juraj wrote in his answer about the simple solution to comment out the #undef printf line.

In the file cstdio is a list of about fourty #undef lines. Only the printf requires to be commented out.

// #undef printf

The file is located in the hidden "Arduino15" folder in the build environment for the Due: Arduino15\packages\arduino\tools\arm-none-eabi-gcc\4.8.3-2014q1\arm-none-eabi\include\c++\4.8.3\cstdio

Then it will also compile for the Arduino Due (even without removing the assert). There are many warnings.

I was able to run it on a SAMD21 processor and it produces random numbers. However, I am not sure that those numbers are correct. I don't know if the many compiler warnings can be ignored.

#include <FastNoise.h>

FastNoise myNoise; // Create a FastNoise object

float heightMap[32][32]; // 2D heightmap to create terrain

void setup() {
  SerialUSB.begin(9600);
  SerialUSB.println("FastNoise");
  delay(1000);

  myNoise.SetNoiseType(FastNoise::SimplexFractal); // Set the desired noise type

  for(int x=0; x<32; x++) {
    for(int y=0; y<32; y++) {
      heightMap[x][y] = myNoise.GetNoise(x,y);
      SerialUSB.println(heightMap[x][y]);
    }
  }
}

void loop() {
}

Do you know the XY Problem? You did not explain the reason for trying to make that library run on a Arduino Due. Perhaps there is an other way for what you want to achieve.

The Arduino Due was a major update for the Arduino boards, but nowadays some say to avoid the Arduino Due because it has issues (hardware and software).

I have updated my answer with help of the answer from @Juray.


VirtualWire send function I am a little confused on how exactly VirtualWire's "send" function works. After looking at the code, the process I gathered is the following.

In the Arduino IDE, call vw_send() with the right parameters.
Inside this method, it will start to encode the message and create the packet.
Then before the function returns, it calls vw_tx_start().
Inside that function, it enables the transmitter hardware and sets the variable "vw_tx_enabled" equal to true. Then this function returns, followed by the immediate return of vw_send(). So there is no where in this flow where the message is actually being sent.

However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.

Can someone explain/clarify this?

Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?

Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

However, the actual transmission of the message happens inside vw_Int_Handler(). But this function is never called in vw_send() or vw_tx_start(). So the only way this could be happening is if there was some sort of multi-threading correct? Because by setting vw_tx_enabled to true, the transmission process would begin inside vw_Int_Handler.

The vw_Int_Handler function is called from the interrupt handler of one of the timer modules in the chip. Yes, you could say it was some form of multi-threading in that it happens interleaved with the main processing of your sketch.

  Moreover, this library uses digitalWrite to transmit the bits. Wouldn't it just be faster to toggle the bits at the registry level?

Yes it would, but it would be less portable.  VirtualWire has been written to work on a wide range of chips, and doing low-level port access would make the code about 1000x more complex, having to include special code for each and every chip it runs on.  Easier (though less efficient) to just use digitalWrite().

  Lastly, in VirtualWire, they send a 36 bit preamble, I assume this is for synchorinzation purposes. So if I want to send 128 byte packet length, how much of a preamble should I use? I believe the reason for VirtualWire only transmitting 27 byte packet length is because the 36 bit preamble will only keep the data synchronized for that long. So is there a certain formula used to determine the preamble size?

VirtualWire uses a coding system called 4b/6b (actually a sub-set of 5b/6b coding). In that system it takes 6 symbols to transmit 4 bits. It is a way of encoding the clock into the signal in a reasonably efficient manner.

The encoding system means that there can never be 36 alternating 1/0 bits in a message. That unique stream is used as the synchronisation because it can't be confused with anything else.  From then on it's just data encoded as 4b/6b. The limit on how much data can be transmitted in one packet is a purely arbitrary value. Since this is a low-speed protocol to low-power devices it is expected that they will have limited RAM, and so limited space to receive data. So small packets are the default.

The numbers in use, incidentally, have been chosen because they fit into the 4b/6b coding scheme quite nicely.  For instance 36 symbols of preamble is equivalent to 24 bits of data. The packet size is 30 bytes, three bytes of which are used for control information (checksum, byte count, etc), leaving 27 bytes of actual payload.  30 bytes is 240 bits, which is, in 4b/6b, 360 symbols. 360 symbols could be packed cleanly into 45 bytes for simple transmission (pre-encoding from binary to 4b/6b before transmission).

Other values won't fit quite so neatly.


Difference between simple wifi transceiver and arduino yun I am debating over getting arduino yun or 2pcs nRF24L01+ 2.4GHz Wireless Transceiver. Here is the link to the transceiver on amazon  amazon description. I do not know much about wifi but why would someone get the 70 dollar yun instead of the basic transceiver and a uno. In particular for my project I want my arduino to use Web API's like twilio to send messages to my phone. Can both products do that?I know the yun has linux but I don't know if I need that for my project.Is their a better option (price is part of my decision)

The nRF24L01+ modules aren't WiFi. They cannot talk to a WiFi router or the internet. They can only talk to other nRF24L01+ modules. They are good for connecting two or more UNOs together.

The Yún has a full WiFi connection and is also able to operate as a router itself. It is best suited when you need to run complex networking on an Arduino.  To access the WiFi on the Yún you need to communicate with it over the in-built serial connection. There are libraries to help you, but the overall package is really very much overkill unless you have a requirement to do complex network routing (VPN for instance) or run software (say a Python program) directly on the Linux portion of the device.

It sounds like what you are really after for your project is an Arduino UNO and WiFi shield.

Another popular option is the ESP8266 modules.  These can be controlled through serial using AT commands, or directly programmed using the Arduino-compatible core available from https://github.com/esp8266/Arduino


Powering ESP8266EX with batteries and a voltage divider So I recently bought a ESP8266 chip, it requires 3V3 and a large current( around 210mA max which is more than that can be supplied by an arduino uno at least). I managed to connect it to my arduino uno and got it to operate in standby mode, but Wifi mode wouldn't work because it requires more power.

After reading multiple online articles, I've decided to construct my own power supply. I'm planning on hooking 3 AAA batteries in series(4V5) and then use resistors(of small values to decrease power loss) to construct a voltage divide which powers the chip.

My concern is that I have not seen a single person doing this online and this seems like a straight forward thing to do, which makes me worried. Did I miss something? Is my plan feasible?

There's a good reason why you can't do this.

When you power something like an ESP, the current it consumes will vary over time, as it does different things. For the purposes of current consumption, you could model the device as a resistor  whose resistance varies (greatly) over time. When it's in sleep mode with the radio off, it might be a 10k resistor. When it's active with the radio on full power, maybe a 30ohm resistor.

A potential divider divides voltage according to the ratio of the resistances. You are talking about putting your ESP in parallel with one of the resistors. Putting two resistors in parallel creates a new resistor with a resistance lower than either of the two.

If you want to calculate the resistance of two parallel resistors, it's R = (R1 x R2) / (R1 + R2).

What values would you choose for the resistors in the potential divider?  You'd have to go for values much lower than 15ohm in order for the 'resistance' of the ESP not to greatly affect the behavior of the divider - say 5ohm in total. This would mean your divider alone would draw a current of 1A from a 5v supply.

Fortunately, voltage regulators and buck converters are easily and very cheaply available. I recently bought a pack of five 3.3v regulator modules from China, delivered for less than £2.

Alternatively, you can create a reasonably stable supply from a reference voltage with just a single NPN transistor, but I don't know offhand whether it would be good enough for this application.


Rounding float number I want to enable user to change the duration of PWM from 0 to 255, the number should be in minute and increase/decrease with two push buttons.

(X) x 255 / 60000 = minute

In above example each time plus button pressed value (X) will multiple by the numbers of button pressed.

if (plusButton == HIGH) {
    PWMduration += (X);
}

The nearest number i found is 235.29 which equals to almost 1 minute:

235.29 x 255 / 60000 = 0.9999

How can i round that number to 1? or is there any other alternative solution to calculate this?

You can cast it to an integer after adding an offset.

Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:

int roundedValue = (int)(0.9975 + 0.5);

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:

float f = 12.0 / 3.0;

or

float f = 12f / 3f;

Than calculate the rounded value:

int roundedValue = (int)(f + 0.5);


Won't break out of for loop I'm new to Arduino and I'm trying to use PWM to generate a tone through a buzzer. I've created a for loop, however, the for loop doesn't seem to break when the variable ms is < 1000000.

int second = 1000000; //1 second in microseconds

void setup() {
  pinMode(3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  //Play middle C for 1 second
  for(int ms=0; ms <= second; ms+=3830)
  {
    digitalWrite(3, HIGH);
    delayMicroseconds(1915);
    digitalWrite(3, LOW);
    delayMicroseconds(1915);
    Serial.println(ms);
  }
  Serial.write("Finished C");
}

We can see on the serial output that the value of ms exceeds 1000000 but the for loop is still going. Can anyone see where I am going wrong?

An int can't hold 1000000.  It is a signed 16-bit variable, which means it can only hold between -32768 and +32767.

To store larger numbers you need to use long, or unsigned long which are signed and unsigned 32-bit variables.


Arduino I2C Register Read I am trying to read a specific register from a device. In this case I am trying to read the value stored in register 0X1F from slave device 0x08. On the scope I see writes for

ADDRESS_SLAVE(Wire.beginTransmission), ADDRESS_TESTCOMP0 (Wire.write)

and

ADDRESS_TESTCOMP0 (Wire.requestFrom(ADDRESS_TESTCOMP0,8))

but I don't see the register values reading out.  Here is my code:

#include <Wire.h>

int ADDRESS_SLAVE = 0X08;
int ADDRESS_TESTCOMP0 = 0X1F;

void setup()
{
 Wire.setClock(3400000);
 Wire.begin();
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(byte(ADDRESS_SLAVE));
   Wire.write(byte(ADDRESS_TESTCOMP0));
   Wire.endTransmission(byte(ADDRESS_TESTCOMP0));

   Wire.requestFrom(ADDRESS_TESTCOMP0,8);
   char read = Wire.read();
   Serial.println(read);

   delay(1000);
}

errors corrected

#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

void setup()
{
 Wire.begin();
 Wire.setClock(400000); // set I2C 'full-speed'
 Serial.begin(9600);
}

void loop()
{
   Wire.beginTransmission(ADDRESS_SLAVE);
   Wire.write(REGISTER_XY);  // set register for read
   Wire.endTransmission(false); // false to not release the line

   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH); // request bytes from register XY
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}

if you read only one register of the device, you can setup the device in setup() and in loop() only read the data from the register:

#include <Wire.h>

byte ADDRESS_SLAVE = 0X08;
byte REGISTER_XY = 0X1F;
byte READ_LENGTH = 8;

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

  Wire.begin();
  Wire.setClock(400000); // set I2C 'full-speed'

  Wire.beginTransmission(ADDRESS_SLAVE);
  Wire.write(REGISTER_XY);  // set register for read
  Wire.endTransmission();
}

void loop() {
   Wire.requestFrom(ADDRESS_SLAVE,READ_LENGTH);
   byte buff[READ_LENGTH];
   Wire.readBytes(buff, READ_LENGTH);
   for (int i = 0; i < READ_LENGTH; i++) {
     Serial.println(buff[i], HEX);
   }
   Serial.println();
   delay(1000);
}


Servo broken? Explanation, Solution I had a question, I tried to control a servo with the arduino, to the servo I attached a stick and at the end of the stick a little weight. After runing my code my servo tried to move the stick, but maybe it had not enough torque to move it so after that I paused the code. Then I tried to control the servo again without weight and this time it didn´t moved. Is it broken? why? Is there a posible solution? Thanks

Without seeing the code you are using, it is difficult to know if you are attempting to drive the servo correctly.

Remember, with a servo, the PWM signal is a positioning signal, not a duty cycle signal as used with speed control on regular dc motors.


Problems stopping an if loop, and starting it as well I want my code to run my motor for a specific amount of time at a specific speed and then stop and not do anything else. I'm having trouble here, I think with my switch and the if loops running on repeat. What is a good way for me to stop the code from looping? And any helpful hints on my switches will be appreciated as well? Thanks and I hope you had a wonderful thanksgiving if you're American. If you're not, I hope you just had a great day in general.

#include <Servo.h>
#include <Adafruit_MotorShield.h>
#include <Wire.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *DC1 = AFMS.getMotor(1);
Adafruit_DCMotor *DC2 = AFMS.getMotor(2);
Adafruit_DCMotor *DC3 = AFMS.getMotor(3);
Adafruit_DCMotor *DC4 = AFMS.getMotor(4);

Servo Servo1;

void setup() {
  digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0
  AFMS.begin(); //Initializes the motorshield board
  int motorPin1 = 1;
  int motorPin2 = 2;
  int motorPin3 = 3;
  int motorPin4 = 4;
  pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input
  digitalWrite(A0, HIGH);
  pinMode(A1, INPUT);
  digitalWrite(A1, HIGH);
  pinMode(A1, INPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  Servo1.attach(9);
}

void loop()  {
  int MAXampDrawTime = 1000;
  int MAXampDrawSpeed = 20;
  int NORMampDrawTime = 1500;
  int NORMampDrawSpeed = 10;
  int DrawTime = MAXampDrawTime + NORMampDrawTime;
  int ServoTime = 450;
  int previousMillis = 0;
  int inPin0 = LOW;
  int inPin1 = LOW;
  inPin0 = digitalRead(A0);
  inPin1 = digitalRead(A1);
  unsigned long time_zero = millis();
  unsigned long current_time = millis();

  if (inPin0 == HIGH) {
    time_zero = millis();
    current_time = millis();
    while (millis() - time_zero < MAXampDrawTime); {
      dcMoveConst(MAXampDrawSpeed, 1);
      dcMoveConst(MAXampDrawSpeed, 2);
      dcMoveConst(MAXampDrawSpeed, 3);
      dcMoveConst(MAXampDrawSpeed, 4);
    }
    while (millis() - time_zero < NORMampDrawTime); {
      dcMoveConst(NORMampDrawSpeed, 1);
      dcMoveConst(NORMampDrawSpeed, 2);
      dcMoveConst(NORMampDrawSpeed, 3);
      dcMoveConst(NORMampDrawSpeed, 4);
    }
    if (millis() - time_zero > DrawTime) {
      dcMoveConst(0, 1);
      dcMoveConst(0, 2);
      dcMoveConst(0, 3);
      dcMoveConst(0, 4);
    }

    if (millis() - time_zero >= ServoTime); {
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }

  if (inPin1 == HIGH) {
    time_zero = millis();
    current_time = millis();
    MAXampDrawTime = 1000;
    MAXampDrawSpeed = 20;
    NORMampDrawTime = 1500;
    NORMampDrawSpeed = 10;
    DrawTime = MAXampDrawTime + NORMampDrawTime;
    while (millis() - time_zero < MAXampDrawTime); {
      dcMoveConst(MAXampDrawSpeed, 1);
      dcMoveConst(MAXampDrawSpeed, 2);
      dcMoveConst(MAXampDrawSpeed, 3);
      dcMoveConst(MAXampDrawSpeed, 4);
    }
    while (millis() - time_zero < NORMampDrawTime); {
      dcMoveConst(NORMampDrawSpeed, 1);
      dcMoveConst(NORMampDrawSpeed, 2);
      dcMoveConst(NORMampDrawSpeed, 3);
      dcMoveConst(NORMampDrawSpeed, 4);
    }
    if (millis() - time_zero > DrawTime) {
      dcMoveConst(0, 1);
      dcMoveConst(0, 2);
      dcMoveConst(0, 3);
      dcMoveConst(0, 4);
    }

    if (millis() - time_zero >= ServoTime); {
      Servo1.write(0);
      delay(400);
      Servo1.write(90);
    }
  }
}

There are two major flaws with your program - and both of them can be "fixed" by you understanding some concepts better.

Firstly, in your program, there is no concept of "When the button is pressed", only "While the button is pressed".  This is caused by an error in your understanding of how reading of buttons needs to be done.

The digitalRead() function will return the current state of the button at that precise moment in time. It has no concept of "This has just been pressed", only "This is currently pressed".  So you need to remember in what state the button was last time you looked at it, and only if it has changed do you do something to react to it.  The same with the releasing of the button - at the moment it only knows that it isn't pressed, not that it was pressed but is no longer pressed.

The second problem is that of state, and is closely coupled with the fixing of the reading of the buttons.  At the moment the state of your arduino (i.e., what it thinks it should be doing at the moment) is entirely defined by what buttons are currently being held in or not held in at any one time.  Instead the buttons need to be used to set flags that tell the Arduino what it should be doing and when - such as a flag that says "You should be moving the servos".  Such an arrangement is called a finite state machine and is one of the simplest ways of getting something small like an Arduino to do multiple things at once - in this case reading what is happening to the switches whilst at the same time making motors do different things.

For more information on finite state machines you might like to cast your eye over this: http://hacking.majenko.co.uk/finite-state-machine


How to use C Libraries for Arduino code I have a code in Visual studio that I want to implement in Arduino. But
there is a problem. Many libraries usable in Visual Studio aren't usable
in the Arduino IDE. How can I use them in my Arduino code? To be
precise, the libraries I want to use are

#include <iostream>
#include <iomanip>
#include <queue>
#include <string>
#include <math.h>
#include <ctime>

I know I have <iostream> available in Arduino. <math.h> is also
available I think along with the <string> library. The main problem is
to how to use #include<queue> and its functions such as
priority_queue() and other functions of iosteam like .pop()? Any
help would be highly appreciated.

Some of the libraries you mention (iomanip, iostream, queue, string) are part of the STL - Standard Template Library. Whilst it does not ship with the IDE download, you can install it yourself. See The Standard Template Library (STL) for AVR with C++ streams - a port to the Arduino by Andy Brown.

I have some implementation notes here.

Be aware that a lot of Arduinos don't have much RAM, so you need to use libraries like this with caution.

Library download: AVR standard template library, version 1.1.1 - 197.29 kB


How to light up all LEDs of a 7x5 LED matrix? I want to light up all the LEDs of a 7x5 matrix with arduino uno. How can i do so?

You don't need an Arduino for that, and one will give you no benefit.

Connect all anodes to power, and all cathodes to the appropriate resistors, then ground.


Is this Bluetooth module cool for Arduino? I am making a basic project that will have 4 or 5 arduino nodes. Each arduino will have a bluetooth module attached. The thing I want is, I want to be able for each one of these arduinos to know the other is present in the room (let's say, 5 meters). For my experience in the cellphone, I don't even have to pair bluetooth devices to know about their presence, as long as they are in visible mode. Since I just need to know their presence, and no exchange of information will ever happen, I probably will never have to pair them right?

For this project I need a bluetooth (BT) module that:

1) Enables me to change the ID of each arduino, so that, even if I use my cellphone to scan for BT devices I will see (Arduino1, Arduino2, etc...) instead of default-factory-names.

2) Enables me to scan around for existing devices every time each X seconds, because I want each arduino to know if the others are in the room.

Will this module do the trick? http://www.ebay.co.uk/itm/Interface-Base-Board-Serial-Transceiver-Bluetooth-Module-For-Arduino-UNO-R3-/111482008102?pt=UK_BOI_Electrical_Components_Supplies_ET&hash=item19f4d87226

Later I will probably hang around with batteries so I will want a low power BT module, having the same 2 capabilities mentioned. Will NRF8001 do the trick for me? http://www.nordicsemi.com/eng/Products/Bluetooth-Smart-Bluetooth-low-energy/nRF8001

Thanks!

From skimming that post, I believe that your linked pcb is not a full bluetooth module (note how there is no bluetooth chip or antenna of any kind). This is simply a "base board," which is why it is so cheap1.

You will need something like this that actually has the components you want.

To answer your questions:

The bluetooth library for arduino sets the discoverale name to ARDUINOBT by default, but that can be changed in the setup() method.
"scan around" is a little ambiguous—AFAIK, bluetooth can only connect to one device at a time, but I'm not sure if that's totally true. You may want to look into using radios instead of BT, as they can communicate more freely with one another, are extremely cheap, and have extensive arduino libraries availible. I'm currently working on a project that uses the nRF24L01, and I'd be happy to answer any questions you have about it.

1: It also has a draw of 6v VCC, which is more than the Uno can output.


Code output is not as expected #include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'E'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
int count = 0; char num[4];
char key;
byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

char adhaar[4][4] = {
  {'1', '0', '8', '3'},
  {'9', '1', '6', '0'},
  {'5', '7', '6', '1'},
  {'6', '7', '9', '3'}
};

char adhaar0[4] = {'1', '0', '8', '3'};
char adhaar1[4] = {'9', '1', '6', '0'};
char adhaar2[4] = {'5', '7', '6', '1'};
char adhaar3[4] = {'6', '7', '9', '3'};
boolean check, control, adhar, tag_status;
int i = 0, j, p, q;

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
  Serial.begin(9600);
  Serial.println(" enter your adhaar ");
}

void loop() {
  getkey();
  checkkey();
}

void getkey() {
  while (i < 4) {
    char key = keypad.getKey();
    if (key) {
      num[i] = key;
      Serial.print(num[i]);
      i++;
    }
  }
}

void checkkey() {
  if (i == 4) {
    control = true;
    for (p = 0; p < 4; p++) {
      for (q = 0; q < 4; q++) {
        if (adhaar[p][q] == num[q]) {
          check = true;
          Serial.println(num[q]);
        } else {
          check = false;
          Serial.println(" not eligile");
          break;
        }
      }
      if (check == true) {
        adhar = true;
        Serial.println(" cast your vote");
      }
    }
    i = 0;
  }
}

My problem is once the adhaar matches with the values initialised in the array I have, it's going to "cast your vote" as expected, but after that it's again executing "not eligible" 3 times.

First, a general remark: most of your variables are never used. You
should get rid of them, as they only serve to make your code more
obscure.

Then, the reason for the observed behavior is that you are comparing the
entered code with 4 predefined codes. Whatever the user enters, there
will be at least 3 non-matches, hence 3 times the program prints “not
eligile”.

To get the behavior you expect, I would get rid all all those boolean
variables that make the logic hard to follow, and instead break down the
problem into smaller chunks, each implemented in its own small function.
This makes it easier to write code that is easy to understand.

First, how do you tell whether two 4-character codes are the same? Like
this:

// Do codes a and b match?
bool match(char a[4], char b[4]) {
    for (int i = 0; i < 4; i++) {
        if (a[i] != b[i])
            return false;
    }
    return true;
}

Then, given a code entered by the user, tell whether it matches
adhaar[0] or adhaar[1] or... or none of them:

// Return the adhaar index matching the given key,
// or -1 if there is no match.
int matching_idx(char key[4]) {
    for (int i = 0; i < 4; i++) {
        if (match(key, adhaar[i]))
            return i;
    }
    return -1;  // no match
}

Now your checkkey() function can be rewritten as follows:

void checkkey() {
    if (i != 4) return;  // should never happen
    if (matching_idx(num) == -1)
        Serial.println(" not eligile");
    else
        Serial.println(" cast your vote");
    i = 0;
}


Is analogWrite() inferior to writing directly into registers? I'm trying to control a DC motor's speed with my Arduino Mega analogWrite(), but it doesn't seem to function properly. The motor never completely slows down, just slows down a bit (which is still pretty fast) and then stops spinning completely.

I'm trying to create a robot with different speeds, and it just has to have a slow speed. I know it isn't the code, since the relay and motor works just fine when I use the digitalWrite().

Is it better to write directly into the timer registers to implement the PWM, OR what else could be causing the problem?

analogWrite() is already PWM, Arduino doesn't produce a true analog signal
Motors tend to draw a lot of current so you might want to control the motor with a MOSFET then connect your power supply directly to the motor. PWM will still work in that case, you just need to connect the output pin to the gate pin of the MOSFET
If you want more of an assurance when working with motors, try buying a motor shield. You current problem, speed problem and many will be resolved. It also makes it easy to control multiple motors.


How to interrupt a code after delay I have a functionality on my mega 2560 to connect with other devices. Sometimes, devices can't answer. I don't want to wait for a longwhile. So, how can I interrupt the chunk of program after the specific amount of time?

My code for receiving messages is:

while (!(UCSR1A & (1<<RXC1)));

so, millis can't solve my problem because I haven't ability to check for conditional loops like that

if(currentMillis - previousMillis > interval) {

OMG, I was stupid. I can just place millis in this while condition.


Creating arduino library linking question I know how to create my own arduino library and use it. I am using Xcode to create a c++ project. I have the arduino library files(Servo, Wire, Keypad, etc). If I want to include the Servo.h library file in my created library, how do I go about linking that? For some reason, I can't just add the Servo.h/.cpp files in my project because then I get other linking file problems that Servo.h references and are not linked in my project. Has anyone done this before?

I can't speak for Xcode, but in general with Arduino IDEs (UECIDE excepting) if you use a library within another library, that library also has to be #included in the main sketch.  That is the only way most IDEs determine which libraries need to be compiled into the finished program.

That's one of the first targets I had for UECIDE - to enable fully recursive library compilation.  Any libraries found within the master header of a library will also be included for compilation - and any found in those libraries, etc.  It took a lot of work (and it's by no means 100% perfect), which is why so few others do it and leave it up to the programmer to ensure the inclusion of the right sub-libraries in their sketch.


Read sensor data repeatedly after specified time? I want to read sensor data using analogRead() after every 5ms. I have read other answers to similar questions but what I'm confused about is:

let's say, I made a loop to read sensor data using analogRead() at the end of which I write delay(50)
it means it'll take some time to read data(adc) , then it'll wait for 50ms
time to execute loop isn't same for every iteration so we get the pattern as: some time for loop execution, delay of 50ms, some time for next iteration........and so on
I want to ask if I want arduino to read sensor data exactly every 5ms, what should I do?
Thanks

You store the time (millis()) of the last measurement. Then wait till 5ms have past since the last measurement. Do your measurement, and update the time.

Something like:

unsigned long lastMeasurement = millis();

void loop()
{
  while( (millis()-lastMeasurement)<5 ){/* do nothing */}
  lastMeasurement = lastMeasurement + 5; //or use `lastMeasurement=millis();` depending on whether you want accuracy between measurement, or accuracy over time
  auto measurement = analogRead(A0);
}


What is the Arduino compiler's version of `__unused` for function parameters? When I first started with the Arduino environment I noticed that it had File | Preferences | Compiler Warnings set to None, so I set it to All - and there were many, many warnings in the supplied libraries! So I quickly set it to None again - until later.

Well, "later" is now, and I started going through the warnings to fix the code to quiet the compiler.

Note that I don't want to disable any warnings - I want to placate the compiler at each spot so that it says to itself "No problem here!"

If the compiler complains of an unused variable, I comment out the variable;
If it complains of a signed/unsigned comparison, I change the type;
If it complains of an unused parameter in a function, I...

...hmmm. If this was C++, I'd simply comment out the parameter name, leaving the type naked:

void Fn(int /*param*/) {
} // Fn(param)

  Arduino reports:
    error: parameter name omitted

But that isn't legal in C. With some compilers you can use the __unused attribute:

void Fn(int __unused param) {
} // Fn(param)

  Arduino reports:
    error: expected ';', ',' or ')' before 'param'
    It's interpreting __unused as the actual parameter name

or if they're fussy:

void Fn(int __attribute__((unused)) param) {
} // Fn(param)

  Arduino reports:
    warning: unused parameter 'param' [-Wunused-parameter]
    That's not the correct __attribute__, obviously

So none of the above work in the Arduino environment. Suggestions?

I've been programming in C and C++ for over twenty years, and I know that the #1 thing you should always do is ask the compiler to tell you about everything it notices. You need a warning-free compile at all times! Otherwise, you spend hours or days trying to find a bug - only to discover that the compiler has been warning you about it all along...

Well, I typed all that question up for posting, then tried one last thing. It worked!

void Fn(__attribute__((unused)) int param) {
} // Fn(param)

So, rather than let a good question go to waste: here's the answer!

Now all we need to do is get the maintainers of all the libraries to put these in... and fix the other warnings...


Use Arduino pro micro to program pro mini? So I got a pro micro and 2 pro minis and I was wondering if I could use the pro micro to program my minis? Anyone has any links or guides on how to do this, if at all possible?

I don't know if it will still work but I will suggest you this.
As arduino micro is Leonardo compatible and you r two arduino minis are based on atmega328. You should be able to use the tutorial posted above to use micro as programmer for the two mini.
Hope that helped.