How to boil down analog input to just three cases? I am investigating the use of a 3-position-switch for one of my projects to switch between different settings using just one analog input pin. For the three positions I am using ground/0V, ~2.5V (via 2x10k voltage divider) and full 5V. I am doing this also because I am planning to use a 5-position rotary switch in a similar way in the future.

Due to tolerances and noise, the readings on the analog pin are not precisely 0, 511, 1023, but rather 0-1, 509-512 and 1021-1023. To take this into account, I am using the map function like this:

const byte alarmSwitchPin = A0;
int alrmSwState;
byte alrmSet;
byte alrmPrevSet;

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

}

void loop() {

  alrmSwState = analogRead(alarmSwitchPin);       // Read input

  byte alrmSet = map(alrmSwState, 0, 1023, 0, 2); // Boil input down to three cases

  if (alrmSet != alrmPrevSet) {                   // Only if state of switch has changed
    switch (alrmSet) {
      case 0:
        Serial.println("Low");
        break;
      case 1:
        Serial.println("Medium");
        break;
      case 2:
        Serial.println("High");
        break;
    }
    alrmPrevSet = alrmSet;
    delay(200);                                   // For testing purposes
  }
}

I only want the setting to change (or, in this case, the console to print) when the state has actually changed. This does not work, though, because the map function is doing its math in integer, which fails in mapping the High position (in this case).

What are my options if I want to stick with the switch method? I am curious if it is possible to get this done without if statements and conditions or, as a more general question, what the best option is to properly map the 10 bit analog input to just 3 cases/numbers.

PS: I thought analogReadResolution() might be an option but I am working with Arduino UNO where this is unavailable.

The simplest fix to your problem is to change the map() call to

byte alrmSet = map(alrmSwState, 0, 1024, 0, 3);

In the call above, the mapped intervals are of the semi-open type, e.g.
[a, b), where the start values (namely 0) are understood as being
inclusive and the end values (1024 and 3) are exclusive.

Although not clear from the documentation, this is the proper way to use
the map() function. Otherwise, the truncated division gives you very
uneven intervals. Compare:

     x       map(x, 0, 1023, 0, 2)
----------------------------------
   0 –  511     0
 512 – 1022     1
1023            2

     x       map(x, 0, 1024, 0, 3)
----------------------------------
   0 –  341     0
 342 –  682     1
 683 – 1023     2

The result you get is very close to Jeff Wahaus’ answer.

What I find annoying about this approach is that a 32-bit integer
division, which map() uses internally, is a very expensive operation
on the small 8-bit Arduinos. If instead of 342 and 683, you use 256 and
768 as thresholds, then you can make the decision by just looking at the
high byte of the analog reading:

uint16_t alrmSwState = analogRead(alarmSwitchPin);

alrmSet = alrmSwState / 256;

if (alrmSet != alrmPrevSet) {
    switch (alrmSet) {
        case 0:
            Serial.println("Low");
            break;
        case 1:
        case 2:
            Serial.println("Medium");
            break;
        case 3:
            Serial.println("High");
            break;
    }
    alrmPrevSet = alrmSet;
    delay(200);
}

Note that the division by 256 is optimized by the compiler into a much
cheaper bit shift, but this is the case only if alrmSwState is of an
unsigned integer type. That's why it is declared above as uint16_t.


What does this notation stands for? Wire.read() <<8 | Wire.read() I'm using the Arduino's site test code for getting raw values from a MPU-6050 accelerometer + gyro. In the loop, there are this lines for getting the next data from its registers:

Wire.requestFrom(MPU_addr, 14, true);  // request a total of 14 registers

AcX = Wire.read()<<8 | Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read()<<8 | Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read()<<8 | Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read()<<8 | Wire.read();  // 0x41 (TEMP_OUT_H)   & 0x42 (TEMP_OUT_L)

GyX = Wire.read()<<8 | Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read()<<8 | Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read()<<8 | Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)

Hex numbers indicates, of course, the address of each register. However, I can't get how, if the first instruction only requests from the MPU_addr (constant), it changes to the consecutive registers. Is it that <<8| makes something like a sum or a logic OR to switch the register to read?

Regards!

Just adding a couple of points to Michel Keijzers's answer.

The expression Wire.read() << 8 takes the value returned by
Wire.read(), which is an int, and shifts it 8 bits to the left,
which is equivalent to multiplying by 256. If you are using a 32-bit
microcontroller (e.g. an Arduino Due), this is safe. However, most
Arduinos are based on an 8-bit AVR chip. On them, an int is 16-bits
and can only hold values up to 32767. If the initial value is larger
than 127, then the bit shift causes a signed integer overflow, which in
C and C++ is undefined behavior (read: “illegal operation”). It is
likely that everything runs fine and you get the expected result, but
it is unwise to ever rely on undefined behavior in C or C++.

The proper way to do the shift is to cast the initial value to an
unsigned data type, which is always safe v.s. overflows, and then do the
shift, like in

((uint16_t) Wire.read()) << 8

You may omit the outer parentheses if you know your operator priorities.

The second point is about the already mentioned fact that the order of
the reads is not specified. The simplest fix is to do one read per
statement, as in:

AcX = (uint16_t) Wire.read() << 8;  // first read MSB
AcX |= Wire.read();                 // then LSB

It is worth noting that the first statement has an implicit cast from
uint16_t (the result of the shift) to int16_t (the type of AcX).
This can also overflow if the shifted value is larger than 32767.
However, an overflow happening during a conversion in not undefined,
but rather implementation defined behavior. This means that the
authors of the compiler must decide and document what happens. Arduino
code is usually compiled by gcc, and the gcc docs document this
behavior as

  • The result of, or the signal raised by, converting an integer to a
  signed integer type when the value cannot be represented in an object
  of that type (C90 6.2.1.2, C99 and C11 6.3.1.3).

  For conversion to a type of width N, the value is reduced modulo 2^N
  to be within range of the type; no signal is raised.

This is exactly what we want here, and since it is the most efficient
choice on a two’s complement architecture, it seems unlikely that
another compiler would make a different choice.


if(Serial) not working correctly on micro or pro micro I have an arduino micro and several clone "pro micro"'s both of which are based on the 32u4, i'm trying to make my project have a debug mode which is only active when the serial port is open, the documentation states that using:

if (Serial)

on these boards should only return true if the port is open (on uart based connections it always returns true), i wrote my sketch to take advantage of that but it didn't seem to be working properly, so i stripped back to basics and wrote this sketch:

void setup() {
    // put your setup code here, to run once:
    pinMode(2, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
    if (Serial){
        digitalWrite(2, HIGH);
    }
    else{
        digitalWrite(2, LOW);
    }
}

I connected an LED to pin 2 and then tested it by connecting and disconnecting the arduino from the PC, and opening and closing the com port.

after freshly connecting the arduino to the PC the LED is off, when i open a connection to the virtual com port the LED turns on.
however i would expect the LED to go out once the port is closed, but it remains on.

My questions are:
1) have i got an out of date bootloader?
2) if so how do i check?
3) is this intended behavior and if so why?
4) is this a bug in the arduino bootloader or libraries?
5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Edit:
should have mentioned i'm seeing this behavior with or without a call to Serial.begin

1) have i got an out of date bootloader?

No. This has nothing to do with the bootloader.

  2) if so how do i check?

See above.

  3) is this intended behavior and if so why?

In a manner of speaking, yes - see below.

  4) is this a bug in the arduino bootloader or libraries?

No. Elsewhere.  See below.

  5) short of having to change my code to look for serial data to start and stop the debug mode (serial comms are being used for other things in the background) is there any way i can work around this? reading from hidden registers etc?

Yes, you can, but only once you understand exactly what is going on.

The problem with USB serial (AKA CDC/ACM) communication is that there is no way of knowing if the port has been opened by the computer or not.  That functionality was just never designed into the protocol.

However, there are two virtual modem signals that the computer can assert that the CDC/ACM device at the other end can examine - one is the equivalent of DTR and the other the equivalent of RTS.

The Arduino's CDC/ACM code examines those, and if either are asserted then it assumes the CDC/ACM port is open. If neither are asserted then it assumes the port is closed.

Now comes the tricky part:  You have little or no control over when those signals are asserted or not.  There are three separate factors that decide what happens:

The software being run can manually control the signals.  The Arduino IDE does this to ensure boards that use DTR to reset (like the Uno, etc) actually do reset.
The drivers on the computer can decide to automatically control the signals when the port is opened or closed
The operating system itself can control the signals when the port is opened or closed.

Some software will control the RTS/DTR signals properly, some won't. Some drivers will control the signals for you, some won't. Some operating systems (such as Linux) will, unless otherwise instructed, default to automatically controlling the modem lines properly. Others, like Windows, won't.

So the only way you can be sure that these signals are being controlled properly is to manually control them from your own software used for debugging, or to find a specific terminal emulator that controls the lines properly.


How to solve Atmega 16A Serial write (println) hang with Arduino Uno firmware? For doing some experiments I bootloaded an Atmega16a with Arduino Uno. I am powering my Atmega16a from Arduino UNO. I am not using any external clock. Atmega16a is connected to a breadboard. For bootloading I refer the site http://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers I can run blink sketch on my Atmega16a using Arduino as ISP. TX and RX of Atmega16 is connected to Max485's DI and RO respectively.

Atmega16a pin 14 (RXD) -> MAX485 pin 1-RO
Atmega16a pin 15 (TXD) -> MAX485 pin 4-DI
Atmega16a pin 17 (D3)  -> MAX485 pin 2 and 3. Also connects a LED to the pin

I used a boards.txt downloaded from https://github.com/sudar/arduino-extra-cores/blob/master/boards.txt

Issue: hang at Serial.println

I faced issues when I started to interface with MAX485.

The program wont run if I add a Serial.println, see my program below.

void setup() {
   Serial.begin(76800); // I tried 9600 too
   pinMode(3, OUTPUT);
}

void loop() {
  digitalWrite(3, HIGH);
  delay(400);
  Serial.println("20"); //comment this code and could see the led blinks
  delay(2000);
  digitalWrite(3, LOW);
  delay(400);
}

Regression

I tried Latest Arduino IDE as well as 1.0.6 version

I could do a serial communication with Raspberrypi and Arduino Uno via MAX485 without any issues. For the complete connection detail of MAX485 and other Arduino, check my blog.

Some times I receive some string to serial port of Raspberry pi like below. I run a nodejs app in RPi, using serialport npm and parser is RAW.

<Buffer fa>
<Buffer 82>
<Buffer 86 ff>
<Buffer fe>
<Buffer fe>

How to prevent these hangs?

Unfortunately you can't just simply upload the Arduino bootloader and expect it to work. The ATmega16 is not the same as the ATmega328. One quick look at the datasheet will already explain why this is not working. The UDR(USART data register) is at 0xC6 on the 328, while it's at 0x2B at the Atmega328. So the ATmega16 will look at the location where the 328 stores the received data and will not find it. This could explain the hang, but I expect that other things like UART setup will have gone wrong before you get to the receiving of data.

If you want serial communication with the ATmega16, try programming it directly in C with the AVR libraries and without the Arduino extensions. That will make it harder to figure out.


Need help with my code for my project using an Arduino Uno and Processing I am using an Arduino Uno for my project. I use 4 digital inputs and they will be triggered by 4 different relays. I would like to save the data in a *.csv file in the format below.

For example, if any of the inputs goes high, it will save a station ID, date, time it goes ON (starts). But once the input goes low, it will save the time it goes OFF (stops) on the same line.

Kindly help to advise if my code is correct because I get too many errors when I run it.

Example table in .csv file:

Date        Oven Station    Time Start     Time Stop
3/7/2017       Oven_P1_1       11:58       16:00
3/7/2017       Oven_P1_2        7:30       11:00
3/7/2017       Oven_P5_1       14:10       20:00
4/7/2017       Oven_P5_2        01:20      7:30
4/7/2017       Oven_P5_1        2:40       8:45
4/7/2017       Oven_P1_2        08:05      12:00
4/7/2017       Oven_P1_1        09:12      13:10

import processing.serial.*;

int Oven_P1_1 = 8;
int Oven_P1_2 = 9;
int Oven_P5_1 = 10;
int Oven_P5_2 = 11;
float Ovenvals [] = {0,0,0,0};

Serial myPort;
String val;
Table table;

String filename;

void setup() {
  String portName = Serial.list()[5];
  myPort = new Serial(this, portName, 9600);
  table = new Table();
  table.addColumn("id");
  table.addColumn("year");
  table.addColumn("month");
  table.addColumn("day");
  table.addColumn("hour");
  table.addColumn("minute");
  table.addColumn("second");
  table.addColumn("Oven_P1_1");
  table.addColumn("Oven_P1_2");
  table.addColumn("Oven_P5_1");
  table.addColumn("Oven_P5_2");
}

void serialEvent(Serial myPort) {
  val = myPort.readStringUntil('\n');
  if (val != null) {
    val = trim(val);
    println(val);
    float Ovenvals[] =float(split(val, ','));
    TableRow newRow = table.addRow();
    newRow.setInt("id", table.lastRowIndex());
    newRow.setInt("year", year());
    newRow.setInt("month", month());
    newRow.setInt("day", day());
    newRow.setInt("hour", hour());
    newRow.setInt("minute", minute());
    newRow.setInt("second", second());
    newRow.setInt("Oven_P1_1", ovenVals[0]);
    newRow.setInt("Oven_P1_2", ovenVals[1]);
    newRow.setInt("Oven_P5_1", ovenVals[2]);
    newRow.setInt("Oven_P5_2", ovenVals[3]);
    {
      saveTable(table, "data/OvenStatus.csv");
    }
  }
}

void draw() {
  OvenVal[0] = digitalRead(Oven_P1_1);
  OvenVal[1] = digitalRead(Oven_P1_2);
  OvenVal[3] = digitalRead(Oven_P5_1);
  OvenVal[4] = digitalRead(Oven_P5_2);
  Serial.print(OvenVal[0]);
  Serial.print(",");
  Serial.print(OvenVal[1]);
  Serial.print(",");
  Serial.print(OvenVal[2]);
  Serial.print(",");
  Serial.print(OvenVal[3]);
  Serial.print(",");
  delay(100);
}

You asked for (emphasis mine):

  [...] But once the input goes low, it will save the time OFF (stop)
  on the same line.

That's hard. What if several other inputs have gone HIGH in the
meanwhile? You will have to somehow rewind part of the file, then add
the stop time, the add again the subsequent lines...

You probably do not want to do all this on an Arduino. Especially
considering that the Arduino has no concept of file, unless you add an
SD card and the appropriate library. And it has no concept of time of
day, unless you add an RTC and the appropriate library. I would suggest
you go the easy path:

have the Arduino tell your computer through the Serial port whenever
one of those inputs changes state
write a program in your computer (with processing or whatever) that
reads this information and formats it the way you want.

For the first part, I suggest the following:

/*
 * Tell us when some pins change state.
 */

const int CHANNELS = 4;
const uint8_t pins[CHANNELS] = {8, 9, 10, 11};

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

void loop()
{
    static int states[CHANNELS];
    for (int i = 0; i < CHANNELS; i++) {
        int state = digitalRead(pins[i]);
        if (state != states[i]) {  // input changed state
            Serial.print("channel ");
            Serial.print(i);
            Serial.print(" going ");
            Serial.println(state ? "HIGH" : "LOW");
            states[i] = state;  // record new state
        }
    }
}

The output will be something like

channel 2 going HIGH
channel 1 going HIGH
channel 2 going LOW
...

For the second part, well, that's not an Arduino-related question
anymore!


Do I need Kalman Filter after I read DMP data on MPU6050? In my project I need to use as noiseless as possible data from a MPU6050, I do have some nice DMP data, what will happen if I apply Kalman filter above it? Will I get more noiseless data? Or will it become unreliable anymore? Are there any benefits to do that ?

The DMP data from the MPU6050 is already filtered, and while I have not expirimented with the DMP data much myself I believe it is pretty clean. If there is a calibration process you can do to improve it, that is probably worth expirimenting with, but you should not filter the values a second time.

You should figure out what your application's noise tolerance actually is before worrying about different filters. There are potential benefits to your own filter, I think knowing exactly how it performs in edge cases and being able to calibrating it to your specific problem could be beneficial; However, it could also end up being worse than the DMP. Don't forget that filter calculations can generally take a few milliseconds for an arduino to run that you don't have to worry about with the DMP.

If you do work on your own filter, you will need to turn off the DMP and filter the raw values. Look into complementary, mahoney, and madgwick filters as well as kalman, which is quite computationally expensive. Using an existing library or an implementation from an open source quadcopter project is probably most efficient. The math associated with kalman filters and 3d rotations gets very complicated very quickly.


Need some Hardware advice with arduino I am fairly new(having less hands on experience) to Arduino and electronics in general. I have a project for which I know the features and required electromechanical parts. I need some advice in choosing the right Arduino. Here's my requirement :-
I need the board to handle the following Hardware/Software parts -

3 Geared motors,
1 BLDC 1000 kva
2 cameras ( one is also ok)
TinyML for object detection
Mic to receive audio commands
Speaker to talk back.
Wifi shield to send/receive information to internet or a laptop.
3 small servo motors.
2 Proximity sensor.
1 dc motor (6-9v)

Please advice which Arduino board will be perfect for the above requirements. I was thinking of Arduino Mega 2560, but after looking into various projects I couldn't decide if it was sufficient as I have many hardware parts.

To process incoming images, voice commands, produce sounds, and also do WiFi is almost certainly beyond the capabilities of any micro computer, like the Arduino (maybe some of the more recent models might). I strongly doubt that the Mega 2560 would. It doesn't have a heap of RAM for one thing (it has 8k of RAM). Look at the sizes of images produced by cameras these days, they are usually measured in megabytes, not kilobytes.
What might work for you would be a Raspberry Pi, which is basically a small Linux computer on a board, with a substantial amount of RAM.


Why does the Arduino Uno WiFi network connection drop when requesting a page? I see frequent errors where the network connection to my Arduino Uno WiFi drops when I am requesting a web page. I wrote a simple REST server, and some of the pages will load as expected, but others will fail after loading half of the the text, and I notice that the network connection drops in the middle of these events. Why is the network connection dropping like this?

I saw this error when I was running low on RAM. The Arduino Uno WiFi appears to drop the network connection in low memory situations. One fix that made a significant difference for my program was to wrap all of the string literals in the F() macro. This moves the strings from ram to flash storage, and in my case quickly freed 500 bytes of SRAM (25% of the available RAM on this board).
For example, replace:

client.println("HTTP/1.1 200 OK");

with

client.println(F("HTTP/1.1 200 OK"));

Some other memory optimization may also be necessary.
Another possible cause of these symptoms would be low voltage, possibly from trying to draw too much power from the board to power external devices, but in my case there were no external connections, and I confirmed it was a low-memory issue.


Identifying a counterfeit or authentic Arduino I would like to know how I can identify a fake or counterfeit Arduino board.  For example this product, which is shown below.

I am concerned that it is cheap (about $12 when converted) and I was wondering if it is like a 'legal cheap version' or is it an unauthentic one?  If it is not authentic, would it be legal to purchase it?

It looks like an R3 Uno, but then pictures can be misleading.

However:

Arduino is open source - anyone can make one
Because of that there are many many "clones" of the Arduino
A clone, as long as it's got the right circuitry (and an Arduino is incredibly simple) is as good as the "real thing".

The only problem Arduino have with clones is the use of the Arduino name and logo.  IIRC they don't mind you claiming "Arduino Compatible", but trying to be an Arduino they don't much like.

If it's just their reference designs re-printed (which you can download for free from the Arduino Uno web page) and no further design work has been done, then although it isn't made in Italy by Arduino, it's still an Arduino.

That's the beauty / curse of open source - anyone can make one.

However, that specific one looks like it fits into the "claiming to be an Arduino" category.  It uses Arduino artwork and logos, and tries to make it look like it's an Arduino made by Arduino in Italy, when in fact it isn't.  Legally speaking, they are ripping off the Arduino brand.  Practically speaking, since it's all open source, the actual device (assuming the components aren't counterfeit) should be perfectly fine.

If they were to change the artwork, so it didn't look quite so much like an Arduino, and had something like "Arduino Uno Compatible" on it, then it would be categorized as a clone, and would be fine - you'd know where you were standing.  As it is though, the artwork on it is breaking copyright laws.

The image shown is too low quality to give much information about it, but the two big pointers that it's not made by Arduino are:

The PCB is too blue (real Arduinos are teal)
The polyfuse is the wrong colour (green instead of grey/gold)


Flash firmware with hex file over serial with Python (no avrdude, Arduino IDE) I'm trying to make a Python function in the TCLab package to flash firmware to an Arduino Leonardo (32u4). I can compile the TCLab ino (firmware) and deploy with the Arduino IDE or with the Python avryp package. The Python avr_helpers package looks like a possible solution but is only supported with the older Python 2.7. Forum posts such as this one, how can I upload a hex file to an arduino uno?, and others suggest avrdude to upload a hex file. However, I need a Python solution that can be used on any platform (MacOS, Windows, Linux, etc) without a requirement to install packages (avrdude, Arduino IDE, etc).

I have the hex file from a successful Arduino build. Here is an unsuccessful attempt to load the hex file with serial communication:

import serial
import time
import os

# open and close COM8 to activate bootloader
ser = serial.Serial('COM8',baudrate=1200)
print(ser.isOpen()); ser.close()
time.sleep(2)

# load hex file on COM9
filesize = os.path.getsize('tclab_v2.ino.hex')
fid = open('tclab_v2.ino.hex','rb')
offset = 0; MTU = 20
ser2 = serial.Serial('COM9',115200)
while (offset < filesize):
    fid.seek(offset, 0)
    ser2.write(fid.read(MTU))
    offset = offset + MTU
ser2.close()

The script is able to activate the bootloader on another port and connect. If I transfer all at once with ser2.write(fid.read()), it semi-bricks the Arduino and I recover it by hitting the reset button just before the Arduino IDE installs the firmware. I use a Maximum Transfer Unit (MTU) of 20 but I couldn't verify if there is one for the Leonardo. I can write a Python function to identify the ports and have used COM8 and COM9 here just to simply the test. Although the TCLab firmware is preloaded for Python, sometimes users change the firmware to use MATLAB, Octave, or Java and then want to switch back to Python. I'd like to make that as easy as possible without adding more steps or more instructions to the troubleshooting FAQ. Can I update the firmware like the MATLAB Arduino Support Package that detects a new device and transfers the firmware automatically with user confirmation?

This isn't the exact answer but it helps.
Uploading without avrdude is complicated and generally slow. The best solution to not using the IDE is to open and close a port then use the avrdude command that the ide usually uses.
from serial import Serial
from time import sleep
from subprocess import run

while input('Press enter to upload ') == '':
    Serial('COM5',baudrate=1200).close()
    sleep(1)
    run(["C:\\Progra~2\\Arduino\\hardware\\tools\\avr/bin/avrdude", "-CC:\\Progra~2\\Arduino\\hardware\\tools\\avr/etc/avrdude.conf", "-v", "-patmega32u4", "-cavr109", "-PCOM6", "-b57600", "-D", "-Uflash:w:C:\\Users\\USER\\Desktop\\Python\\tclab_v2/tclab_v2.ino.hex:i"])


Arduino Due - using built in ADC as a DSO causes issues at high frequencies (kHz) I am trying to use the inbuilt ADC of the Arduino Due to measure voltage signals. The frequency range I'm interested in measuring is  up to about 30 kHz.But I'm observing a strong capacitor behaviour as I increase the frequency ( from 10kHz onwards this is quite visible).

This is most visible when measuring a square wave. When I get close to 30 kHz the signal looks exactly like the text book capacitor charge/discharge wave and nothing like a square wave. Even at around 15 kHz, the square wave looks more like a sine wave/ ramp signal than a square wave.

Based on the behaviour my guess is that a capacitor in the Arduino Due ADC is causing this (as  the frequency increases, the capacitor cannot charge/discharge fast enough). But I'm not sure whether I'm correct about this.
Even if I'm correct, how can I fix this?

Any help would be much appreciated.

Thanks.

I don't have screenshots for the behaviour for a range of frequencies, but I will attach a hand drawing of what it looks like.

Also NOTE that As the frequency increases, the amplitude of the observed wave decreases ( I couldn't show this in my drawing). Think this again links back to the capacitor charge/discharge speed behaviour.

My Vin circuit : I tested by adding a voltage follower at the right most end(not shown on the schematic), but that made no difference.

Well, if you have source output impedance about 1k and Sample-And-Hold capacitance is 14pF, then RC time constant is about 14us.

You need something with low output impedance. Non-inverting Voltage Follower would be perfect for this (see source):


Does the map() function works on an ATtiny85? I have a working project on Arduino Uno.Now I want to shrink my project using an ATtiny85. Before purchasing an waiting for the shipment to arrive, I want to make sure that my whole code will run on ATtiny85.

specialy, will the map() function which is working on  an Arduino Uno ( ATMEGA328P-PU ),  work with a ATtiny85 Microcontroller?

The map function uses integer arithmetic, and since the ATmega series and the ATtiny series use the same 8-bit AVR instruction set, there should be no difference when using it, and you are good to go from that aspect.

Consider that there are many other differences regarding I/O pins, storage etc. - that you might want to consider. Here is a good source for a basic comparison between the ATmega based Arduino to ATtiny85.


SIM800L always returns +CREG: 0,2 I'm using a SIM800L module, and I am checking the status of my network with the AT+CREG? command.

However, it always returns the same 0,2:

0 -> disable network registration unsolicited result code

2 -> not registered, but ME is currently searching a new operator to register to

How do I activate 2G or 3G network?

It can take a while to register - sometimes several minutes. Have you left it after power-up for enough time?
If your operator has no signal in your area it will never register. National roaming is normally disabled. If you have national roaming available you will have to manually connect to another operator.
Check that your modem can see your operator with AT+COPS=?


Detect USB activity from a host I am testing a WinCE device that loses all USB communication infrequently. I need to detect when the USB fails on this device. When it fails, the power is intact at the port, just no data at all on D+ and D- (I verified this with an oscilloscope). This host device is basically a black box to me so I can't do anything to it but check it's state.

My proposed solution:  Use an arduino of some type (preferably an UNO since I have one already) programmed to detect USB activity to let me know when USB is failing on the host device I am testing.

Is this possible? The arduino seems like a good solution for me because I assume it is a USB client, which I need in this scenario.  Any example or pointing me in the right direction would be of great help.  Thanks!

If all you are interested in is the voltages on the D+ and D- lines you could wire those direct into two ADC inputs on the Arduino and wire +5V and GND into the +5V and GND pin.  The Arduino can then sample the voltages and compare them to valid or invalid ranges.


Fast I2C communication between ESP8266 & PCF8591 I need faster communication between the ESP and the ADC, so I found this
https://github.com/pasko-zh/brzo_i2c.

Original wire Example

#include "Wire.h"
#define PCF8591 0x48
byte a0;

void setup() {
  Wire.begin(13, 14);
  Serial.begin(115200);
}

void loop() {
  Wire.beginTransmission(PCF8591);
  Wire.write(0x04);
  Wire.endTransmission();
  Wire.requestFrom(PCF8591, 5);

  a0 = Wire.read();
  a0 = Wire.read();

  Serial.println(a0);
  delay(1000);
}

Brzo I2C example

#include "brzo_i2c.h"

uint8_t buffer[10];
uint8_t error = 0;
float temp = 0.0;

uint8_t ICACHE_RAM_ATTR get_temp(float *t) {
  uint8_t bcode = 0;
  brzo_i2c_start_transaction(0x48, 400);
  buffer[0] = 0x04;
  brzo_i2c_write(buffer, 1, false);
  brzo_i2c_read(buffer, 2, false);
  bcode = brzo_i2c_end_transaction();
  *t = ((buffer[0] << 8) | buffer[1]);
  return bcode;
}

void setup() {
  delay(500);
  Serial.begin(115200);
  brzo_i2c_setup(13, 14, 2000);
}

void loop() {
  error = get_temp(&temp);
  if (error == 0) {
    Serial.print("Temp = ");
    Serial.println(temp, 8);
  } else {
    Serial.print("Brzo error : ");
    Serial.println(error);
  }
  delay(500);
}

But I get always the same error.

  1 : Bus not free

I rewrote it in different ways, changing the frequency, pins and doing multiple transactions. The main reason I don't get it to work is the difference in the API.

There is no Wire.requestFrom(); in the brzo_i2c lib. So I need to read the value with brzo_i2c_read(buffer,2,false);.

This line

brzo_i2c_start_transaction(0x48,400);

Sets the SCL frequency to 400kHz.

According to the Datasheet for the PCF8591 the maximum SCL clock frequency is 100kHz.

The other issue may be the "repeated_start" flag on brzo_i2c_write.

If you look at the examples, and "apply" that to your code, your would do something like:

uint8_t ICACHE_RAM_ATTR get_temp(float *t){
  uint8_t bcode=0;
  brzo_i2c_start_transaction(0x48,100); // changed 400 to 100
  buffer[0]=0x04;
  brzo_i2c_write(buffer,1,true); // changed to true because
  brzo_i2c_read(buffer,2,false);
  bcode=brzo_i2c_end_transaction();
  *t=((buffer[0]<<8)|buffer[1]);
  return bcode;
}

My understanding of the code is that you would set repeated_start to true in the write if you want to then immediately read - which in your case you want to.


Arduino Mega connect to 2.1 speakers I am new to Arduino and I want to connect it to my 2.1 speakers and later to a 5.1 surround system.

The purpose is to play some wav sounds when a button is clicked or when a trip laser is cut. What should I do in order to play those wav around through the speakers? I also have an SD shield.

First, you need to figure out the bandwidth requirements and if this is possible at all. You need to do some basic calculations and answer the question if the Arduino and the different components have the bandwidth (byte/second) that is required.

The Arduino MCU (AVR) is too "weak" to do this on it's own. A special shield is required. Such as https://www.adafruit.com/products/1788

The Arduino Due has more processing power but still not stereo quality; https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

More info to be googled.

Cheers!


Sampling stereo audio at greater than 40 Hertz using arduino I am working on a project to make a speaker with reactive lighting. I need to be able to sample stereo audio at a decent rate for songs. The audioRead () function can do about 8 kHz and I have heard you can push it up till 35 kHz but than you can only use it for mono and you cannot use the arduino for anything else.

Someone recommended that I use an ADC. What can it do for me?
Is the arduino's operating speed a limitation?
If not the arduino which other micro-controller is suitable for this purpose.

If you are only interested in getting a reading of the sound intensity,
then 8 kHz may be enough. You can also convert the signal to mono
using a pair of resistors. If you want the Arduino to do other stuff
while taking the analog readings, then you should forego analogRead()
and access the ADC directly. This is more involved that typical Arduino
programming, as it involves configuring the ADC at low-level, in “free
running mode”. In this mode the ADC operates in an autonomous way, and
send you an interrupt every time a sample is ready.

I have written a program that does something similar: it samples an
analog input at 9.6 kHz (104 µs per sample) an periodically
sends the reading through the serial port: sound-meter.ino. You can
probably adapt it for driving LEDs instead of the serial port.


comparison in a time sequence in an Arduino sketch a user is invited to input a number representing a time in the format HH:MM,  this number is to be added at the end of an ordered and limited sequence of times

--the first input (lower limit) can be any time within the 24 hours,

--the upper limit is calculated as lower_limit+period; with period being 1,2,3,4,6,8,12 or 24 hours,

--and to be accepted, the input must verify that it is chronologically after the previous element, and that it's within the given period;

for example if first element is 20:00 and the period is 8, the upper limit will be 20+8=28 wich is 04:00; both 21:00 and 03:00 are accepted, where'is 19:00, 05:00, 09:00, 17:00, ... are rejected.

without any information on the 'day', i did not find any suitable algorithm, and none of the available Arduino libraries is useful in this case.

any link, or tip,...

Here is the basic idea and a sample implementation for solving the problem:

The problem is: Given a start time time1 and a period period, each described by a pair of (hour,minute), how can we check whether another time time2 is within time1 to time1 + period?

First we can see that we given a (hour, minute) pair we can compute the total number of minutes as totalMinutes = 60*hour + minute.

Then we can observe that there two distinct cases that we must check:

the entire "time check period", that is, time1 to time1 + period is within 00:00 to 24:00 without overflowing past 24:00 when we simply add the times. then, we can use a simple bounds check worded as "time2 must be greater than time1 and less or equal to time1 + period when comparing total minnutes.
time1 + period overflows past 24:00. We consider an example of  time1= 20:00 and period = 8:00. Thus all valid times are from 20:00 to 04:00 with an implicit "wrap around" at 24:00 to 00:00. We can see that there are now two time-intervals we must check: Everything from 20:01 to 24:00 and from 00:00 to 04:00 is valid. Thus we can derive the the bounds in minutes again. We can obtain the 04:00 by computing 20:00 + 08:00 modulo 24:00. The C operator % is used to compute the residue of the division by a certain number. I.e. 28 % 24 = 4 because 28 / 24 = 1 residue 4. This is  called modulo-arithmetic.

The following C++ program demonstrates the solution:

#include <cstdio>

/* returns whether time2 defined by hour2:minute2 is within the period time1 = hour1:minute1 to time1 + period. */
bool is_time_within_period(
    int hour1, int minute1,
    int hour2, int minute2,
    int periodHour, int periodMinute) {

        //Reject garbage input
        if(hour1 > 24 || hour2 > 24
            || minute1 > 60 || minute2 > 60
            || periodHour > 24 || periodMinute > 60) {
                //TODO throw error message
                return false;
        }

        //Convert hours and minutes into absolute minutes. One hour is 60 minutes.
        int time1Minutes = 60 * hour1  + minute1;
        int periodMinutes = 60 * periodHour + periodMinute;
        int time2Minutes  = 60 * hour2 + minute2;

        int periodEnd = time1Minutes + periodMinutes;

        //If the start time plus the period time is over 24:00 there is a wrap-around the we need to consider.
        bool wrapAround = false;
        if( periodEnd > (24 * 60)) {
            wrapAround = true;
        }

        bool result = false;

        //printf("Wrap: %d Period end %d\n", wrapAround, periodEnd);

        if(!wrapAround) {
            //if there is no wrap-around we can just compare the total minutes against each other
            //time1 must be after time2 but before (time1 + period).
            result = time2Minutes <= (time1Minutes + periodMinutes) && time2Minutes > time1Minutes;
        } else {
            //There was a wrap around, i.e. start time + period was beyond 24:00.
            //We need to make two comparisons: is it in the time period from time1Minutes to 24:00?
            result = time1Minutes < time2Minutes && time2Minutes <= (24 * 60);

            //the result can also be okay if it from the time from 00:00 to the remaining period
            //use the module operator here. This transforms e.g. 28:00 would be reduced to 04:00. (modulo 24 hours calculated in minutes)
            int upper = (periodEnd % (24 * 60));
            //printf("Upper: %d (%02d:%02d)\n", upper, (upper / 60), upper % 60);
            result |= time2Minutes >= 0 && time2Minutes <= upper;
        }

        return result;
}

int main() {

    const int hourStart = 20;
    const int minuteStart = 0;

    const int periodHours = 8;
    const int periodMinutes = 0;

    //play around with these values
    const int compareTimeHour  = 4;
    const int compareTimeMinute = 0;

    printf("Start: %02d:%02d\n", hourStart, minuteStart);
    printf("Period: %02d:%02d\n", periodHours, periodMinutes);
    printf("Check time: %02d:%02d\n", compareTimeHour, compareTimeMinute);

    bool res = is_time_within_period(hourStart, minuteStart, compareTimeHour, compareTimeMinute, periodHours, periodMinutes);

    if(res) {
        printf("Time is within bounds\n");
    } else {
        printf("Time is not within bounds\n");
    }

    printf("Hello\n");

    return 0;
}

The function is_time_within_period has no dependencies and can thus be copy-pasted into any Arduino sketch.

Let the start time be 20:00 and the period 04:00. Then feeding the program different times to compare against lets us see that it indeed works.

Start: 20:00
Period: 08:00
Check time: 20:00
Time is not within bounds

Start: 20:00
Period: 08:00
Check time: 20:01
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:00
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:01
Time is not within bounds


why am I losing data over serial communication between arduino and pc I'm working on a project for school. I'm trying to rotate a servo by writing the letter that identify the servo and then the angle.

the problem is that sometimes the last number of the angle is lost or the whole angle all together. for example i want to rotate servo "a" 50 degrees. i enter a50 this works most of the time but sometimes i only get a 5 without the zero and sometimes i just get a zero. can anyone help, thanks.

please keep in mind i only did computer science in high school and intro to c++ in college. go easy on me please.

attached is the code and an image illustrating my problem.

#include <Servo.h>

Servo servo1;
Servo servo2;
Servo servo3;

String angle1="";
String angle2="";

char serialbuffer[4];
int index=0;
int charcount=0;

int lastangle;
int dif;

void setup() {
  servo3.attach(3);  // attaches the servo on pin 9 to the servo object

  Serial.begin(9600);

  serialbuffer[0]='0';
  serialbuffer[1]='0';
  serialbuffer[2]='0';
  serialbuffer[3]='0';
}

void loop() {

       charcount=0;
       index=0;
       serialbuffer[0]=99;

   while (Serial.available() > 0) {

      char charbuffer = Serial.read();
       if(charbuffer=='\n'){
          index=0;
        }
        else{

           serialbuffer[index]=charbuffer;
           index++;
           charcount++;
          }

      }

  angle1="";
  if(serialbuffer[0]=='a'){

      for(int i=1;i<charcount;i++){
         angle1+=serialbuffer[i];
      }
      move_servo3(angle1);
      index=0;
      serialbuffer[0]=99;
    }
  delay(15);
}

void move_servo3(String angle2){

   Serial.println(angle2.toInt());
   servo3.write(angle2.toInt());

  }

Are you hand-typing the commands? It is pretty difficult to do that consistently. I ask because your code collects data from the serial buffer until the buffer is empty - i.e. when you pause even slightly in your typing - and tries to act on whatever it has collected so far. That may be (probably will be!) an incomplete command. Even if your terminal uses line-by-line entry, there is still the risk that your code could notice an empty buffer between characters within a line.

Try collecting characters until it sees a newline, instead. That is probably what you intended, and it will be immune to your typing speed. You'll still need to test for .available, but that should only allow the code to collect more characters. Keep collecting until it sees a newline.

What (I think) is happening now is called a race-condition. That means that the program's behavior is dependent on which of two (or more) events happens first, and the order of their occurrence is indeterminate. Race conditions are especially hard to find when the order of two events is almost always the one you expected. Notice the "gotcha" word in that sentence? :)


Multiple serial monitors with the same arduino mega I’ve got mega 2560.
In my project serial port is used for communicating with PC.
However, I’d like to see debug info in serial monitor. Mega has a few hardware Serial ports. How to use one of them got extra serial monitor?

Use an USB to TTL Serial adapter. Wire it to one of the RX/TX pin pairs and in code use the corresponding Serial object Serial1, Serial2 or Serial3. Don't forget to wire Ground.

You can use some terminal program or Serial Monitor in Arduino IDE to communicate over the adapter. You can open a second instance of the Arduino IDE by starting it with the Desktop or menu shortcut. In this instance you can select a different port then the sketch upload port.


How should I initialize a RepRap Discount 12864 on u8glib? I was taking the advantage of an existing piece of hardware (RepRapDiscount Full Graphic Smart Controller) for my present project.

Here is a link for the RepRap wiki about the controller

#define LCD_PIN_SCLK   A4
#define LCD_PIN_MOSI   6
#define LCD_PIN_CS   8
U8GLIB_ST7920_128X64_1X u8g(A4,6,8, U8G_PIN_NONE);

But all I got is a blank screen with no light at all. What has happened?

I solved the problem myself. It turns out to be a problem of wrong pinouts.

My PCB of the project was originally designed for the LCD2004 counterpart, and I thought it was a drop-in replacement for 12864. But no, it's not.

This is the "Smart Adaptors". Notice that the orientation are 180 degree different.

If you have the same problem not lighting up a 12864 when switching from 2004, or vice versa. Check your orientation as above.

My solution will be crimping a different JTAG wire instead.


Getting error 32 in multi-master I2C sketch with library https://github.com/rambo/I2C I am developing a multi-master scenario sketch with the https://github.com/rambo/I2C library, because this library will handle multi-master data collisions.

I created a setup with two Arduino nano's which act both as master and slave.
My sketch works as long as I use only one master. Sending data from one Arduino to the other works fine. The other receives the data.

But when I sequentially try to send data from the second Arduino to the first, I get an error (32). After that even sending data from the initial Arduino results in error 32.

This is the used sketch for both the Arduino's.
The only difference is that I switch the values of rel_address and own_address when programming the seconds Arduino.

Sending data is done by pressing a button on pin 2 (switchPin)

/**
   atme328 = ATmega328
   SDA --> Pin A4
   SCL --> Pin A5
*/
#include <I2C.h>
#include <Wire.h>

int switchPin = 2;
int relayOnPin = 3;
int relayOffPin = 4;

uint8_t broadcast_address = 0;
uint8_t own_address = 11; // CHANGE FOR EVERY MODULE!!
// rel_address = address of relay to switch; SET to own_address if relay is connected to this chip!
uint8_t rel_address = 10; // CHANGE FOR EVERY MODULE!! SET to own_address if relay is connected to this chip!
uint8_t rpi_address = 1;

unsigned long counter = 0;

void setup() {

   Serial.begin(9600);
   pinMode(switchPin, INPUT_PULLUP);

   pinMode(relayOnPin, OUTPUT);
   pinMode(relayOffPin, OUTPUT);
   // start condition
   digitalWrite(relayOnPin, HIGH);
   digitalWrite(relayOffPin, LOW);

   I2c.begin();
   I2c.timeOut(50);
   // I2c.pullup(true); // done by external 4.7kOhm resistors

   // config Wire library for I2C slave functionality
   Wire.begin( own_address );

   TWAR = (own_address << 1) | 1;  // enable broadcasts to be received!

   // set slave receive callback
   Wire.onReceive( onI2CReceive );

}

void loop() {
   counter = counter + 1;
   if (counter == 20000) {
      digitalWrite(relayOnPin, LOW);
      digitalWrite(relayOffPin, LOW);
   }
   if ( digitalRead(switchPin) == LOW ) {
      sendCmd('d', rel_address); // send command to remote relay
   }
}

void sendCmd(uint8_t cmd, uint8_t address) {
   uint8_t status = I2c.write(address, cmd); //configure device for continuous mode
   if (status > 0) {
      // error codes at https://github.com/rambo/I2C/blob/master/I2C.cpp
      Serial.print(status, DEC);
      Serial.print('!');
      digitalWrite(relayOffPin, HIGH);
      delay(50);
   } else {
      digitalWrite(relayOnPin, HIGH);
      Serial.print('.');
   }
   counter = 0;
}

void onI2CReceive(int howMany) {
   // loops, until all received bytes are read
   while (Wire.available() > 0) {
      digitalWrite(relayOffPin, HIGH);
      Serial.write(Wire.read());
   }
   counter = 0;
}

What do I need to do to be able to send from two units using this library?
Thanks!

You cannot use the I2C library and the Wire library at the same time. From the code I guess you wanted the Wire library to do the slaves job and the I2C library to implement the master. But since both libraries use the same hardware, this cannot be divided between them. Combining two libraries for the same hardware isn't that trivial. The I2C library only provides master functionality. So, to reach your goal, you would have to find a library, that provides both master and slave functionality while doing correct bus arbitration (which is the term for correctly handling master data collisions). Or you have to change one of the two libraries yourself, to provide the missing functionality.

And the error you get is defined in #define MT_SLA_NACK    0x20 in I2C.h (0x20 is equal to 32). This means, that you haven't got an acknowledgement from the slave you have addressed. This suggests, that in your current code only the master functionality is working. (But it may have another meaning considering the interaction of the two libraries on the same hardware)


please tell me how do I fix this code down here(please tell in my easy English) LiquidCrystal 1cd(12, 11, 5, 4, 3, 2);

 void setup() {
   1cd.begin(16, 2);
   1cd.print"abbu, kya, chalrelaye!");
 }

 void loop() {

 }

Variable names MUST NOT start with a digit. Only '_' and a-z are allowed!

1cd really should be lcd with an 'ell' instead of a one (1).


PCINT with my arduino UNO says redefinition of 'void __vector_4()' So i'm working on a quadcopter controlled by the arduino UNO, and focusing in pin interrupts for the reciever. This is the code for the reciever.

unsigned long timer[4];
byte last_channel[4];
volatile int input[4];

void rx_initialize() {
  PCICR |= (1 << PCIE0);
  PCMSK0 |= (1 << PCINT0);
  PCMSK0 |= (1 << PCINT1);
  PCMSK0 |= (1 << PCINT2);
  PCMSK0 |= (1 << PCINT3);
  Serial.begin(9600);
}

ISR(PCINT1_vect) {

  timer[0] = micros();//Lire la valeur PWM en microsecondes

  //////////////////////////CHANNEL1/////////////////////////////
  if(last_channel[0] == 0 && PINB & B00000001){//vaut digitalRead(HIGH); mais en plus rapide
    last_channel[0] = 1;//le state est HIGH
    timer[1] = timer[0];//Lire combien de temps HIGH
  }
  else if(last_channel[0] == 1 && !(PINB & B00000001)){
    last_channel[0] = 0;//le state est HIGH
    input[0] = timer[0] - timer[1];
  }

  //////////////////////////CHANNEL2/////////////////////////////
  if(last_channel[1] == 0 && PINB & B00000010){//Rising
    last_channel[1] = 1;//le state est HIGH
    timer[2] = timer[0];//Lire combien de temps HIGH
  }
  else if(last_channel[1] == 1 && !(PINB & B00000010)){//Falling
    last_channel[1] = 0;//le state est HIGH
    input[1] = timer[0] - timer[2];
  }

  //////////////////////////CHANNEL3/////////////////////////////
  if(last_channel[2] == 0 && PINB & B00000100){//Rising
    last_channel[2] = 1;//le state est HIGH
    timer[3] = timer[0];
  }
  else if(last_channel[2] == 1 && !(PINB & B00000100)){//Falling
    last_channel[2] = 0;//le state est HIGH
    input[2] = timer[0] - timer[3];
  }

  //////////////////////////CHANNEL4/////////////////////////////
  if(last_channel[3] == 0 && PINB & B00001000){//Rising
    last_channel[3] = 1;//le state est HIGH
    timer[4] = timer[0];
  }
  else if(last_channel[3] == 1 && !(PINB & B00001000)){//Falling
    last_channel[3] = 0;//le state est HIGH
    input[3] = timer[0] - timer[4];
  }
}

I'm using various files for every other part of the quadcopter such as PID controlling and IMU Reading.

But avrdude tells me that I did a redefinition of 'void __vector_4()'.
Itried to look into PinChangeInt.h in the Arduino library folder but still no solution to the problem.

Thank you for your help!

__vector_4() is just another name for PCINT1_vect(). The error
message simply means that you have defined that function twice. One
definition is explicit in the code you are showing to us. I cannot see
the other definition: obviously you are not showing all of your
code. Most likely that other definition lies inside some library you are
using in your program.

Since you cannot define an ISR twice, you will have to use another PCINT
which is not already in use. Or you could modify the library and try to
merge it's PCINT1_vect() with yours.

BTW, the error message does not come from avrdude, it comes from the
linker.


Connect 5v 30a relay with Arduino Uno I have previously connected 5V 10A relay switches to my Arduino.

But for my new project I need to use a 5V 30A relay switch with my Arduino.

In 10A relay switches, we make connection with Arduino using GND, VCC and IN.

But for 30A switches, there are DC+, DC-, IN.

My question is that, how do I connect my Arduino to the relay using these pins?

From the Amazon page you linked to:

  1 dc+ : Dc power supply positive pole
  2 dc- :Dc power supply negative pole (i.e. ground)

Arduino:
VCC: positive DC power supply
GND: ground

technically, VCC = the voltage at the collector of a transistor, these days it's used as shorthand for the positive output pin of an IC.


What is Reverse Current through an Arduino? Can someone explain (in a non-wiki technical way) what reverse current is through an Arduino ? Cheers y'all

It's current flowing "the wrong way".

The electronics inside the main chip are designed such that the + side (Vcc) must be at a significantly higher voltage than the - side (GND).  By significantly I mean 2.1-5.5V higher.

Because of that it is expected that the current will flow through the components in one direction (or in a couple of pre-determined directions depending on settings).  Any situation which causes a reversal of that current through the internals is bad, and as called "reverse current".

It could be caused by something as simple as connecting a power supply backwards, or more technical things like the "Back EMF" from an inductive load (motor, relay, etc) entering a pin that is an output and flowing backwards up to Vcc, or "Back Powering" where the chip is not powered but some external device connected to it is powered, and it "leeches" power backwards through IO pins to power the chip.

All of those situations are bad and should be avoided.


NeoPixel setPixelColor works only in for loop I am working with a NeoPixel RGB led and have gone through various tutorials but I have a question regarding the setPixelColor().

If I do not have my setPixelColor() and show() inside of a for loop it will not work.

This works:

void holoLight(uint32_t c){
  for(uint16_t i = 0; i<2; i++){
    holo_pxl.setPixelColor(i, c);
    holo_pxl.show();
    delay(2500);
  }
}

This does not:

void holoLight(uint32_t c){
    holo_pxl.setPixelColor(1, c);
    holo_pxl.show();
    delay(2500);
}

I am sure it is something specific to the language or execution but would love some clarifications, thanks =)

I am not sure I fully understand your exact problem but you have to be aware that holo_pxl.setPixelColor(1, c); set the color of the second LED in a NeoPixel chain, NOT the first one.

For the first LED, you have to use holo_pxl.setPixelColor(0, c); instead.


LED matrix question light up H or 4 Just a basic query;

On my understanding of LED Matrix's, The following would light up 4 LEDs.

But what if I only wanted to light up just 3 of those LEDs? The circuit still needs the same inputs, since power will continue across all columns/rows

Thanks

Tom

Multiplexing is the answer.

If you want to, as an example, light up only LEDS 1, 3 and 4, you will:

activate line A
activate line X
de-activate line X
de-activate lines A and B (yes, B was not active)
activate line A and B
activate line Y
de-activate line Y
de-activate lines A and B
start again from top

Do this so that the loop takes less than 10 milliseconds and you are actually refreshing the entire matrix at 100Hz, fast enough to trick the eyes of any human being as if the LEDs 1,3 and 4 are lighted up at the same time: persistence of vision is your friend.


Why can't my IF statement see a global? I'm rather new to Arduino programming. I have a problem compiling the following bit of code:

const int relay1 = 10;  //Power Relay 1
const int relay2 = 11;  //Power Relay 2
const int relay3 = 12;  //Toggle Relay
const int button1 = 3;
const int button2 = 4;
const int button3 = 5;

//---Button States---\\
int button1State;   //Current state of Button 1
int button2State;   //Current state of Button 2
int button3State;   //Current state of Button 3
int button1State_prev = LOW;  //Previous state of Button 1
int button2State_prev = LOW;  //Previous state of Button 2
int button3State_prev = LOW;  //Previous state of Button 3

//---General Variables---\\
int userSelection = 0;
int interlockState = 0;
int platformState = 0;

//---Interval-Tracking Variables---\\
unsigned long lastTime_Debounce1 = 0;   //Button 1 debounce time
unsigned long lastTime_Debounce2 = 0;   //Button 2 debounce time

//---Activity Delays---\\
const unsigned int relayDelay = 10;           //Delay between relay actions (ms)
const unsigned int debounceDelay = 60;        //Delay for button de-bouncing (ms)

void setup() {
  //Configure Pins
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);

  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
  digitalWrite(relay3, LOW);
}

void loop() {
  //Read value of each input pin
  int button1Reading = digitalRead(button1);  //Current reading of Button 1
  int button2Reading = digitalRead(button2);  //Current reading of Button 2
  int button3Reading = digitalRead(button3);  //Current reading of Button 3

  //Debounce Button1
  if (button1Reading != button1State_prev) {
    lastTime_Debounce1 = millis();
  }
  button1State_prev = button1Reading;
  if ((millis() - lastTime_Debounce1) > debounceDelay) {
    if (button1Reading != button1State) {
      button1State = button1Reading;
    }
  }

  //Debounce Button2
  if (button2Reading != button2State_prev) {
    lastTime_Debounce2 = millis();
  }
  button2State_prev = button2Reading;
  if ((millis() - lastTime_Debounce2) > debounceDelay) {
    if (button2Reading != button2State) {
      button2State = button2Reading;
    }
  }

For some reason, the compiler is convinced that the variable lastTime_Debounce1 in the second IF-statement, on Line 54, has not been declared in-scope. I don't understand how this is possible, since the variable in question is a defined and initialized global.

If I comment-out the first trio of IF-statements (handling Button 1), the second trio (handling button 2) has no problem compiling, even though it does exactly the same thing in exactly the same way.

I checked all the usual suspects: spelling, braces, semicolons, even commented-out blocks of code one at a time, but I can't find the source of the problem. I'm using the Arduino 1.8.2 IDE.

Can someone please point out the mistake I'm missing?

The backslash in your comments are the problem. As per C++ language definitions, a \ at the end of the line is interpreted as a "line continuation". Thus, your comment gets continued in the next line and your variable declaration and initialization is commented out.

This is apparent when opening your code with a good syntax highlighting program, like Notepad++.

Removing all \\ from the end of the comment line solves your problem.

Side note: For more info, look at https://stackoverflow.com/a/30290133/5296568. Backslashes at the end of a line are actually useful when used in multi-line macro definitions.


ESP8266: Multiple analog inputs using software Is there a way to get at least three analog inputs to the esp8266 (without a multiplexer)?

Each digital or analog pin on an Arduino can be configured as digital or "analog" (e.g., PWM software).

Here is a way to squeeze one additional analog input pin: hackaday.io/project/8435-2-analog-inputs-for-esp8266-without-multiplexer

Any ideas or software?

1) nope it's not possible "in a straightforward way". you should use analog muxes.

2) the statement "Each digital or analog pin on an Arduino can be configured as digital or "analog" (e.g., PWM software)." means for PWM or the so called "analog output". not intended the ADC unit.

3) the link provided uses software tricks to measure 2 signals in a muxed fashion. it's up to purpose.

workarounds :

1) use CD4066 CMOS bilateral switch. it works with analog signals.

2) use GPIOs to supply voltage to measurement units. like the link you provided. it works for passives like photoresistors and for devices like LM35 temp sensor. but can't be used for devices like 3 channels analog-out accelerometers.


Arduino DUE as a FTDI programmer I want to use Arduino DUE board as a FTDI programmer.

The task is to program ESP32 module which is connected to the Arduino Serial port.

I can use only DUE Native port. There is no DUE programming port in my design.

Yes, it is possible, and not too difficult. Also, the native port is a lot faster than the programming  port ;)
All you need to do is to read the serialUSB data in and write it to the SerialX port, and read the data in from the SerialX port and write it to the SerialUSB port. It's best to do it on a byte by byte basis, and the due should be plenty fast enough.
This code should do the job. Let me know if it doesn't, and I'll take a look. (I have a Due and esp32)

void setup(void) {
  SerialUSB.begin(9600); //speed here doesn't matter as far as I am aware.
                         //the serial baud here should match the speed that
                         //you try to upload at to the esp32
  Serial1.begin(9600);   //change the Serial port to suit your needs
}
void loop(){
   if(SerialUSB.available()> 0){
    Serial1.write(SerialUSB.read());
   }
   if(Serial1.available()> 0){
    SerialUSB.write(Serial1.read());
   }
}


Datalogger with interruputs I'm trying to do a data logger. Writes into SD card has to stop when millis()=1000. Maybe I have a problem between millis() and my interrupt, because datalogger doesn't stop after millis()=1000. I'm working with Arduino Mega.

#include <SPI.h>
#include <SD.h>
volatile unsigned int cuenta = 0;
unsigned char contador = 0x00;
const int chipSelect = 53;
long currentMillis = 0;
long previousMillis = 0;
long interval = 1000;

void setup() {
  DDRA = B11111111;
  cli();//stop interrupts
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 10000khz increments
  OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);
  sei();//allow interrupts
  //periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");
}

ISR(TIMER0_COMPA_vect) {
  cuenta++;
  if (cuenta > 9) {
    PORTA = ++contador;
    cuenta = 0;
  } else {
    PORTA = 0X00;
  }
}

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis <= interval)
  {
    String dataString = "";
    for (int analogPin = 0; analogPin < 1; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString = String(sensor);

      if (analogPin = 1) {
        dataString += ",";
      }
    }
    File dataFile = SD.open("datalog2.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
    }
    else {
      Serial.println("error opening datalog.txt");
    }
  }
}

The millis() function is based on a counter which is incremented by
the Timer 0 overflow interrupt. Since you reconfigured
that timer to never overflow, that counter is not incremented anymore.

If you want to configure an Arduino timer for your own purposes, you
have to either:

use any timer other than Timer 0, or
loose the Arduino standard timekeeping functions: millis(),
micros() and delay().

I would favor the first option, especially on the Mega which has quite a
few spare timers.


NodeMCU keeps disconnecting I have made a home automation system consisting of a NodeMCU, 4 channel relay board running on Blynk and IFTTT.

At the moment I'm only controlling a string of fairy lights and two LED strips from it, both connected to the relay of course.

The only code running on the NodeMCU is the Blynk ESP8266 Standalone code. Here it is (with the necessary changes of course) -

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";

void setup()
{
  // Debug console
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
}

void loop()
{
  Blynk.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}

Now the thing is, the NodeMCU automatically disconnects from the WiFi randomly. Sometimes it reconnects immediately, sometimes it doesn't reconnect at all and I have to keep hitting the reset button to get it working again.

This is really annoying as everything I got connected to the NodeMCU also comes on all of a sudden and scares the hell out of me.

The code is all fine, the power supply is stable (5v 1A), all the cables are in place and the NodeMCU is tucked away in a corner where nobody touches it.
I can't seem to work out why is this happening.

Any fixes for this?

I had this same issue with an ESP8266 NodeMCU-12E using Cayenne in the past. It would drop connection for no apparent reason, but no matter what, most of the time it'd never reconnect until a reset. Here's what I did:

CAYENNE_DISCONNECTED(){
  Serial.println(F("Cayenne disconnected, rebooting..."));
  ESP.restart();
}

I've never used Blynk before, but after a quick look, this may do the same thing (untested):

if (! Blynk.connected){
  Serial.println(F("Blynk disconnected, rebooting..."));
  ESP.restart();
}

It effectively reboots the ESP unit if the connection to Blynk drops for any reason.


Arduino Mega with two Arduino Unos as slaves via I2C? Good morning!  This is my first post here, and my first time diving into the world of microcontrollers.  Bear with me, as I describe this theoretical project.

I've got an Arduino Mega 2560, two Arduino Unos, one accelerometer, two Wii Nunchucks (with Nunchucky adapters) and two 3-axis joysticks.  I'm curious how to go about wiring/programming the two Unos to the Mega as slaves; both with one nunchuck and joystick going to them to control a set of servos/actuators each, for a total two sets of servos/actuators.  The accelerometer will be connected directly to the Mega, and will control a third set of servos/actuators via head-tracking (accelerometer mounted to a headset).

I've been reading all over, and the first thing I need to learn is how to go about establishing I2C between the Mega and two Unos.  I found a few diagrams, but wasn't sure if that way was best for my application.  After the I2C is established, I am interested in learning how to make accelerometers and joystick potentiometers most effectively control servos and actuators.  I'm also interested in how to program buttons to playback pre-programmed servo sequences, but I'm getting way ahead of myself.  If anyone's wondering about this project, it's for a large animatronic suit.  Any advice is welcome, and thanks for reading!

*edit: I made a sketch in Fritzing to give you an idea of what I have in mind.  Don't mind the accelerometer on the left- that'll come later when I get into solenoids.

Welcome to the wonderful world of microcontrollers!  Looks like an exciting project, and you will definitely learn a lot!

As for wiring with I2C, you have a few things to connect:

SDA (the "data" line)
SCK (the "clock" line)
GND (ground)

For I2C (which is also called TWI for two-wire interface), you connect all like lines together.  This means connect all the SDA pins (analog pin 4 [A4] on Unos, digital pin 20 on the Mega) and all the SCK pins (analog pin 5 [A5] on the Unos, digital pin 21 on the Megas).  I think the schematic is different than this.  I can't read the actual lettering on the boards because the image resolution is not high enough.  You also want to connect all the ground pins together, which you've done in your drawing.

If you want a quick way to get up and running with I2C, use the example sketches in the Arduino programming environment.  Open up Arduino, then go to File > Examples > Wire.  In your case, I would pick one master and use the other two as slaves.  I would try using the master_writer on the Mega and slave_receiver on the 2 Unos.  A good idea would be to leave all of the accelerometers, potentiometers, etc. off to start.  Just have the master send a command to the two slaves, and when they receive it they can light up their on-board LED:

digitalWrite(13, HIGH)

Another note: the Fritzing sketch shows a 3.7V battery powering the Arduinos, but they need 6-20V and it's best to use 7-12V.  This may just be a filler battery you threw in for the drawing, I understand.  Just in case, I thought I'd mention it.

As suggested by Nick Gammon above, you will probably get the best response by breaking up the rest of your post into individual questions.  Good luck with your project!  Sounds like a fun one!


Arduino using delay in I2C receiveEvent I have read before that you can't use delay() inside I2C receiveEvent because it is an ISR.
What I want to do is as follows: I have a servo connected to my Arduino Uno and I want to control that using an I2C signal. Since I want to decrease the speed of the servo, I was previously using a loop with delay inside, which doesn't work when the function is called by I2C.
This is the code that I used before to control the servo:
void setServo(bool status) {
    if (status) {
        for (int pos = 0; pos <= 180; pos += 5) {
            servo.write(pos);
            delay(50);
            Serial.println(pos);
        }
    } else {
        for (int pos = 180; pos >= 0; pos -= 5) {
            wasteFlapServo.write(pos);
            delay(50);
            Serial.println(pos);
        }
    }
    servoStatus = status;
}

How could I still control the speed of the servo even if I use I2C? Thanks for your help.
Kind regards,
Moritz

The general way of doing long things triggered by an ISR is to simply set a flag insode the ISR, which then gets checked inside void loop().
volatile byte flag = 0;

void loop(){
    if(flag){
        // Do something here
        flag = 0; // reset the flag
    }
}

void receiveEvent(int howMany){
    flag = 1; // set flag, if correct data was received
}

Here keep the following in mind:

The loop() needs to run fast to react fast. Long delays are doing other long stuff there will impact the responsiveness of the code. Depending on your plans for the exact behavior, the usage of delay() is generally not good. You should look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning that rather early.

flag mus be declared volatile, to tell the compiler, that is may change at any time. Otherwise it might optimize the variable away.

flag is of type byte here. It is imprtant, that this flag only has a single byte, because reading and writing of a single byte cannot be interrupted. Multi-byte variables get read or written in multiple COU cycles, thus it would be possible, that the interrupt writes parts of the variable, while you are reading it in the main code. That would lead to garbled data. By using a single byte, you avoid using critical sections for keeping the reading in main code save. For a flag thats way simpler.


Arduino resets itself If I connect more power consuming components to Arduino, it gets reset. What is the cause of this observation?

When powered through USB there is a resettable polymeric ("poly") fuse. If you draw more than about 500mA this fuse will cut out and isolate the power.  When you remove the load the fuse will reset and allow power back to the board.

"Poly" fuses are in fact "Positive Temperature Coefficient" (PTC) thermistors. As they get hot their resistance increases (as opposed to the NTC thermistors you use for temperature sensing where the resistance decreases as they get hotter).  The current flowing through the PTC causes it to warm up. Too much current and it gets too hot, and the resistance gets too high (it's non-linear, so the resistance suddenly increases a lot).


My GY-MAX30100 pulse oximeter issue with Arduino Uno I connected the purple oximeter (GY-MAX30100) to the Arduino Uno with the following connections.

OXIMETER       ARDUINO UNO
VIN              5V
GND              GND
SCL              SCL
SDA              SDA
INT              D2

It shows me inaccurate measurements.

13:16:02.851 -> Pulse oxymeter test!
13:16:02.851 -> BEAT
13:16:02.851 -> BPM: 8616.35 | SaO2: 92.01%
13:16:03.055 -> BEAT
13:16:03.055 -> BPM: 4313.73 | SaO2: 92.66%
13:16:03.089 -> BEAT
13:16:03.089 -> BPM: 1209.15 | SaO2: 92.74%

I used this sketch from github
https://github.com/xcoder123/MAX30100/blob/master/max30100.ino

This is the sensor

EDIT

I have run an I2C scanner and this is the result: I2C device found on address 0x57. The library has the same address hard coded in it.

There are 2 newer libraries you can try. I have used both with a MAX30102 and they work.

The first one is here: SparkFun_MAX3010x_Sensor_Library. There are several sketches included, and this one worked for me: Example5_HeartRate.

The other library I had success with is this one: Protocentral. It has a test sketch that writes the data to the serial port, but you can add Serial.println() statements to it to see if the data "makes sense".


Reverting Arduino Environment on OS X I am using Arduino environment 1.6.17 on OS X, 10.12.2. In this version, all of the core avr library stuff is located in ~/Library/Arduino15.

I was told by a vendor that in order for their program to compile properly, I needed to compile it under 1.6.4 of the Arduino environment. I dowloaded that version and compiled the program again. I could tell though, by the compiler messages, that while the IDE may be version 1.6.4, the program was still compiling with version 1.6.17 tools and avr libraries. Is there anyway to change that so I can get it to actually compile with all tools and libs from 1.6.4?

I didn't try the total removal of the environment and then a re-installation as JRobert suggested, because I didn't really want to nuke my current environment. But his post did inspire me to try and run the 1.6.4 environment from another user account that had never run any Arduino stuff before. This seemed functionally equivalent to his or her suggestion. That seemed to work. Although, I still have a feeling that there is a more convenient solution out there.


How to remember variable values after rebooting an Arduino Uno R3 board? Is there any way to store the values of necessary variables somewhere (may be in a file that gets updated by the program at various events), which can be read back when program starts after rebooting the Arduino board?

I am trying to control my AC appliances using IR remote control. Where I want Arduino to remember what was on and what was off in my room after a power failure.

Using EEPROM looks like a fairly good solution, though it has a limitation of 100,000 writes which is making me try to find another way out.

Using an external EEPROM which doesn't have that limitation or its fairly big, is a really good idea I got from fuenfundachtzig, thanks for this great idea. But I don't know how to implement this in my project. Any resource to gather knowledge on using external EEPROM, will be much appreciated.

Thank you all...

The internal RAM of the Arduino will be reset when you repower the chip, so if you want to keep your data, you need to store it in EEPROM.

If you are worried about the limited write/erase cycles, you should estimate how often the data would be updated (i.e. written to EEPROM) and how long you plan the lifetime of the device you build. If 100,000 cycles then still is an issue, you have several options:

Keep the variables in RAM and only write them to EEPROM say every 5 minutes (100,000 cycles then makes about one year of continuous usage until the EEPROM might fail).
Use an external EEPROM (in a socket) that could be easily replaced if needed.
If replacing it is not an option, consider using an FRAM instead (advantage vs EEPROM: much more erase/write cycles but also very expensive, so not an option for large amounts of data but certainly for a few variables).

Note, however, that your description sounds like a typical use-case for user settings that you don't want to get lost on reboot. For those the internal EEPROM is the right place: only store them when they're changed and you're golden -- the user won't change them a 100,000 times easily...


Using an IR sensor from another manufacturer I am currently trying to create a line tracing robot with my Arduino Uno.

I have an IR Sensor (http://support.robotis.com/en/product/auxdevice/sensor/irsensor_manual.htm) but I am not sure if I can use this for my Arduino.

Can someone please tell me if I can? Thanks in advance.

Yes, you will need to connect the sensor ADC line to an ADC input on the Arduino and calculate the range from the analogread result.  You should be able to use one of the Sharp sensor libraries, although you may need to apply a correction factor to the distance results.


Accelstepper run stepper backward Update:

Below I implemented how I understood your suggestions. And it still does only turn in one direction (forward). Curiously if I entered M_DEST in the stepperOneForward() function it turned forward very long but smooth. The code below made it rotate as usual very jittery. Is this the acceleration part and if so how can I change that ? Ideally I would be able to tell the stepper go to position X and return to start and that in constant speed.

 #include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

unsigned int DEST = 800;
unsigned int M_DEST = -800;
unsigned int SPD = 1600;
unsigned int ACCEL = 800;

AccelStepper stepper1(1,stepPin,dirPin);

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);

  stepper1.setEnablePin(enPin);
  stepper1.setPinsInverted(false, false, true);
  Serial.begin(9600);  // Start Serial
}

void loop() {

stepperOneForward();
Serial.println("Stepper1 turned forward.");
delay(1000);
stepperOneBackward();
Serial.println("Stepper1 turned backward.");
}

void stepperOneForward() {

  stepper1.enableOutputs();
  stepper1.setMaxSpeed(SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(DEST);
  if (DEST > 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  //stepper1.disableOutputs();
  }
 }

 void stepperOneBackward() {

  stepper1.enableOutputs();
  stepper1.setMaxSpeed(SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(M_DEST);
  if (M_DEST < 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  //stepper1.disableOutputs();
  }
 }

I have multiple steppers that I would like to run forward until they hit a microswitch and backwards to the initial position. But to simplify things I would like to control one stepper going forward and then backward. The code below always just turns clockwise.

I tried to set the dirPin to low, which did not work.
I tried to reverse the setMaxSpeed (by putting a minus in front of it).
I found the "enum AccelStepper::Direction" class in Accelstepper that did not explain how to to set DIRECTION_CCW or DIRECTION_CW.

What I would like to achieve is control these steppers so they move smoothly forward, wait and then backwards. This should be very easy, but has frustrated me now for too long. I would use any library at this point that can do this and control more than 1 stepper.

The SPD and ACCEL values are so high because I use microstepping (6400 is a full cycle).

#include <AccelStepper.h>

const int stepPin = 5;
const int dirPin = 4;
const int enPin = 12;

unsigned int DEST = 6400;
unsigned int SPD = 1600;
unsigned int ACCEL = 800;

void setup() {

  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
  pinMode(enPin,OUTPUT);
  Serial.begin(9600);  // Start Serial
}

void loop() {

stepperOneForward();
Serial.println("Stepper1 turned forward.");
stepperOneBackward();
Serial.println("Stepper1 turned backward.");
}

void stepperOneForward() {

  AccelStepper stepper1(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper1.setMaxSpeed(SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(DEST);
  if (DEST > 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

 void stepperOneBackward() {

  AccelStepper stepper1(1,stepPin,dirPin);
  digitalWrite(enPin,LOW);
  stepper1.setMaxSpeed(-SPD);
  stepper1.setAcceleration(ACCEL);
  stepper1.move(DEST);
  if (DEST < 0) {
    while ( stepper1.distanceToGo() > 0) {
      stepper1.run();
      }
  digitalWrite(enPin,HIGH);
  }
 }

First, you are creating/destroying the AccelStepper stepper1() object at every call. This is not right, as the library can no longer keep track of the stepper position and state.

The stepper object should be created in the global scope (that is, outside of setup() or loop()).

Second, you can call stepper1.setEnablePin(enPin) and stepper1.setPinsInverted(false, false, true) after you create the object to have the AccelStepper library control the enable pin and to set the enable pin to operate active-low. Then the driver is enabled or disabled with calls to stepper1.enableOutputs() and stepper1.disableOutputs(). In practice, you would not disable the driver except for power saving, as the stepper can no longer hold it's position when the outputs are not enabled. It will lose it's position.

Third, do not set the speed to a negative value. The direction of the stepper is determined by the library based on the current position and the desired end position. When the library is created, the position is zero. You can set the new position in several ways:

stepper1.move(): Set the target position relative to the current position. This means to go backwards you pass this function a negative value. It will add this (negative) number to the internal target position, and then run() will work to get it there.
stepper1.moveTo(): Set a new absolute position. If you initially set the position to 100 and move there, then set it to 50, the stepper will run in reverse to be able to reach position 50. If you start in position 0 and run to 50, it will run forward. If you start at 0 and set to -50, it will run in reverse to get there, and so on.


Does Arduino run AC or DC Does arduino run AC or DC? Based on my small knowledge on the crystal in an arduino, it seems like AC makes sense. True? No?

As a general rule, any modern electronic device with computational ability has to use DC. The reason is that they use specific voltage levels to indicate binary/logical states (i.e. 0's and 1's).

In theory, an ideal DC supply (Direct Current) should provide a constant voltage. That allows the circuit to effectively turn it on an off to represent binary states. (In reality, there's no such thing as truly "off" though, because voltage is relative.)

However, the voltage from an AC supply (Alternating Current) is constantly varying. If you plot it on a chart, you should see a nice sine wave, flowing smoothly between positive and negative several times per second. Hypothetically, if a digital circuit tried to use AC then it would get very confused, because everything would seem to be turning on and off all the time.

With all that said, it's very common to turn AC into DC through a process called rectification. For example, that's what allows DC devices to get power from an AC outlet (e.g. to run your computer or charge your phone).


Which wireless technology should I use for my outside "check-if-door-is-open" project? I want to connect a magnetic door open/closed sensor to a device that can transmit (or be queried for, whichever) the state of the door to a hub inside (probably RaspberryPi). The outside unit should...

Operate on as little power as possible (outside unit will consist of board, open/closed sensor, power, and transmitter)
Be able to transmit from my back yard to inside my house (~15 meters to house & 1 or 2 walls).

I am new to this and pretty confused as to whether I should use BLE, Zig/xbee, or 2.4ghz rf (is that different? I am not even sure...).

Other considerations are cost (of course) and ease of use. I am a novice with hardware & want something easy to get up and running.

I agree with @Gerben - the nRF24L01+ would probably be the most suitable for your application.  It should have enough range to go 15m through a few walls, and the cost is about as cheap as you can get.

You can pick up cheap Chinese clone modules (not real nRF24L01+ but another chip that operates exactly the same) for around $2 each on eBay.  I by them by the bag full.

There are a few good libraries around for controlling them with an Arduino so programming really isn't much of a problem.

They even have the advantage that they can operate in a mesh network mode if you ever expand your system to incorporate other things.

The connection to the module is a simple 5-wire SPI interface - SDC, MOSI, MISO, Chip Enable and Command Select pins, so you don't even need to mess with lots of wires.

You can read more about using them here: http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01

The best library in existence is the RF24Network library: https://github.com/maniacbug/RF24Network

If you are looking for something more self-contained and stand-alone, you might look at the ESP8266 modules which are a programmable WiFi module.  They can either interface with an Arduino to be controlled through AT commands, which is quite nasty, or they can be programmed directly using an Arduino-like API which can be obtained here: https://github.com/esp8266/Arduino

These modules are a little more expensive, but that cost is offset by not then needing an Arduino in the mix as well.  The NodeMCU is probably the easiest to work with since it contains the USB serial interface on board like an Arduino.  It also has its own Lua based programming environment if you don't mind learning another new language, but you can use it with the Arduino API for ESP8266 above.

The ESP8266 is also supported by the beta version of UECIDE


Troubleshooting optocoupler I'm trying Project 15 from the Arduino Uno Projects book (optocoupler).

I manage to turn on and off a LED in a separate circuit using my Arduino-driven optocoupler.

Now I tried to also turn on some real device (battery-driven toy from my kid that she doesn't used anymore). Replacing the toy's original switch with jumper wire leaves it running, so I'm confident that it basically works. But putting my optocoupler in between, it just won't fire up.

Measuring resistance on the 4N35's output bins as advised here, I obtain -15k Ohm (and 1 when measuring the other way round, i.e., as if there were no connection at all). Switching wires also exactly switches the measurement, i.e., I never obtain any positive resistance measurement.

What can go wrong here? What else can I try to find out what's wrong? Thank you!

First of all there’s no negative resistance, resistance is a positive only measure, from 0 to infinity.

My best guess is you have your optocoupler the other way around, so you are measuring the input rather than the output: is that possible?


Stepper Motor with Limit Switches I have the code below which is my attempt to control a stepper motor direction that moves a carriage to the right and left. In addition there are limits at each end of the travel that when activated stops movement in the respected direction. My problem is that the motor works just fine in the left and right directions but I can only get one of the limit switches to work. I'd appreciate any suggestions.

int PUL = 7; //define Pulse pin
int DIR = 6; //define Direction pin
int ENA = 5; //define Enable Pin
int RGT = 3;
int LFT = 2;
int potPin = A5;
int count = 0;
int interval = 1000;
int val = 0;
int Spd = 500;

#define Limit01 8  // Pin 2 connected to Limit switch out
#define Limit02 9  // Pin 3 connected to Limit switch out

void setup() {
  pinMode (PUL, OUTPUT);
  pinMode (DIR, OUTPUT);
  pinMode (ENA, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if (digitalRead(LFT) == LOW) {  //  If joystick is moved Left
    if (digitalRead(Limit01) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor clockwise

      digitalWrite(DIR, LOW);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);
    }
  }

  if (digitalRead(RGT) == LOW) { // If joystick is moved right

    if (digitalRead(Limit02) == HIGH) {} // check if limit switch is activated

    else {  //  if limit switch is not activated, move motor counter clockwise

      digitalWrite(DIR, HIGH);
      digitalWrite(ENA, HIGH);
      digitalWrite(PUL, HIGH);
      delayMicroseconds(500);
      digitalWrite(PUL, LOW);
      delayMicroseconds(500);

    }
  }
}

What I understood from your question is you want only one limit switch to control the stepper motor in both directions.So here is the code that might be helpful for you in that case:

int dirpin_T1 = 2;
int dirH_T1 = 3;
int steppin_T1 = 4;
int limit = 10; // ASSUME LIMIT-SWITCH IS PLACED AT RIGHT CORNER
void setup() {
  pinMode(limit,INPUT);

  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);

}

void loop() { //STEPPER TRAVELLING LEFT TO RIGHT

    digitalWrite(dirpin_T1, LOW );
    digitalWrite(dirH_T1, LOW);
   do
   {
      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);

   }(digitalRead(limit)==HIGH); //AS LIMIT-SWITCH PRESSED MOTOR STOPS
  delay(500);
  //WHEN LIMIT-SWITCH IS LOW CHANGE THE DIRECTION OF MOTOR ROTATION
  if(digitalRead(limit)==LOW)
  {
      digitalWrite(dirpin_T1, LOW ); //CHANGE MOTOR DIRECTION (LOW TO HIGH)
      digitalWrite(dirH_T1, HIGH);
     for(int i=0; i<36000;i++)
      { //please try changing value of i as it depends on how much rotations you want your motor to step forward

      digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(50);
     }

  }
}

The simple logic would be to move the motor in one direction until limit-switch is HIGH. And to move it to the other direction when its LOW i.e already pressed.Correct me if I am wrong and try modifying the code as per this logic.However you need to change your code depending upon what type of driver you are using. Right now I am using TB6560 driver.You can use if loop instead of do while loop to make it easier to understand.


a code to implement a simple traffic signal and also display on LCD which color is ON? I have tried code given below for simple traffic signal and also display on LCD which color is ON, but it didn't work. Please me to make it work.

int red = 10;
int yellow = 9;
int green = 8;
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup(){
    pinMode(red, OUTPUT);
    pinMode(yellow, OUTPUT);
    pinMode(green, OUTPUT);
}

void loop(){
    changeLights();
    delay(1500);
}

void changeLights(){
    lcd.print("red");
    digitalWrite(yellow,LOW );
    digitalWrite(red, HIGH);
    digitalWrite(green,LOW );
    delay(3000);
    lcd.print("yellow");
    digitalWrite(yellow,HIGH );
    digitalWrite(red,LOW );
    digitalWrite(green,LOW );
    delay(3000);
    lcd.print("green");
    digitalWrite(yellow,LOW );
    digitalWrite(red,LOW );
    digitalWrite(green,HIGH );
    delay(3000);
    //if(
}

Write a sketch to test your LCD.

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 4, 2);
void setup(){
    lcd.begin();
    lcd.print("Hello World!");
}
void loop() {
    lcd.setCursor(0, 1);
    lcd.print(millis() / 1000);
}

Make sure the R/W pin is connected to GND on your breadboard. You may need to connect the contrast pin to 5V. Ideally it should be connected to the wiper of a 10KOhm trimpot with either end connected to GND & 5V (so you can vary the contrast).

Once that set-up works change your code

 void setup(){
     lcd.begin();
     lcd.print("Traffic signals");
     delay(500);
     pinMode(red, OUTPUT);
     pinMode(yellow, OUTPUT);
     pinMode(green, OUTPUT);
 }

 void loop(){
     changeLights();
     lcd.setCursor(0,0);
 }


communicating with arduino over serial via terminal I'm attempting to write data over a serial line to the arduino, however I don't want to use the arduino IDE but rather use the command line.

In order to do this I have the following commands:

$stty -F /dev/ttyACM0 cs8 9600 ignbrk -brkint -imaxbel -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke noflsh -ixon -crtscts
$echo s123 > /dev/ttyACM0

The code on the receiving end checks whatever or not the input is s123 and if it is starts blinking. I have tested this using the arduino IDE and it worked, however this did not work.

The sketch looks like this:

    void loop(){
     if(Serial.available()==4){
       byte b1,b2,b3,b4;
      b1=Serial.read();
      b2=Serial.read();
      b3=Serial.read();
      b4=Serial.read();
        if(b1=='s'){
               digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
               delay(1000);               // wait for a second
               digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
               delay(1000);               // wait for a second
               digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
               Serial.println("the cow has landed");
          }
     }

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

the output of

stty -F /dev/ttyACM0 -a

was :

speed 9600 baud; rows 0; columns 0; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>; eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R; werase = ^W;
lnext = ^V; flush = ^O; min = 0; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread clocal -crtscts
ignbrk -brkint -ignpar -parmrk inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -iutf8
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
-isig -icanon -iexten -echo -echoe -echok -echonl noflsh -xcase -tostop -echoprt -echoctl -echoke

Thank you

This was fixed this morning after a reboot and upgrade command, still don't know which one of these fixed it but it seems to work now.

Ah figured it out we were using the 0 and 1 rx gates to communicate over serial rather then usb and as the used power supply turned out to be only 5V rather then 9-12V it didn't quite work as intended.


Dynamic allocation/ Pointer to Pointer to update an Array containing parameter topicArray defined as follows:

const char* msgTopic = "Home/Messages";
const char* groupTopic = "Home/All";
char* deviceName = deviceTopic;
const char* topicArry[2] = {deviceTopic, groupTopic};

But deviceTopic can be changed during code run, and I wish that topicArray containg deviceTopic will have the correct value after deviceTopic has changed.

What is the right way doing so ?

You may try something like this:

const char* topicArry[2] = {NULL, groupTopic};
const char** const pDeviceTopic = &topicArry[0];
#define deviceTopic (*pDeviceTopic)

Arguably not very elegant, but now when you assign, e.g.

deviceTopic = msgTopic;

you are actually writing into topicArry[0].


Measure current and consumption I'm trying to measure kWh with an Arduino that I have connected to a ESP8266 that communicates this value to a web server I have. And I've been trying to find the best and easiest way to go about this.

I'm thinking that I can hook a PMAC903 up to the Arduino using the interrupt pins and measuring the pulses, but I don't really know how I'm supposed to do that? Will it even work? Is this the way it's normally done? I can't really say I've found an easy solution to measure current.

You can find documentation for the PMAC903 here and I'm currently in possession of an Arduino Uno that I'm using.

The state of this meter can be read in 3 ways:

Pulse, this is very easy to implement. But depending on the stability of the hardware u can miss pulses leading to inaccurate values. In this way u have to calculate the meter value yourself.
RS485, this is a communication bus not default on arduino. But given this link https://arduino-info.wikispaces.com/RS485-Modules i think it is doable but not easy. This will read the value from the meter.
M-Bus: There is special hardware needed to interact with it. This is the industry standard of doing it. It's not cheap. But u can link many meters together. This will read the value from the meter.

Depending on your time/knowledge/other requirements u have to make a chose what way your going to use.