Trying to switch a 5v fan with a LiPo and can't figure our what's wrong at full duty cycle I have a simple project where I want to turn a 5v fan on/off and both the MCU  and fan will powered by a LiPo battery.
I'm powering the ESP and fan directly from the battery in the attached circuit. For now I've decided not to boost the power to 5v for the fan because the fan runs fine at lower voltage. Also using a BJT transistor as a low side switch.
This all seems to work fine except at full duty cycle the voltage to the fan seems to completely collapse. At just below full (like if a do analogWrite(pin 1000) it's humming along fine but when I go to 1023 the voltage drops from around 4 to closer to 2 and the fan stops. Even at lower duty cycles like 50% the fan operates nice and slow.
I put a multimeter on the leads to the fan and observe the voltage drop at full duty.
I'm very new to all this and have done a lot of reading but I haven't been able to solve this. Also this is my first fritzing drawing so I hope it makes sense.
Edit: I made some changes to the circuit and it's working as expected. I have also updated the circuit diagram below.

According to specs I found online, the NodeMCU wants 7-12V on Vin. Most LiPo cells put out around 4 volts, which isn't enough. The battery voltage may drop and the MCU's voltage regulator probably fails to keep putting out 3.3V when the fan's average power draw exceeds some threshold.

It might also be that the fan itself is slowing when the duty cycle approaches 100% and the battery voltage drops.

Doesn't the NodeMCU run on 3.3V, not 5V? If you feed 5V into the 3V pin and that's supposed to have 3.3V, it will likely damage or destroy the board.


Stepper not working properly using L298N If googled and search here but can't find the same issue.
I'm using an Arduino Uno, L298N driver (5v jumper is off - actually just 2 holes where the jumper pins were supposed to be), scavenge stepper motor from a 5 inch drive - TEAC P.no. 14769070-90 (we call it a floppy drive). I used the example from the Arduino IDE that spins the stepper in on direction and then the other.
The stepper motor has a 5 wire ribbon and with an LED test showed that the out side two wires are a pair. I've look at schematics for the 5 wire, I know it's got to do with the uni/bi polar of the motor but I have no idea if I need to connect this middle wire?
I've wired it according to this Maker Guides article
The issue is that in the clockwise direction it is very weak and it just vibrates in the anti-clockwise direction.
How do I go about diagnosing the issue?
(I'm on a beginner level with regards to hw. Sw engineer with a Solder iron - very dangerous)

The motor you got is a unipolar stepper motor. The five wires are one end of the four windings inside the motor, plus a common wire that connects all the other poles together.
Bipolar motor offer more torque than unipolar, at the expense of a more difficult control. 6 wires unipolar stepper motors can be converted to bipolar motors just selecting the correct wires. I am not aware of any method to convert a 5 wires unipolar motor to bipolar that does not imply tearing it apart (which is not really a great idea).
The L298 is not really made to drive this kind of motor, it is best suited to drive bipolar motors (can still drive it tho, please read the next paragraph). Good news, driving unipolar steppers is rather simple. You basically have to connect the common wire to you V+ rail and connect the other wires to GND via BJT/MOS. Don't connect them directly to the Arduino! It's the perfect recipe for fried chips. You can either choose to use discrete transistors or arrays like the ULN2003.
If you still want to use the L298 to drive the motor you can exploit the lower transistors of the H-bridge. Connect Vss and the enable pins to 5V, Vs to your positive rail voltage and pin 1, 8, 15 to GND. Then connect each phase to each output and the input to 4 pins to an Arduino/microcontroller. Leave the pins normally on and turn one off in turn (1->2->3->4->1...) and your stepper should run! This works because when you leave the pins on, the upper side of the H-bridge is powered on, thus shorting the winding. When you turn one pin off the lower part of the bridge will actually turn on and let the current flow to GND, closing the circuit and powering the winding. Using this kind of circuit you could also omit the freewheeling diodes needed to discharge the windings (as said before, you short them, allowing current to freely circulate).
EDIT/TLDR: Connect the windings to the output of the L298 and the common one to the positive rail. Keep the pins high and turn one sequentially off, you should see the motor move.


Combing two codes to make it work on the same time but not affecting the other code? I am trying to make a game where there are arrows going towards an object (in this case I printed x) and you have to evade the arrows. When you press the button it is supposed to print x on the top row and clear the bottom row with printing nothing and if you don't press the button its supposed to print x on the bottom row and nothing on the top. Then the for loop is supposed to print arrows randomly going from right to left.

Problem: When I actually run the code I only see the x every time the arrow hits the (0,1) or (0,0) position.

I want the x to be there all the time.

#include <LiquidCrystal.h>
// init the lcd display according to the circuit
LiquidCrystal lcd(12, 11, 6, 5, 4, 3);

String line2 = " x ";
int xPosition;
int yPosition;
int yConstant;

void setup()  {
  lcd.begin(16, 2);
  // put your setup code here, to run once:
  int switchState = 0;
  pinMode(7, INPUT);
  int leftjump = 0;
  pinMode(8, INPUT);
}

void loop() {
  ///////////////////////////////
  //supose tp print arrow randomly going from right to left
  xPosition = 15;
  yPosition = random(0, 10);
  if (yPosition > 5) {
    yConstant = 1;
  }
  else yConstant = 0;
  lcd.setCursor(xPosition, yConstant);
  for (int xPosition = 15; xPosition > 1; xPosition--) {
    lcd.print("<-");
    delay(100);
    lcd.clear();
    lcd.setCursor((xPosition), yConstant);
  }
  ////////////////////////////
  // suppose to print x on the top row and print nothing on buttom row
  //and otherwise when button is not pressed print x on bottom and
  //print nothing on top row
  int rightjump = 0;
  rightjump = digitalRead(7);
  if (rightjump == 1 ) {
    lcd.setCursor(0, 0);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 1);
    lcd.print("  ");
  }
  else if ( rightjump == 0 ) {
    lcd.setCursor(0, 1);
    //delay(10);
    lcd.print(line2);
    //delay(200);
    lcd.setCursor(0, 0);
    lcd.print("  ");
  }
}

Combing two codes to make it work on the same time but not effecting the other code?

the simplest would be to have two arduino and run each piece on one of them.


Raspberry Pi Outputting Signal to arduino I have been trying to get my raspberry pi to output a signal of High or Low, which is then picked up by digital pin 4 on my arduino.

On the raspberry pi, I have connected the output to GPIO 24 and have set up a simple to circuit with an led and 220 ohm resistor in series to check if there was any output. I did manage to get the led to turn on and off due to typing commands into the console on the raspberry pi, so that can't be the problem.

For the raspberry pi side of things, I have installed the WiringPi library and typed these commands:

gpio -g mode 24 out

This set up the GPIO pin and then to turn them off, I used these independently.

gpio -g write 24 1
gpio -g write 24 0

For my code on my arduino, I have adapted a rtc with stepper motor piece of code that I am working on to go with this sub project.

#include <DS3231.h>
#include <Stepper.h>

//---( Number of steps per revolution of INTERNAL motor in 4-step mode )---
#define STEPS_PER_MOTOR_REVOLUTION 32

//---( Steps per OUTPUT SHAFT of gear reduction )---
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 64  // 2048

// Init the stepper object with sequence 1-3-2-4 for proper sequencing
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);

// Init the DS3231 using the hardware interface
DS3231 rtc(SDA, SCL);

const int raspiPin = 4;
int raspiSwitch = 0;

int  Steps2Take;

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  pinMode(raspiPin, INPUT);

  // Initialize the rtc object
  rtc.begin();

  // The following lines can be uncommented to set the date and time
  // rtc.setDOW(SATURDAY);     // Set Day-of-Week to SUNDAY
  // rtc.setTime(22, 32, 50);     // Set the time to 12:00:00 (24hr format)
  // rtc.setDate(3, 6, 2017);   // Set the date to January 1st, 2014
}

void loop()
{
  // Read the state from the raspi
  raspiSwitch = digitalRead(raspiPin);

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Declare variable for later testing against
  String myTime = rtc.getTimeStr();

  if (myTime == "17:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (myTime == "08:00:00") {

    Serial.println("Rotating stepper motor at " + myTime + ".");

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  } else if (raspiSwitch == 1) {

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

    Steps2Take  =  STEPS_PER_OUTPUT_REVOLUTION / 2;  // Rotate CW 1 turn
    small_stepper.setSpeed(500);
    small_stepper.step(Steps2Take);
    delay(1000);

  }

  delay (1000);

}

When I use the else if statement to turn the stepper motor if there is a high signal from the raspiPin, the motor will turn even when the signal is low.

I used Serial.println to output the state of the raspiSwitch variable to the serial output and for some reason, it changes by itself between 1 and 0. I do not know why and would like to resolve this so I can move onto the next stage of connecting it to the internet on a php webpage.

If anyone could help, I would greatly appreciated it

The Arduino and the Raspberry pi should have a common ground. Connect the ground pin of the Arduino to the Raspberry pi. Both boards should be powered by the same power source and connect a pull-down resistor from the digital pin of the Arduino to ground. about 10Kohms might be enough.


Correct solution for "multiple definition of" compile error I'm in the process of trying to take this demo sketch and extract the necessary bits into a modular library that can be included in other sketches.

Here's where I'm at so far.

Here's the test sketch that I'm including it in.

However, when I try to compile it right now, I'm getting...

libraries/Adafruit_CC3000_Dynamodb/sha256.cpp.o: In function `Sha256Class::init()':
/home/me/sketchbook/libraries/Adafruit_CC3000_Dynamodb/sha256.cpp:33: multiple definition of `Sha256Class::init()'
sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here

I've been programming for years in other languages, but I'm not all that experienced in C. I'm sure I'm doing something completely stupid, but I can't figure out what it is.

I'm also aware that this code still needs a lot of cleanup work in general. Right now I'm just trying to work toward a basic MVP that works so that I start gradually cleaning things up and making it more OOP one step at a time.

You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.

It is probably a bug in the IDE that doesn't remove the old files.

Restarting the IDE will cure the problem and allow you to compile.


Unfamiliar error on code about port(s) here is the code:

#include "DHT.h"
#include "NewPing.h"
#define DHTPIN 7
#define DHTTYPE DHT22
#define TRIGGER_PIN  10
#define ECHO_PIN     10
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float hum;
float temp;
float duration;
float distance;
float soundsp;
float soundcm;
int iterations = 5;

DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin (9600);
dht.begin();
}
void loop()
{
delay(2000);

hum = dht.readHumidity();
temp= dht.readTemperature();
soundcm = soundsp / 10000;
duration = sonar.ping_median(iterations);

Serial.print("Sound: ");
Serial.print(soundsp);
Serial.print(" m/s, ");
Serial.print("Humid: ");
Serial.print(hum);
Serial.print(" %, Temp: ");
Serial.print(temp);
Serial.print(" C, ");
Serial.print("Distance: ");

if (distance >= 400 || distance <= 2) {
Serial.print("Out of range");
}
else {
Serial.print(distance);
Serial.print(" cm");
delay(500);
}

Serial.println(" ");
}

here is the error:

Arduino: 1.8.7 (Windows 7), Board:
"Arduino/Genuino Uno"

Sketch uses 6156 bytes (19%) of program storage
space. Maximum is 32256 bytes.
Global variables use 326 bytes (15%) of dynamic
memory, leaving 1722 bytes for local variables.
Maximum is 2048 bytes.
Please select a Port before Upload

In the Arduino IDE you need to select which port COM port the Uno is connected to.


How can I reset the program on an Arduino Uno while the device isn't recognised by my computer at all? So I've recently been playing around with my arduino uno, and today it completely refuses to communicate with my computer at all. I've tried using other cables, switched OS (Tried Windows 8.1 and Ubuntu 14.04), and tried on my laptop, none of them recognise the device at all.

From what I've read, this problem can be caused my a program on it with a Serial.println() frequently used, which I believe is the case here. The solution for this problem is according to other answers, to hold the reset button while I upload an empty sketch to the arduino. However, I can't do this, since the computer doesn't communicate with the arduino at all.

Any ideas what could've gone wrong, and how to fix it?

EDIT: Alright, the problem seems to have resolved itself... I have no idea what made it work, I was frustrated and went to bed last night, and today it works without an issue..

EDIT #2: Scratch that.. now I get this error when I try to upload a program to the arduino:

avrdude stk500_getsync() not in sync resp=0x00

The device does show up in Device Manager, so I tried installing the arduino drivers for it, but it gives me the error code 10. Windows automatically installs some serial driver for it, but any attempts of serial communication with the arduino fails.

I had the same problem with my Arduino Leonardo. But when I kept the reset button pressed and plugged it into my laptop, it got recognised again. But since you're using an arduino uno it might also be the atmega16u2 which isn't working properly. If holding the reset button while plugging in the arduino to the laptop doesn't work, try to reset your atmega16u2 chip on the arduino. This is the chip which makes the communication from USB possible.

To reset the atmega16u2 follow this tutorial


Read from lux hangs in bright light I am using VMEL6040 sensors and occasionally under bright light the read can hang, rather than using a wdt to recover I would like to ask some questions about the library.
as for debugging the sensors run stabley (several days at reads every 250 ms) in low light, but over 6k lux they can crash.
I am using wire.h here
in the header
TwoWire *_i2cPort;

the read value calls the ReadRegister function:
uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
{

  uint16_t _regValue;

  _i2cPort->beginTransmission(_address);
  _i2cPort->write(_reg); // Moves pointer to register.
  _i2cPort->endTransmission(false); // 'False' here sends a restart message so that bus is not released
  _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
  _regValue = _i2cPort->read(); // LSB
  _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
  return(_regValue);

}

is there a reason they are not checking the return of the _i2cPort->endTransmission(false);call? I am wondering if I should check that and not call the requestFrom if it does, i.e.:
uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
{

  uint16_t _regValue;

  _i2cPort->beginTransmission(_address);
  _i2cPort->write(_reg); // Moves pointer to register.
  if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released
      _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
      _regValue = _i2cPort->read(); // LSB
      _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
      return(_regValue);
  }
  else
      return 0;
}

Or could my error be from the static casting do int?

so I think I got it, the problem was that on a fail wire.read() returns an int -1
when that gets converted to a unint16 its a big number then it gets left shifted and overflows
the solution was:
uint16_t SparkFun_Ambient_Light::_readRegisterLight(uint8_t _reg)
{
    int lsb;
    int msb;

    _i2cPort->beginTransmission(_address);
    _i2cPort->write(_reg); // Moves pointer to register.
    if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released

        unsigned long tstamp = millis();
        while ((_i2cPort->available() < 2) && ((millis() - tstamp) < 10));

        if ((_i2cPort->available() < 2)) {
            _i2cPort->requestFrom(_address, 2); // Two reads for 16 bit registers
            lsb = _i2cPort->read(); // LSB
            msb = _i2cPort->read(); //MSB

            if ((lsb >= 0) && (lsb <= 256) && (msb >= 0) && (msb <= 256)) {
                _regValue = lsb + msb * 256;
            }
        }

        return(_regValue);
    }
    else
        return _regValue;//last read
}

This contains some extra error handling I added, but will leave in such as:

timeout on waiting for a response
checking on properly closing the bus in end transmission
checking for errors from the read

I didn't do error handling as I would need to rewrite the whole library, and for my application repeating the last reading is sufficient.


Segmentation fault at Serial.begin() I try to communicate with my Arduino clone (Elegoo Uno R3) from Arduino IDE (v1.8.4 installed by dnf from repos) at Fedora 27. Compiling and upload of normal example code works well. However, as I try to start any serial communication (e.g. for debug), the compiler fails returning following segfault:

"/usr/bin/avr-gcc"  -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_407070/AnalogReadSerial.ino.elf" "/tmp/arduino_build_407070/sketch/AnalogReadSerial.ino.cpp.o" "/tmp/arduino_build_407070/../arduino_cache_983152/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a" "-L/tmp/arduino_build_407070" -lm
lto1: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://bugzilla.redhat.com/> for instructions.
lto-wrapper: fatal error: /usr/bin/avr-gcc returned 1 exit status
compilation terminated.
/usr/lib/gcc/avr/6.3.0/../../../../avr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.

I found similar issue here https://github.com/sudar/Arduino-Makefile/issues/486 However, that solution deals with Arduino-Makefile software that is little bit complex for me.

I would appreciate any help either how to solve the segfault itself, or how to easily use Arduino-Makefile (I would like to compile from Arduino IDE or any user-friendly IDE).

There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)


I/O expander with i2c interface vs Multiplexer I am wondering where are the difference in between using something like:
CD4067, which selects which pins to read/write from by "selecting" an address with 4 pins by writing to it. Versus the MCP23017 which uses the i2c interface.

I am trying to learn and build a simple application with lots of digital inputs and outputs, and need something that is fast at switching the pins and reading/writing to it.

The MCP23017 gives you 16 extra real IO pins. Each one has facilities such as pull-up resistors, change notification interrupts, etc - the kind of things that you expect from real IO pins. You can read and write to all of the pins.

A multiplexer though just feeds signals through to the existing pins. They're pretty dumb. Only the signal that is currently fed through can have anything done to it. So only one signal can have a value written on it or read from, and pullup resistors and interrupts are non-existent.

However the CD4067 can be used with signals other than digital - as such they are good at being a multiplexer to the analog inputs, something an IO expander can never do. You could, though, use an I2C ADC chip for that.

For high speed IO control you really want to be using the MCP23S17 instead of the MCP23017. It uses SPI instead of I2C and thus is much faster to control.


Shift register on Attiny85 programmed by Arduino Shift registers need 3 digital pins in order to work (data, clock and latch), but Attiny45/85 chips provides 2 digital and 2 analog pins.

Would I use 1 analog pin as digital pin? How?

The ATtinyX5 does not have any analog-only pins; all 5 pins are usable as digital I/O (all 6 if you know what you're doing, but if you need to ask how then you're not ready to do so).


Smooth breathing led I am trying to make a simple breathing led circuit in which the intensity of the led varies between 0 and 255. I followed the Fade tutorial on the Arduino site, which gives me what I want, but I notice that the change in brightness is much more noticeable when the intensity is at 0.

In other words, the brightness seems to be bouncing back from 0, rather than slowly gliding back up.

I tried mapping the value of the delay to brightness: del = map(brightness, 0, 255, 10, 1); but that did not do the job.

The mapping seems to work better when I use 30 instead of 10 as longest delay time:  del = map(brightness, 0, 255, 30, 1); but I think what I really need is to implement some sort of sinusoidal function to make transitions smoother, but I am really struggling with the math... Any suggestions?

Here is the code:

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 1;    // how many points to fade the LED by
int del;

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }

  // here I map the delay to brightness
  del = map(brightness, 0, 255, 10, 1);

  delay(del);
}

There's two ways you could algorithmically do what you want, both with different results.

The first is with a sinewave:

for (int i = 0; i < 360; i++) {
    analogWrite(5, (sin(i * 0.0174533) + 1) * 127));
    delay(3);
}

Basically you work your way 360 degrees around a circle and take one axis (e.g., the vertical one), offset it so that the values are all positive (sin gives a value between -1 and +1), then multiply it to fit the full brightness.

This is the smoothest way of fading an LED, but it doesn't respect the different sensitivities your eye has to the different brightnesses (you see more brightness variation when it's dim compared to when it's bright).

The other method is much cruder but does respect those differences in sensitivities. This specific method only gives you 8 brightnesses as opposed to 256, but they are on a log2 curve:

for (int i = 0; i < 9; i++) {
    int v = (1 << i) - 1;
    analogWrite(5, v);
    delay(100);
}
for (int i = 7; i > 0; i--) {
    int v = (1 << i) - 1;
    analogWrite(5, v);
    delay(100);
}

The theory of this one is it uses bit-shifting to gradually fill a byte with 1 from the least significant bit upwards.

When i is 0, this formula:

int v = (i << i) - 1;

gives:

1 << 0 == 0b00000001
0b00000001 - 1 = 0b00000000

If i is 4, you get:

1 << 4 == 0b00010000
0b00010000 - 1 = 0b00001111

So you effectively end up with a set of values:

0: 0
1: 1
2: 3
3: 7
4: 15
5: 31
6: 63
7: 127
8: 255


Is a variable declaration inside a loop static declaration or dynamic? while(condition){
    Object object = new Object();
}

So my question is, will each iteration would create a different object in different memory location or it will overwrite the once created object every iteration.

It will be created every iteration.

Assuming, you are not using it to add to a list (e.g. to use in later loops), what you better can do is make it in a global, you also don't need to use 'new', thus:

Object object;

Also, if you do not delete/remove the object at the end of each while condition (with the delete keyword), you will lose the memory (and this is a memory leak). Also, you run the risk of memory shortage (the Uno has only a few KB of memory).

What I also miss in your code is the pointer (*, because the new keyword creates a pointer), and also Obj and Object are inconsistent types (they should be equal), so:

Object* object = new Object();

If you only need the object within the condition and it can be removed in the next while, than you don't need to use new, so just declare it as a vaiable

Object object;

This also has the benefit that the (local) variable will be destroyed at the end of scope (which is at the end of the while).


How to calculate voltage from A0 pin I would like to calculate the amount of voltage from my A0 pin. I am using a 9v battery to power my load in my circuit. The formula to calculate voltage from the A0 pin is:

    sens = analogRead(A0);
    vol = sens * ( 5.0 / 1023.0);

If my power source is 9v, should i replace the 5.0 to 9.0?

The analog input pins are 0V-5V strictly. If you need to measure a 9V input, you need to scale the voltage to test so that it is within a 0V-5V range. Often this is done with a voltage divider circuit.

In the example below, the 9V test voltage is divided in half, so the scale is 0V-4.5V, which is within range of the input pin.

Then your algorithm is

vol = sens * (2.0) * ( 5.0 / 1024.0);

simulate this circuit – Schematic created using CircuitLab


String(int) function stopping the Arduino Well I am trying make an application with arduino leonardo and GSM Shield. There are conditions if, else if, else .. etc
  if (smsMetni.indexOf("DURUM") != -1) {
    Serial.println("SMS income");
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";
    char tempSMS2[] = "";
    temp2.toCharArray(tempSMS2, 30);
    Serial.println(tempSMS2);
    Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);
  }

After the last line "Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);" program stopping I watching serial monitor there is no notification or error. just stopping.
If I change those lines and remove String(analogRead(LM35_pin) * 0.48828125) :
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";

and just write like this, it works very well.
String temp2 = "Hava  derece.";

maybe you think there is a problem with LM35, even if I change it String(analogRead(LM35_pin) * 0.48828125); with String(30);, it doesn't work again. after the last line it is not continue.
only one sollution I've found if add delay(500) after each line it works but my codes looks ugly with this. are there any solution.

You should avoid String on the Arduino. It will cause random crashes. However that's not your issue. Your issue is trying to copy the data into an array that is too small.
char tempSMS2[] = "";

That creates a one byte array which contains just a \0. You then try and squeeze your String data into it and it of course overflows all over the rest of your variables and data.
A better solution is to work directly in char arrays. It is a little trickier though:
First convert your float to a string:
char tempFloat[8];
dtostrf(analogRead(LM35_pin) * 0.48828125, -7, 3, tempFloat);

Then build up your string:
char tempSMS2[30];
strcpy_P(tempSMS2, PSTR("Hava "));
strcat(tempSMS2, tempFloat);
strcat_P(tempSMS2, PSTR(" derece."));


cu port always busy on Mac I'm going bonkers here. I'm using a Macbook Pro with Yosemite. Connected to the MKS Gen-2Z V1.1 reprap board (ATmega 2560).

The Arduino IDE only shows the cu port being available and not the tty.

Any attempts at opening the CU port show it as being busy. This is also true when I open the port using PronterFace (3d printer software). Yet, the PronterFace shows the tty port and gladly opens it and communicates. I downloaded Arduino 1.0.6 and the tty is available in the dropdown menu and it will open the port. But my 3D printer firmware will fail building on any Arduino IDEs prior to 1.6.0.

I found a few suggestions on creating a file "lock" in /var/ and then changing the r/w permissions. Also doing the same for /var/spool/uucp. Changing both of those permissions did nothing for me.

I may just have to build it and use AVRdude directly so I can use the tty port, but I have no idea why the cu would be busy all the time. Any suggestions?

Here's the Arduino output when I try to upload:

  avrdude: ser_open(): can't open device "/dev/cu.usbserial-AL00YS9R": Resource busy
      ioctl("TIOCMGET"): Inappropriate ioctl for device
      ioctl("TIOCMGET"): Inappropriate ioctl for device
      avrdude: ser_send(): write error: Bad file descriptor
      Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

Can't you see what's hooking the serial port with sudo lsof -n | grep cuaU0 ? If so, sudo kill -9 12345, where 12345 is the offending PID. Your FTDI chip may need a driver, try sudo dmesg after pluggibg it in, or use systemprofiler.


Pixel font resources in byte format To write text on a dot-matrix or LC display with an Arduino you need to have a pixel font in byte format (i.e. typically 1 bit = 1 pixel).
On the Internet I have found surprisingly few resources for this.

Most of the results when searching for pixel fonts return true-type fonts (or similar) which are rather complicated to convert to obtain a satisfying result.
Also, most of the fonts are rather high resolution.
Any good resources I have missed?

The UTFT library has a SmallFont which is 8x12. Not sure whether this is too big for you, but it could be worth looking into. It is ASCII only, so you might want to add some characters yourself. But as someone mentioned, memory is limited, so add sparingly.


Sensor for turning rail direction I am trying to control an actuator carrying a carriage made from stepper motor. My problem is that after the carriage reach certain height, I want it to delay for several minutes and change direction to move the other way around.

Any suggestion on what sensor to use? I tried to use EndStop switch like the one in 3D printer but I haven't found any luck as it simply cuts the electronic connections once the carriage hits it.

If you are using a microprocessor, specifically an Arduino, then what you need to do is send the signal from the 'switch' (as defined by Mark Smith) into a digital input port and then let the Arduino make the electronics pause before reversing.  From you post it sounds like (and I am probably wrong) you have put the switch in between the power source and the actuator.

(Diagram by Majenko)


Using time function in arduino how to get exact timestamp of a sensor reading and compare it with other sensor values in arduino?

Ex: Get the time of low reading of LDR and compare it

As Majenko said you can use the millis() keyword.

Unless millis is not accurate enough. In that case you can use micros(), but this overflows every 70s if I'm correct, but you can offset it against millis().

If you need to compare two values, what you can do is:

get millis()
get micros()
read sensor data (optimize if needed)
get micros()

Average the difference of the micros, and add it to millis, and you have the average time for the sensor data readings.

Of course if it doesn't matter that all sensor data is read at approximately the same time, you can use millis() for each sensor data reading and work with those values.


for loop iterated only once I have written a little project, it works so far as it should but the for loop is only iterated once, then the result is displayed on the LCD.

#include <LiquidCrystal.h>
#include <stdlib.h>
const int Contrast=20;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int led = A5;
const int button = A3;

void setup() {
  Serial.begin(9600);
analogWrite(6,Contrast);
lcd.begin(16, 2);

pinMode(led, OUTPUT);
digitalWrite(led,LOW);
pinMode(button, INPUT_PULLUP);
}

void loop() {

unsigned long mittelwert = 0;

for(int i=0; i<10; i++){
  unsigned long r = random(1,5000);
  unsigned long now = millis();

  digitalWrite(led,HIGH);

  while (digitalRead(button) == HIGH){
    lcd.setCursor(0,0);
    lcd.print("druecken");
  }
  mittelwert = mittelwert + millis() - now;
  digitalWrite(led, LOW);  //LED aus

}

lcd.clear();
lcd.setCursor(0,0); //setze Cursor auf 1.Stelle in der 1. Zeile
lcd.print(mittelwert/1000);
lcd.setCursor(0,1);
lcd.print("Sekunden");

delay(5000);
lcd.clear();

}

Your button is configured as an input with a pullup.  Therefore, except when the button is depressed to ground that input, this nested loop

while (digitalRead(button) == HIGH){
   lcd.setCursor(0,0);
   lcd.print("druecken");
}

will endlessly repeat, preventing execution from advancing.

Given that your question fails to state what you are hoping to accomplish it's not possible to make any corrective recommendations.  If you do want to make use of the button, you should probably first search and read the existing questions here having to do with debouncing.


Generating digital positive (+5 V) and negative (-5 V) signal? Problem in getting -5 V with Arduino.

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

void loop() {
  digitalWrite(13, HIGH);
  delay(20);
  digitalWrite(13, LOW);
  delay(20);
}

Above code is generating below digital signal:

I want this type of digital signal output:

I read this for generating negative -5 V signal:

https://electronics.stackexchange.com/questions/10322/what-is-negative-voltage

but not able to understand very well WRT Arduino.

Also read this:

Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?

seems to much complicated circuit diagram with TL802.

My questions:

How do I get above digital signal?
I was wondering if we can use some 1 microF capacitor or transistor to generate negative signal? (simplest way)

It is not so easy to create a -5v power supply using a capacitor or transistor.

A very easy way is to use an additional Wall wart power supply to create -5 volts (while still using your original +5 volt power supply).

For the additional (new -5 volts power supply), use the two wires (positive and negative to create your -5 volts).   The positive lead goes to your board ground, and the negative lead becomes your -5 volts.

EDIT 1  :   Make certain that the Wall wart that you use is isolated from the mains voltage (line voltage you plug it into).  Most Wall warts are isolated,  but check to be sure.

Then you need level translation, which can be done with an op-amp and a couple of resistors  :

You have not mentioned what frequency (data rate) you need.  This circuit is not fast, so for high frequency or high data rates, the circuit could be improved.


Read/write data from 2 Arduinos simultaneously with Python So for my project I have one Arduino Mega hooked up with a quadrature rotary encoder which is connected to the computer. An Arduino Uno is connected to a circuit I built, which in turn is connected to a valve and a touch connector (also connected to the computer via USB). Both of them should be controlled with a Python script.

If the rotary encoder is moved, I can read out a value via the serial port. The value of the rotary encoder is used in Python to move a dot on the screen. If the dot on the screen reaches a certain point, I want to give a signal to the valve to open (something like pin.write(1) to turn on or pin.write(0) to turn it off). At the same time I want to be able to detect the touch sensor if the circuit is closed.

The issue is now that I need to somehow need to read the rotary encoder, process the data and send it to the valve, as well as reading the touch sensor simultaneously. So far I have not found a way how to achieve this as my code does not function.

At the moment I have custom code on My Arduino Mega and a StandardFirmata on the Arduino Uno, but I am open to other suggestions that could work.

Arduino Mega code:

/*
by Ben-Tommy Eriksen
https://github.com/BenTommyE/BenRotaryEncoder
*/

// Encoder connect to digital pin 2 and 3 on the Arduino.

int counter = 0;
//This variable will increase or decrease depending on the rotation of encoder

void setup() {
  Serial.begin (4600);
  //Setting up interrupt
  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
  attachInterrupt(0, ai0, RISING);
  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
  attachInterrupt(1, ai1, RISING);
}

void loop() {
  // Send the value of counter
  Serial.println (counter);
}

void ai0() {
  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
  // Check pin 3 to determine the direction
  if(digitalRead(3)==LOW) {
    counter++;
  } else {
    counter--;
  }
}

void ai1() {
  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
  // Check with pin 2 to determine the direction
  if(digitalRead(2)==LOW) {
    counter--;
  } else {
    counter++;
  }
}

Python code:

import pyfirmata
import serial
import time

#Associate pyfirmata with python for my UNO board
port='COM5'
board= pyfirmata.Arduino(port)
#Use iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start()

#Define pins (giving roles to pins: i.e. d=digital,7=pin number,i=input)
lickPin = board.get_pin('d:10:i') #records signal from the touch sensor
outPin1 = 12 #passes the signal to the valve

s = serial.Serial('COM4',4600)
while time<60s #generalized:
    rotary = s.readline() #reads the counter of the rotary encoder form arduino

    #convert the rotary to an integer try/except is needed to work
    try:
        var = long(rotary)
        last_var = var
    except:
        var = last_var
        pass

    value1 = lickpin.read()

    # Here I move the cursor up and down depending on the rotation of the encoder
    # if the cursor moves above a certain value
    if y>-18:
        board.digital[12].write(1) #should open the valve

Unfortunately the code above does not trigger the valve to be opened, and I do not know why. Help is greatly appreciated. Thanks!

I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).

Here is the pinout:

ENCODER            ARDUINO UNO
====================================
GND            ⇒   GND
+              ⇒   +5V
SW  (button)   ⇒   pin D4 (PORT D4)
DT  (encoder)  ⇒   pin D3 (PORT D3)
CLK (encoder)  ⇒   pin D2 (PORT D2)

Here is a screenshot of the output in the serial plotter:

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

And here is the code :

/*
LECTURE D’UN ENCODEUR ROTATIF KY-040
====================================
# DESCRIPTION DU PROGRAMME
Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
série de l’IDE Arduino (CMD-SHIFT-L).
La rotation du bouton est détecté avec des interruptions sur les
broches 2 et 3 du port D.
Ce programme implémente un filtrage des rebond en deux étapes (voir
la procédure “lectureEncodeur”).
Ce programme est basé sur celui d’Oleg Mazurov
https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
Pour la gestion des interruptions, voir
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
# RÉFÉRENCE DE L’ENCODEUR
http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
# CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (bouton)   ⇒   pin D4 (PORT D4)
    DT  (encodeur) ⇒   pin D3 (PORT D3)
    CLK (encodeur) ⇒   pin D2 (PORT D2)
juin 2016, ouilogique.com
*/

#define ENC_A 2
#define ENC_B 3
#define ENC_C 4
#define ENC_PORT PIND
#define BtnRead  ! bitRead( ENC_PORT, ENC_C )

bool encodeurTourne = false;
byte ENC_PORT_VAL = 0;

// Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
// pas trop vite. Cette valeur représente le nombre de millisecondes
// avant un changement sur la sortie.
static const long sensibiliteEncodeur = 10;

// Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
static const int8_t minVal = 0;
static const int8_t maxVal = 10;

void setup()
{
  pinMode( ENC_A, INPUT_PULLUP );
  pinMode( ENC_B, INPUT_PULLUP );
  pinMode( ENC_C, INPUT_PULLUP );

  PCICR  |= ( 1<<PCIE2 );
  PCMSK2 |= ( 1<<PCINT18 );
  PCMSK2 |= ( 1<<PCINT19 );
  PCMSK2 |= ( 1<<PCINT20 );
  PCMSK2 |= ( 1<<PCINT21 );

  encodeurTourne = true;

  Serial.begin( 115200 );
}

void loop()
{
  static int8_t compteur = 0;

  // Lecture et affichage des valeurs de l’encodeur
  // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
  if( encodeurTourne )
  {
    int8_t encodeurVal = lectureEncodeur();

    // Si le bouton est pressé, on remet le compteur à 0.
    if( encodeurVal == 2 )
    {
      compteur = 0;
      Serial.println( 0 );
      while( BtnRead ){ _delay_ms( 1 ); }
      _delay_ms( 20 );
    }

    // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
    else if( encodeurVal != 0 )
    {
      if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
        { compteur = minVal; }
      else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
        { compteur = maxVal; }
      else
        { compteur = compteur + encodeurVal; }

      Serial.println( compteur );
    }
    encodeurTourne = false;
  }
}

/*
  lectureEncodeur() retourne
  -1 pour une rotation dans le sens anti-horaire
   0 pour une valeur impossible (rebond)
  +1 pour une rotation dans le sens horaire
  +2 si le bouton de l’encodeur est pressé
*/
int8_t lectureEncodeur()
{
  // Si le bouton est pressé, on quitte en retournant 2.
  if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
  {
    return( 2 );
  }

  // Lecture des signaux de l’encodeur et comparaison
  // avec les valeurs possibles dans le code de Gray.
  // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
  // Les valeurs à 0 représentent les transitions impossibles
  // et qui doivent être supprimées (resultat = 0).
  // Les valeurs à 1 représentent les transitions dans le sens horaire.
  // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
  static const int8_t enc_states[ 16 ] PROGMEM =
    { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
  static uint8_t old_AB = 0;

  old_AB <<= 2;
  bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
  bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
  uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

  // On accumule “maxVal” résulats dans un sens ou dans l’autre
  // avant de bouger. Ceci permet de supprimer les derniers rebonds
  // de l’encodeur qui n’ont pas été filtrés ci-dessus.
  if( resultat != 0 )
  {
    static int8_t resultatCumul = 0;
    const int8_t maxVal = 2;
    resultatCumul += resultat;
    if( resultatCumul >= maxVal )
    {
      resultatCumul = maxVal;
      resultat = 1;
    }
    else if( resultatCumul <= -maxVal )
    {
      resultatCumul = -maxVal;
      resultat = -1;
    }
    else
      { resultat = 0; }
  }

  // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
  // et éviter ainsi qu’il ne tourne trop vite.
  static long lastT = millis();
  if( millis() - lastT < sensibiliteEncodeur )
    { resultat = 0; }
  else
    { lastT = millis(); }

  // On retourne le résultat.
  return( resultat );
}

ISR( PCINT2_vect )
{
  ENC_PORT_VAL = ENC_PORT;
  encodeurTourne = true;
}


SIM800L change default baud rate I am using an ATmega328P with internal clock (8 MHz) with a SIM800L module. The default baud rate of the SIM800L is 115,200 baud and I can't make them talk to each other correctly. Although I was able to make them talk very easily at a baud rate of 9600 baud. But now, with a new SIM800L I can't.

Question:

How to change the default baud rate of a SIM800L?
Is it possible to run an ATmega328P at a baud rate of 115,200 baud?

Thanks in advance!

EDIT:

I know that I can run atmega328p at baud rate of 115200 with different crystal, but is it possible to it using internal crystal.

As you say, SIM800L default baud rate is 115200. So, you have to set that baud rate on arduino side. And yes, it is possible to run an ATmega328P at a baud rate of 115200 baud.

You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.

#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(115200);      // Set your buad rate
}

And you can also do without this library.

void setup()
{
  Serial.begin(115200);        // Set your baud rate
}


Arduino current output Simple question: I'm researching before buying. Can any of the Arduino products output current on a 4-20mA scale? I've seen them with Analog inputs but not outputs. And if they do not, are there add on cards/Shields/Modules that you can add to use that as a function?

Thanks a bunch!

Assuming a GPIO pins outputs 5V, and you need 20 mA (0.02A), why not use a resistor of 250 ohm?

V = I * R <=>
5 = 0.02 * R <=>
R = 5 / 0.02 = 250 ohm

For 4 mA you use a resistor of 5 = 0.004 * R <=> R = 5 / 0.004 = 1,250 ohm

If you want it from the same GPIO pin, you can use also a trick:

Take a LED from a GPIO which you control by PWM
Tie a photosensor against the LED and put tape around both the LED and the photosensor
The photosensor will have a certain resistance (you can control it by the LED)
Run your circuit needing a current from 4-20mA through that photosensor.


How do I recover a beetle where I loaded a program that was too large and overwrote the bootloader? I'm doing on-target unit testing for an industrialized application and my test code is too large to fit everything on the board at the same time. I'm using the Sloeber toolset to develop, and I put something on the board that was over 28K, and the programming failed. Now the beetle does not show up as a serial port, and not even when pushing the reset pins, which I've had to do a number of times in the past.
If I overwrote the bootloader, which seems likely, is there a way to recover it? Do I need to reprogram the bootloader on a Beetle board? I haven't found any way to do that with a Beetle...
Thanks!

I don't know the Sloeber toolset, but it seems very unlikely, that it really has overwritten the bootloader. When programming via USB, it is actually the bootloader, which writes the program into the flash memory. So that would mean, that the bootloader had overwritten itself, only because a too large program. Not sure, if this is even possible.
Anyway, you can utilize an ICSP/ISP programmer (or another Arduino, if you don't have one) to burn the bootloader onto the chip again. Google for Arduino ISP to get instructions for it, there are plenty of tutorials.
You need to connect the correct pins on the Beetle with the ISP programmer. According to this site, you should find the ICSP pads at the back of the board (the group of 6 pins in 2 rows). Through these pins you can burn the bootloader.
If that doesn't work either, the problem lies somewhere else. As I already stated, overwriting the bootloader because a program is too big for the MCU should not happen and it is highly unlikely, that this is really your problem. You might have damaged something on your board, though we cannot tell that from the description. So you could just try to burn the bootloader and see what happens.


Can I make the Arduino ignore serial print I like having serial communication for debugging and testing purposes but after a while it takes away too much speed from the sketch.

Is it possible to have the Arduino ignore serial.print and serial.println throughout my code, without turning it into a comment or placing every serial printing inside for example "if(debug == true)" statements?

Thanks in advance.

If you insist on top performance, the best thing would be to use a macro for that:

#define Sprintln(a) (Serial.println(a))

Then instead of

Serial.println(F("Hello world!"));

write

Sprintln(F("Hello world!"));

etc. To deactivate the Serial printing, define the macro empty:

#define Sprintln(a)

This will have the preprocessor remove all debugging code defined with Sprintln from your code.

(Of course, there's a huge number of variations on this theme.)


Why use .h files with .cpp? At school, our teacher always taught us to use .hpp (C++ Header files) with our .cpp (C++ files). But Arduino seems to use .h files (with .cpp links?).

When someone is programming in C (without C++ compiler) they have the chance to get linked to a .cpp file through a .h file?

So why isn't a .cpp file always with a .hpp file?
What are the drawbacks of using .hpp files with your .cpp files?

This is not to start a discussion on what's best, please provide an answer with arguments that are not based on "what you like to do more".

The extension you use for a header file doesn't technically matter because the compiler never sees it. You could name it with the extension .this-is-a-header-file and it would probably still work.

The compiler only handles the C/C++ source files, typically named .c and .cpp. However, before that happens, the preprocessor goes through and looks for any #include lines. When it sees one, it basically copies the entire contents of the included file into the source file before it gets compiled.

This is normally used to include header files. However, the preprocessor doesn't know or care about different programming languages. All it does is process the raw text so there's nothing stopping you from including any text file you like, with any name or extension.

Choosing to use .h or .hpp is mostly just personal preference. You could certainly argue that it lets you (as a programmer) distinguish between C/C++ code more easily.

However, the reason why .h is more common is probably that C and C++ code is mixed so freely. You can generally compile C code as C++ without any problems, in which case it's the context (rather than the file itself) that tells you if it's C or C++. It's also possible to write a library in C++ which only exposes a C interface, meaning it could be used by C programs.

You could definitely include a C++-specific header file in a C program by mistake. All that would happen is that the compiler wouldn't understand the contents of that header file. Sensible development environments don't link to a project/library when it sees a #include directive (the Arduino IDE is the only one which does this, as far as I'm aware).


Is it possible to overload the digital pins for an Arduino? I worked on an Arduino project for school that was a self-driving security robot that also acted as a smart home system.

It was essentially a self-driving Roomba-like car that included several LED's(resembling home appliances), three distance sensors, an LCD screen, a motion sensor, an audio amplifier with a speaker, an SD card module to store .wav files, a Bluetooth module to connect with MIT App Inventor, and a motor driver that controlled two electric motors. It's a long list of modules so the Arduino Mega was required. When assembling all of these modules and building the code, I would perform intermittent tests that would isolate the obstacle avoidance and driving, turning on appliances(LED's), and sending and receiving data from the phone app. Every aspect of the project worked in isolation until I combined everything.

When everything was combined, instead of simply driving forward until an obstacle is detected as its programmed, the car would jitter around and not react to walls or obstacles. Also, the LCD screen was heavily dimmed as opposed to when the Arduino was running off of laptop power. Especially when the phone app called for turning on heat or AC, the proper LED's would turn on, but the whole system seemed to respond to the initial load required to read a .wav file and play the corresponding audio and made the jitter worse.

So my question is this, with all these modules plugged into an Arduino, is it possible that the number of modules all needing some input from the digital pins has highlighted a current limitation? All of these issues were exacerbated when the laptop power was replaced with a 9v battery. I was able to confirm that the code was not the issue as I would simply comment out major portions but leaving all the pins initialized. Also, if there is a current output limitation, is there any way to explain why? Thank you for reading my lengthy post and for giving feedback.

As mentioned in the comments, you cannot power your robot from a 9V block battery. These are made for low power projects (like a smoke detector) and cannot provide enough current to drive even only the motors correctly. Using 2 of them does not really help much. You need to change to a different battery type. If you want to stay with alkalines, you could use six AA batteries or C cells, like jsotola suggested. But you might want to upgrade to a fitting LiPo/LiIon battery (in combination with a fitting battery charger module). That would give you enough power for all your needs, while being rechargable.

A different issue: It seems to be, that you provide all the components (sensors and motors) with power through the 5V pin of the Arduino. But especially with motors you can easily reach the current limitation of the voltage regulator on the Arduino. When drawing more current through it, than recommended, the regulator will go in emergency shutdown (with a genuine Arduino; with the cheap clones, the regulator will melt and be destroyed).

Instead you need to be sure, that the drawn current does not exceed the maximum current for the voltage regulator (depends also on the voltage provided). At least the motors should be provided with power parallel to the Arduino, so that the motor current will not flow through the Arduino. It is unclear, how you are controlling the motors. If you are using a motor shield, then look for the terminal for external power supply on it. Most motor shields have them. Depending on the batteries, you will use in future, and on motors and shield, you maybe an directly connect the battery voltage to the shield. Or you need to buy an extra (switching) voltage regulator, which brings the battery voltage down to 5V. In that case be sure, that the regulator can provide the needed current plus some overhead clearance.


Arduino Leonardo keyboard I use Arduino Leonardo board for virtual keyboard. Everything work fine, but when my local keyboard layout is russian it's not work how I want. This is my code

Keyboard.print("cmd");
typeKey(KEY_RETURN);
delay(2000);
Keyboard.print("powershell iwr -outf %TEMP%\\index.html http://google.com");
typeKey(KEY_RETURN);

Otput in English US keyboard layout:

cmd
powershell iwr -outf %TEMP%\index.html http://google.com

Output in Russian keyboard layout

сьв
зщцукырудд шцк -щгеа %ЕУЬЗ%\штвучюреьд реезЖ..пщщпдуюсщь

Is there a way to make Arduino Leonardo to write every time in English US keyboard layout no matter what keyboard layout uses my computer?

The Arduino Leonardo, in the same way as any keyboard, just sends keystroke data. It is down to your computer's operating system to translate those into individual letters and symbols. The Leonardo (and indeed any keyboard) has no say over how the operating system does that translation.

A brief google search (which led back to Stack Exchange) found me this project which may be of some interest. It allows you to automatically change the selected keyboard language depending on which keyboard is being used at any one moment in time.


Junk values in EEPROM. while writing large values Facing an issue while writing a large value (like 2000-5000) to EEPROM using EEPROM.put().
For example, While writing 2000 values to address 5 of EEPROM. Some junk values are written automatically to a nearby address (address 4, 6, 7...).
Note : Not trying to write an array of 2000 elements
Board Used : Arduino Uno (Atmega328P)
Q1 : What is the typical range of a each address by using EEPROM.put() . Like EEPROM.write() has range limit of 0-255.
Q2 : How to write large value EEPROM addresses without effecting the nearby address.

It depends on what type of variable you have.  If you have single byte variables like byte or char then it is one value to one address.  But if you have an int value like:
int x = 2000;

then try to store that in EEPROM that will take 2 bytes because an int is 2 bytes in size.  So if you write that to address 5 it will take 5 and 6 to write it.
If you write a long or a float, they are 4 bytes, so they will take 4 address slots in the EEPROM each.
If you just write EEPROM.put(5, 2000); then the 2000 gets seen as either int or long depending on how the code is written.  I don't remember.  But you certainly can't fit 2000 into a byte so it's going to have to take more than one.


adafruit LSM9DS0 Library - ok with Uno but compile error with LinkitOne? I'm calling an adafruit Flora LSM9DS0 magnetometer using the Adafruit library with the following sketch:

        #include <Wire.h>
        #include <SPI.h>
        #include <Adafruit_LSM9DS0.h>
        #include <Adafruit_Sensor.h>  // not used in this demo but required!

        unsigned long timeNow = 0;
        unsigned long mSecInHour = 3600000;
        unsigned long TimeNow =0;
        int millisecs =0;
        int seconds = 0;
        byte minutes = 0;
        byte hours = 0;

        int mag_raw_x;
        int mag_raw_y;
        int mag_raw_z;

        // i2c
        Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0();

        // You can also use software SPI
        //Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(13, 12, 11, 10, 9);
        // Or hardware SPI! In this case, only CS pins are passed in
        //Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(10, 9);

        void setupSensor()
        {
          // 2.) Set the magnetometer sensitivity
          lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS);
        }

        void setup()
        {
        #ifndef ESP8266
          while (!Serial);     // will pause Zero, Leonardo, etc
        #endif
          Serial.begin(9600);

          // Try to initialise and warn if we couldn't detect the chip
          if (!lsm.begin())
          {

            while (1);
          }
          Serial.println(F("Found LSM9DS0 9DOF, measurements in Gauss"));
         }
         void loop()
        {
          lsm.read();
          TimeNow = millis();
          mag_raw_x = lsm.magData.x;
          mag_raw_y = lsm.magData.y;
          mag_raw_z = lsm.magData.z;

Which compiles and runs fine on the Arduino Uno, but I don't understand why the same sketch causes this compile error in the LSM9DS0 library when I compile for the LinkitOne?

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'bool Adafruit_LSM9DS0::begin()':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:77:16: error: 'SPCR' was not declared in this scope

         SPCRback = SPCR;

                    ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'void Adafruit_LSM9DS0::write8(boolean, byte, byte)':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:365:18: error: 'SPCR' was not declared in this scope

           SPCRback = SPCR;

                      ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:374:7: error: 'SPCR' was not declared in this scope

           SPCR = SPCRback;

           ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'byte Adafruit_LSM9DS0::readBuffer(boolean, byte, byte, uint8_t*)':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:415:18: error: 'SPCR' was not declared in this scope

           SPCRback = SPCR;

                      ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:426:7: error: 'SPCR' was not declared in this scope

           SPCR = SPCRback;

           ^

Any suggestions welcome !

The Adafruit library for the LSM9DS0 is written to run on an 8-bit Arduino. The LinkitOne isn't - it's an ARM board.

Either get a different library that is written to work on ARM, write your own library to work on ARM, or don't use that combination of components.


SIM800l doesn't respond on arduino micro I want my Arduino Micro to interact with my SIM 800 L module. But unfortunately nothing happens, may you can help me figure out where I made a mistake. Here's my wiring:

Summary of my wiring:

External Battery ---> 800L
plus ---> 5VIN
minus ---> GND (both in POWER and UART TTL-Section)

Arduino ---> 800L
RX ---> RXD
TX ---> TXD

With that setup I'm using the following code:

#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(1, 0); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    char c = mySerial.read();
    Serial.print(c);
  }

  mySerial.write("at+cmee=2"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    char c = mySerial.read();
    Serial.print(c);
  }

}

But it gives me the following output as a loop:

 Sending AT command
 Response:
 Sending AT command
 Response:
 Sending AT command
 Response:

And I've noticed that a yellow LED is blinking on the Arduino while running the program so I assume there has to be some input from the SIM800 but I can't read the data at the moment. On the 800L-board itself is also an LED that blinks in an interval of about one second, wich tells you that it has no connection (I live in a relatively remote area) but even if there's no connection shouldn't it still return OK when sending AT?

If you need any further information feel free to ask. I would appreciate every idea you come up with :)

Edit: On the photo the wire goes from the Arduino directly to the 800L but I've changed it so the 800L-power comes from a battery now.

Here is some edit in your code

#include <SoftwareSerial.h>
#include<Arduino.h>

//Arduino Micro
//SIM 800l

SoftwareSerial mySerial(9,10); // RX, TX

void setup()
{
  // Open serial communication
  Serial.begin(9600);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);

  Serial.println("Setup finished");

}

void loop() // run over and over
{
  Serial.println("Sending AT command");
  mySerial.write("AT\r\n"); //OK should be returned
  delay(1000);
  //read sim-module response
  Serial.println("Response: ");
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

  mySerial.write("at+cmee=2\r\n"); //set sim-module into debug mode

  delay(1000);

  mySerial.write("at+cpin?\r\n"); //check if pin is necessary

  //read sim-module response
  while( mySerial.available() )
  {
    String c = mySerial.readString();
    Serial.println(c);
  }

}

Change UART pins to 9,10 as 0,1 are already used in normal serial. Secondly change Seria.read() to Serial.readString() because as far as i know the response is string.


Arduino configure script for conditional compilation of libraries I have a library the uses conditional compilation based on the preprocessor variables. The library is a separate .cpp object file with a header.

How can I pass preprocessor variables to the compilation of the library? Standard #define in a sketch file wouldn't work, since their live will be limited to my sketch object file(s), not the library's.

Normally it is solved by the ./configure script and/or the custom make process. How can I do it on Arduino?

Supplying a separate compilation/source code of the library for all 2^8 combinations of the preprocessor switches doesn't seem feasible...

The problem here is that the Arduino IDE is not setup for doing this. Any real IDE has the possibility to set defines.

If you want your library to be used by arduino IDE users you will have to go to dirty routes like the #include and config.h approach already mentioned.
If I'm not mistaken arduino IDE compiles libraries with the full include path so you can have the config.h next to your sketch.ino file.

If the library is not intended for arduino IDE users I would advice using a real IDE like my Arduino Eclipse Plugin.


OSX upload error: avrdude: ser_open(): can't open device "/dev/cu.mydev" : Resource Busy I'm trying to upload the blink script to my unnamed Arduino-like board. However, the USB port appears to be busy.

This is all the output I get:

Archiving built core (caching) in: /var/folders/43/7_h5zwcs1csdr2dc635m1yq40000gp/T/arduino_cache_942504/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a
De schets gebruikt 928 bytes (2%)  programma-opslagruimte. Maximum is 32256 bytes.
Globale variabelen gebruiken 9 bytes (0%) van het dynamisch geheugen. Resteren 2039 bytes voor lokale variabelen. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "/dev/cu.mydev": Resource busy

I've tried all solutions I could find on internet, but they haven't solved my issue. The main difference with my error and online solutions/errors is that I only have this error. Other people experienced extra errors which enabled the debugging of the problem.

Can anyone help me please?

I think my available serial ports were insufficient or something. I installed the ch34* driver which allowed an additional device showing up. Here's the download: http://www.wch.cn/download/CH341SER_MAC_ZIP.html

Then I selected this port and I finally could upload.


How to compile an official VS1003 / VS1053 example for Arduino / ESP8266? Have anyone ever successfully run any of the official playback and recording examples for VS1003 or VS1053 on Arduino / ESP8266? I mean, I was able to play sound with VS1003, but I just can't make the official example compile on Arduino IDE... It looks like it should be no problem (just provide a few methods and copy the main method code from the PDF file to the setup() in sketch) but I'm just getting a bunch of stupid compiler or linker errors, like "undefined reference to 'VSTestInitHardware()' " while the player.h header file (containing it) is included. I'm not a C / C++ expert so it's either something stupid I do or it's just not possible on Arduino. Can anyone provide a compilable example? I'm trying it with ESP8266 currently (and it is my desired target CPU), but an Arduino Uno version could help too (it throws different errors but doesn't compile neither). Thank you.

Ok, after long battle with C++ compiler I have a working example (at least for VS1003 and ESP8266) with a checklist how to recreate it (with minimal changes to the example files). I'm sure someone else will have this problem so I'm attaching it:

The things that you need to do in player1003.c:

rename to player1003.h (change file extension only)
remove all 5 includes from the top (stdio, string, stdlib, ctype, "player.h")
turn off REPORT_ON_SCREEN (change #if 1 to #if 0) if you don't want to have a lot of serial output
mass replace "FILE *" to "File " - mind the space (change type of file variables in all methods, mark "Case sensitive" to avoid errors in player1053!)
mass replace fopen( to fopen2(
mass replace printf( to Serial.printf(
mass replace fflush(stdout); to //fflush(stdout); (or Serial.flush();)
remove method: VSTestInitHardware(void)
remove SM_SDISHARE flag from WriteSci(SCI_MODE, SM_SDINEW|SM_SDISHARE|SM_TESTS|SM_RESET); line  (in VSTestInitSoftware(void) method)
in VSTestHandleFile() at the bottom add fp.close(); after VS1003PlayFile(fp); and VS1003RecordFile(fp); lines (especially after the record!). We don't want unclosed files on SD card.

The main sketch (.ino):

#include <SPI.h>
#include <SD.h>
#include "player.h"

using namespace std;

// I use these values below for ESP-12 (ESP8266):
#define MP3_xCS 2
#define MP3_xDCS 4
#define MP3_DREQ 5
#define MP3_xRESET 16
#define SD_CS 15
#define SPI_MOSI 11 //SPI
#define SPI_MISO 12 //SPI
#define SPI_CLK  13 //SPI

#define  WAIT_DREQ()  while(!digitalRead(MP3_DREQ))

File song;

int VSTestInitHardware()
{
  pinMode(MP3_DREQ, INPUT);
  pinMode(MP3_xCS, OUTPUT);
  pinMode(MP3_xDCS, OUTPUT);
  pinMode(MP3_xRESET, OUTPUT);
  pinMode(SD_CS, OUTPUT);

  digitalWrite(MP3_xCS, HIGH);
  digitalWrite(MP3_xDCS, HIGH);

  digitalWrite(MP3_xRESET, LOW); // chip off!
  delay(100);
  digitalWrite(MP3_xRESET, HIGH); // chip on!

  Serial.begin(115200);

  if (!SD.begin(SD_CS))
  {
    Serial.println("Can't initialize SD!");
    return -1;
  }
  Serial.println("SD OK!");

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV32);  // Bus SPI at 1MHz (for Arduino: 16MHz / 16 = 1MHz)
  SPI.transfer(0xFF);  // Write something to the bus
  delay(10);
  return 0;
}

void setup()
{
  if (VSTestInitHardware() || VSTestInitSoftware())
  {
    Serial.printf("Failed initializing VS10xx, exiting\n");
    exit(EXIT_FAILURE);
  }
  /* ... */
  /* Playback example. You can call these functions many times in a row
  because they leave VS1003 in a stable state. */
  VSTestHandleFile("TEST.mp3", 0);  // remember to use 8.3 file names format on SD!
  /* Recording example */
  VSTestHandleFile("RECORDED.WAV", 1);  // original example for VS1003 has a bug here (OGG extension)

  Serial.println("Playing recorded file...");
  VSTestHandleFile("RECORDED.WAV", 0);

  Serial.println("THE END");
}

void loop()
{
}

void WriteSci(unsigned char reg, unsigned char hsb, unsigned char lsb)
{
  // for debugging:
  Serial.printf("Setting %s to: %d (%X, %X)\n", RegName(reg), (hsb<<8) + lsb, hsb, lsb);

  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x02);
  SPI.transfer(reg);
  SPI.transfer(hsb);
  SPI.transfer(lsb);
  WAIT_DREQ();
  digitalWrite(MP3_xCS, HIGH);
}

void WriteSci(u_int8 addr, u_int16 data)
{
  WriteSci(addr, data >> 8, data & 255);
}

uint16_t ReadSci (unsigned char reg)
{
  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x03);
  SPI.transfer(reg);
  delayMicroseconds(10);

  char response1 = SPI.transfer(0xFF);
  WAIT_DREQ();
  char response2 = SPI.transfer(0xFF);
  WAIT_DREQ();

  digitalWrite(MP3_xCS, HIGH);

  unsigned int resultvalue = response1 << 8;
  resultvalue |= response2;

  // for debugging:
  if (reg != SCI_HDAT0 && reg != SCI_HDAT1)  // these registers are filtered out because they are intensively used during recording
    Serial.printf("%s is: %d (%X, %X)\n", RegName(reg), resultvalue, resultvalue >> 8, resultvalue & 255);

  return resultvalue;
}

int WriteSdi(const u_int8 *data, u_int8 bytes)
{
  WAIT_DREQ();
  digitalWrite(MP3_xDCS, LOW);

  for(int y = 0 ; y < bytes ; y++)
    SPI.transfer(data[y]);

  digitalWrite(MP3_xDCS, HIGH);
}

const char* RegName(uint8_t reg)
{
  switch (reg)
  {
    case 0x00: return "SCI_MODE";
    case 0x01: return "SCI_STATUS";
    case 0x02: return "SCI_BASS";
    case 0x03: return "SCI_CLOCKF";
    case 0x04: return "SCI_DECODE_TIME";
    case 0x05: return "SCI_AUDATA";
    case 0x06: return "SCI_WRAM";
    case 0x07: return "SCI_WRAMADDR";
    case 0x08: return "SCI_HDAT0";
    case 0x09: return "SCI_HDAT1";
    case 0x0A: return "SCI_AIADDR";
    case 0x0B: return "SCI_MIXERVOL";
    case 0x0C: return "SCI_AICTRL0";
    case 0x0D: return "SCI_AICTRL1";
    case 0x0E: return "SCI_AICTRL2";
    case 0x0F: return "SCI_AICTRL3";
  }
}

void SaveUIState(void)
{
}

void RestoreUIState(void)
{
}

int GetUICommand(void)
{
  while (Serial.available() > 0)
  {
    char c = Serial.read();
    if (c != 10 && c != 13)
      return c;
  }
  return -1;
}

void exit(int code)
{
  if (code == EXIT_SUCCESS)
    Serial.println("Exited with no error.");
  else
    Serial.printf("Terminated with error: %d\n", code);
  while (true) { yield(); }  // yield() is needed for ESP8266 only
}

File fopen2(const char* fileName, const char* mode)
{
  if (mode[0] == 'w')  // fast workaround!
  {
    Serial.printf("Opening for writing: %s\n", fileName);
    song = SD.open(fileName, O_WRONLY | O_TRUNC | O_CREAT);
  }
  else
  {
    Serial.printf("Opening for reading: %s\n", fileName);
    song = SD.open(fileName, O_RDONLY);
  }

  if (!(song))
  {
     Serial.printf("File not found: %s\n", fileName);
     return song;
  }
  Serial.printf("File opened: %s\n", fileName);
  return song;
}

size_t fread ( void * ptr, size_t size, size_t count, File stream )
{
  yield();  // this is needed for ESP8266 only (otherwise reboots)
  return stream.read(ptr, size * count);
}

int fseek ( File stream, long int offset, int origin )
{
  stream.seek(offset);
}

size_t fwrite ( const void * ptr, size_t size, size_t count, File stream )
{
  return stream.write((uint8_t*)ptr, size * count);
}

int fflush ( File stream )
{
  stream.flush();
  return 0;
}

#include "player1003.h"

(i had to manually clean this file out of my additional code, but I hope it will compile just fine).

I have a request:

If you run this example, please write me in comment whether the recording worked. I can't make my VS1003 module record sound. I have a suspicion that mic in my module is broken. That's why I was trying the official example (with the minimum changes as possible). It records only noise in my case, but plays mp3 perfectly. If you have a working example of recording, please share too.

And one more to the people with more rep (moderators): Please add a VS1003 (and VS1053 and VS1063) keywords and assign it to my questions about VS1003, because I'm unable to do it and it should be done. The chip deserves a keyword. (It's really good and not expensive.)


Powering arduino uno from Car's reverse light? I am making a reverse sensing alarm system. I am using a HC-SR04, arduino UNo and a piezo buzzer. The programming was a success however i will like this circuit to be powered when the reverse gear is shifted into place. So I am thinking to power the V in of the UNO with the 10V from the  reverse bulb socket receives. However I think the amperage sent to this bulb is too much for my UNO. What should I do ? and Does anyone have any other recommendations to power the UNO in such a scenario?

Power the Arduino in parallel with the bulb.  Take the V+ wire running to the reverse light and the frame ground.  The frame ground is any bare metal surface of your car will be grounded, just connect a wire to your frame.  Or you can just splice the light bulbs ground wire.  When powering the circuit in parallel you do not have to worry about the amperage draw of the light.  By a barrel jack connector like this connector from spark fun you can buy these cheaper elsewhere just a 2.1mm barrel jack connector.  Connect the positive and negative respectively, and connect the 12v into the Arduino's barrel jack.

As a side note the bulb should be getting 12V not 10V it's not a huge problem, but it is a slight issue that could later be a problem or be caused by an electrical bug.  If everything works don't scramble to fix it, but be aware it exists.


Strings from serial are not equal In my code I have that string:String code = rs1 + rs2 + rs3; //rs1=034, rs2=000, rs3=017 It means that code = "034000017". But if I run if (code.equals("034000017")) Serial.println("OK"); There is nothing in serial monitor. Here is full code:

String code, rs1, rs2, rs3, readString;
void setup() {
    Serial.begin(9600);
    Serial.println("Serial ready!");
}

void loop() {
    if (Serial.available()) {
        while (Serial.available()) {
          delay(10);
          if (Serial.available() >0) {
            char c = Serial.read();
            readString += c;
            rs1 = readString.substring(0, 3); //034
            rs2 = readString.substring(3, 6); //000
            rs3 = readString.substring(6, 9); //017
            code = rs1 + rs2 + rs3;
            Serial.println(code);
            if (code.equals("034000017")) Serial.println("OK");
          }
        }
    }
}

Lots of errors in your code. Mine is basically the same that @frarugi87's answer.

I only have to add: when reading serial, wait for the end of line ('\r' and/or '\n') to know when you have all your data, so you don't depend on length (which can be corrupted).

Edit (on Majeko's comment)

String code, rs1, rs2, rs3, readString;
void setup()
{
  Serial.begin(9600);
  Serial.println("Serial ready!");
}

void loop()
{
  static bool inData = true;

  while (Serial.available()) {
    char c = (char) Serial.read();

    if (c != '\r' && c != '\n') {
      readString += c;
      inData = true;
    }
    else {
      if (inData) {
        rs1 = readString.substring(0, 3); //034
        rs2 = readString.substring(3, 6); //000
        rs3 = readString.substring(6, 9); //017
        code = rs1 + rs2 + rs3;
        Serial.println(code);

        if (code.equals("034000017")) {
          Serial.println("OK");
        }
        readString = "";
        inData = false;
      }
    }
  }
}

This code works for any configuration of line ending ('\r', '\n' or '\r\n').

It doesn't test for length (or validity or timeout); it's left as an exercise to the reader :-)

I hope it shows how code grows when making it robust in all scenarios.


What's the point of a USB to Serial converter in Arduino Uno? I am trying to understand how an Arduino Uno communicates with a PC and why it does so.

As far as I understand, an Arduino can be programmed to communicate with a PC only via a COM interface. At the same time, an Arduino Uno uses a physical USB interface to connect to a PC and it has a USB-serial converter onboard. So data sent from the board is converted from COM to USB to be transferred to the PC where USB data is converted to COM by a device driver to be read by a COM-port listener.

Why does this COM-related stuff is needed if the Arduino already uses the USB stack for connection? And is the Arduino able to emulate a keyboard and mouse if it has to use interrupts for this, so it has to act like USB device without using COM?

The problem with your understanding is with what "COM" is.

"COMx" is not a physical serial port - it is merely a concept. It is a "serial device" in Windows.

That Serial Device is implemented as a CDC/ACM protocol on USB. It's not "converted" - "COMx" is just the visible interface to the PC's end of the CDC/ACM connection.

The ATMega328P chip (and the ATMega2560) can't talk USB directly. They talk UART. So UART data is sent to another chip that can talk both USB and UART to bridge the two technologies.

So from the PC perspective the chain is:

CDC/ACM Driver ("COMx") => USB => ATMega16U2 => UART => ATMega328P

Boards with an ATMega32U4 chip on them, like the Leonardo, can talk USB directly - so the sequence is much shorter:

CDC/ACM Driver ("COMx") => USB -> ATMega32U4

Again there is no conversion from "COMx" to "USB" since "COM" is just the name given to the exposed end of the CDC/ACM driver.

It can be said that CDC/ACM emulates a serial port over USB. It forms a channel between the CDC/ACM driver ("COMx") and a pair of bulk endpoints in the chip at the other end of the connection.


Usefulness of measuring 0v using ADC I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (VBG), and lastly 0V (GND).

What would be the use of measuring 0V?
Would it ever result in a reading other than 0? I find it very intriguing.

The datasheet doesn't seem to give any additional information about it.

AVR126 seems to give a hint:

  configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC.

Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz).

Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).

That quote you mention says it all really.  It's purpose is to discharge the Sample And Hold capacitor.

That capacitor is used (as I'm sure you are aware) to store the incoming voltage while it's being sampled by the ADC.  The ADC operated in two main phases:

Acquisition
Sampling

During acquisition the capacitor is connected to the incoming voltage.  During sampling it is disconnected from the incoming voltage and the voltage it stores is read into the internal registers.

It takes a certain amount of time for the voltage in the capacitor to equal that of the incoming voltage.    If you try reading at higher speeds then what voltage was in the capacitor from the previous sample can affect the new reading.  However, if you do each sample always from a known voltage in the capacitor (0V) then you get much more stable results.

Another good use for it is when using the ADC as a Charge Time Measurement Unit.  This is the proper way of performing capacitative sensing.  You apply a constant (tiny) current to an external capacitor (the sensing plates) for a specific period of time.  When that time is up you disconnect the constant current source and measure the voltage that has developed across that capacitance.  The capacitances and currents are small, and if there is a charge in your S&H capacitor at the time you do the sampling that will be back-fed into the touch sensor capacitative plates changing the voltage.  By ensuring that the S&H capacitor is at 0V before you sample the plates you won't be adversely affecting the voltage on the plates with successive readings (well, you will, but it will be consistently in the same way every time so it won't affect your overall results).


Logging multiple gigabytes of data with Arduino I have Arduino Uno with SD card shield. I'm planning to log a huge amount of data from various sensors - including accelerometers and 3D compass - to the SD card.

However, I have understood that Arduino, 64GB SD, FAT and large amount of data are not working too well.

Does Arduino work well with this amount of data on FAT? There's no need to read any data from SD on Arduino. If not, is there a better approach? Writing directly to SD without FAT?

This data logger will be on the environment where no computer or network connection is available. Performance is not an issue - around 8kB/s (over three months) is already enough.

I'm not sure where you have the impression it won't work. I haven't used 64GB cards, but have used 32GB cards and they work fine in terms of FAT32 and writing files.

As you have already worked out, reading or searching the file system can get very slow as size increases.

That said, I have found that larger capacity cards are more likely to have problems with the SPI interface being poor quality. Consumer devices do not use the SPI interface, and it seems that some manufacturers are willing to skimp on this side of it. The SPI interface can be buggy or unstable as a result. Genuine name-brand cards should work fine though.


Arduino Rotary Encoder Pulses? I made an program so if I turn on my rotary encoder the position and the rotation comes on a LCD screen. But I need to change it a bit up for my teacher, she wants to see the graph of the pulses on the serial monitor. I searched it up and can't find a solution? Any help?

My program:

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);
#define outputA 2
#define outputB 4
int counter = 0;
int angle = 0;
int aState;
int aLastState;
int lastAngle = 0;
String rotationDirection;
String savedRotationDirection;

void setup() {
  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);

  aLastState = digitalRead(outputA);
  lcd.begin();

     }

void loop() {
  aState = digitalRead(outputA);
  if (aState != aLastState){
     if (digitalRead(outputB) != aState) {
       counter ++;
       angle ++;
     }
     else {
       counter--;
       angle --;
     }
     if (counter >=30 ) {
      counter = 0;
     }

     if (angle < lastAngle){
      rotationDirection = "CCW";
     }
     else {
      if (angle > lastAngle){
        rotationDirection = "CW";
      }
      else {
        rotationDirection = savedRotationDirection;
      }
     }
     lcd.clear();
     lcd.setCursor(0,0);
     lcd.print("Position: ");
     lcd.print(int(angle)*(-1));
     lcd.print((char)223);
     lcd.setCursor(0,1);
     lcd.print("Rotation: ");
     lcd.print(rotationDirection);
     savedRotationDirection = rotationDirection;
     lastAngle = angle;
  }
  aLastState = aState;

}

Add Serial.begin(115200); in setup() and use Serial.println() or Serial.print() to print to Serial.

In Arduino IDE open Serial Monitor and set baud rate to 115200.

EDIT: The question turned out to be about Serial Plotter. Maximilian Gerhardt answered in a comment :

  If you want multiple data streams (graphs) you need to seperate them
  by a comma: Serial.println( String(digitalRead(outputA)) + "," +
  String(digitalRead(outputB)));


Processing printing sensor readings and raising NaN exception at the same time I am using pressure sensor with Arduino Uno within Processing.
Given these variables:

Serial myPort;              //the serial port
float sensorValue = 0;      //the value form the sensor

Arduino is printing float numbers on Processing console, according to the snippet below.

(...)

void serialEvent (Serial myPort){
//get the ASCII string
String inString = myPort.readStringUntil('\n');

if (inString != null){
//trim off any whitespace:
inString = trim(inString);
//convert to an int and map to the screen height
sensorValue = float(inString);
println(sensorValue);
sensorValue = map(sensorValue, 0, 1023, 0, height);
//println(sensorValue);

However, I am getting a NaN exception:

sensorValue = map(NaN, 0, 1023, 0, height);

how is this possible? printing numbers that aren't numbers?

//convert to an int and map to the screen height
sensorValue = float(inString);

You can't convert a String to a Float just like that by casting.  You have to interpret the characters within the String.  Oh, and a float isn't an integer.

All you're doing there is trying to cast the address of the String object to a float, which it really doesn't like, hence you get NaN.

Try:

int sensorValue;
sensorValue = inString.toInt();


What changes I have to take care while coding from Atmel Studio instead of Arduino IDE? -Are there any changes in Bootloader?
-Why is the coding different for same chip in different softwares?
-How to upload the program from Atmel Studio?

Atmel cpp projects do not currently provide an option to upload using Arduino bootloader. Atmel only provides upload using hardware programmers.

The bootloader is deleted when you upload using a hardware programmer either from Atmel Studio or from the Arduino ide.

The underlying Atmel toolchain is not very different from the latest Arduino toolchain however Atmel does not know about the Arduino hardware/cores. You have to copy the Arduino core sources to your Atmel project if you want to compile for Arduino compatibility but that still does not give you bootloader upload.

It is not clear from your question if you have the Arduino sources in your cpp project already. If you do have the sources in your project then you can use avrisp mkII or other programmer to upload but the Arduino libraries might be an issue for you if you are using them.

There is another option in Atmel Studio however it might not be what you require ...

You can install the Visual Micro plugin for Arduino from the Atmel Gallery and work with standard Arduino sketch projects inside Atmel Studio.

The Visual Micro plugin provides full Arduino compatible sketch build and bootloader upload in Atmel Studio. Because of the nature of Arduino, the Visual Micro plugin automatically manages the include paths and Atmel project properties so that intellisense works in projects that contain .ino source code files. If the project does not contain .ino files then Visual Micro sleeps (does not interfere with cpp projects)

The plugin also provides other features such as a serial usb debugger, library manager, board manager, Arduino examples etc.

More about Visual Micro is here

Tutorials are here

Debugger overview is here

Update:

There is no difference in program execution between uploading using a physical hardware programmer or using a usb cable via bootloader.

The Arduino libraries sources can be more complicated to include/compile in a project because they often include additional folders with private source code. This is more of an issue with older Arduino libraries that have a sub folder called \utility.


Docs for using i2C LCD with Newliquidcrystal_1.3.5 library? I bought a 20x4 I2C LCD from OddWires. (https://www.oddwires.com/20x4-lcd-display-with-i2c-interface/) It came with ZERO specs or documentation. After some hair-pulling I was able to figure out how to get it working. (I had to use the commands

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address and pin assignments, including the backlight pin and polarity

and

  lcd.begin(20,4);               // initialize the lcd to 20 characters, 4 lines

To get the LCD working (The tricky bit was figuring out the pin assignments. They're not documented.)

I'm assuming this LCD unit is a lot like all the others out there.

It works, and If found the basic commands to clear the screen, position the cursor, and print text.

I've also found commands lcd.cursor() and lcd.noCursor() that let me show/hide the cursor.

I'd like to know if I can do things like blink characters between normal and inverse, underline text, etc using the standard LCD library (I've seen code that uploads custom character maps, so I assume I could upload an alternate underlined character set, but that sounds like a LOT of work for something I'm hoping is built in to the library.)

Can somebody point me to docs on the full suite of commands commonly available for these LCD units in the Arduino Newliquidcrystal_1.3.5 library?

(Sorry to be vague on the specifics of my LCD module. I did not get specs from the vendor, so I have had to guess as to how to use it.)

I'm using the I2C LCD NewLiquidCrystal LCD library. (https://github.com/fmalpartida/New-LiquidCrystal)

Often in software development, the code is the documentation. The merits of this are debated ad nauseam elsewhere.

As you have provided a link to the GitHub repository of the library you are using, you have all you need, though the provided utility/docs path doesn't fully document the I2C interface.

The function prototype (that is, the function, its return type, and parameters, but without the actual code) is found in header files which usually have the .h suffix.

Since you have an LCD with a I2C interface, you can look at the GitHub repo for the file LiquidCrystal_I2C.h

Within this file, you can see that the class is defined with name LiquidCrystal_I2C and has multiple constructors, each with a different list of parameters. The particular class constructor used is the one that matches the count and type called in your declaration of the object of that class.

The code in the header file is well documented. The first prototype listed includes good commenting:

/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    */
   LiquidCrystal_I2C (uint8_t lcd_Addr);
   // Constructor with backlight control
   LiquidCrystal_I2C (uint8_t lcd_Addr, uint8_t backlighPin, t_backlighPol pol);

This block shows the first 2 constructor options: With a uint8_t type that defines the I2C address of an I/O expansion module (which is what many "LCD backpacks" are -- that, or shift registers), and one with an I2C address, a backlight pin, and the polarity of the backlight.

Proceeding down, we find the one with 10 parameters, which is what you ended up using:

  /*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d4[in] LCD data 0 pin map on IO extender module
    @param      d5[in] LCD data 1 pin map on IO extender module
    @param      d6[in] LCD data 2 pin map on IO extender module
    @param      d7[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7 );
   // Constructor with backlight control
   LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
                     uint8_t backlighPin, t_backlighPol pol);

That last constructor is used to override the default pin mappings from the I/O Expander to the LCD. This is tricky -- what were the mappings based on? An I/O expander is basically a way to access multiple pins on an external chip through a single two-wire interface (I2C). How an LCD is connected depends on what pins of the I/O Expander are connected to which pins of the LCD. There is not a formal standard, though there may be convention.

Reading the GitHub page, you see that this is a

  Clone of the new liquid crystal library from: https://bitbucket.org/fmalpartida/new-liquidcrystal

Following that link takes us to some kind of documentation, noting that one of the connection types is:

  I2C IO bus expansion board with the PCF8574* I2C IO expander ASIC such as I2C LCD extra IO.

A link to that hardware is helpfully provided! We can follow the link to see that the hardware is discontinued, but helpfully documented with some schematics and PCB layouts that tell us which pins of the I/O expander are connected to which pins of the LCD:

P0 is pin 0 of the I/O expander -- the top row are the I/O expander pins. Vo, RS, R/W, etc. are the LCD pins.

LCD Pin  |  I/O Expander Pin
     En  |  P4
    R/W  |  P5
E (rst)  |  P6
     D4  |  P0
     D5  |  P1
     D6  |  P2
     D7  |  P3

(And the backlight is a passthrough pin, not on the I/O Expander. It appears the definition of the backlight pin and polarity refer to I/O Expander pins.)

This is the point where you have to find out if the I/O expander on your purchase has the same pinout as the product for which this library was written.

Your "working" instance is called as (with annotations to the constructor being called)

LiquidCrystal_I2C lcd(
  0x27,       // lcd_Addr
  2,          // En (enable pin)
  1,          // Rw (read/write pin)
  0,          // Rs (reset pin)
  4,          // d4 (data)
  5,          // d5 (data)
  6,          // d6 (data)
  7,          // d7 (data)
  3,          // backlight
  POSITIVE    // backlight polarity
);

This indicates that the I/O expander on your LCD does not have the same pin connections as that for which the library was written, which is why you had success only when remapping them in the constructor.

All that to just re-state the hair-pulling you had to do!

The actual functions available are noted to be:

  This library provides the same interface to applications as the LiquidCrystal library sourced by the Arduino SDK.

But to be absolutely sure, you can also see their prototypes in the header file: https://github.com/fmalpartida/New-LiquidCrystal/blob/master/LCD.h

It provides scrolling, blinking, enable/disable, etc.


Ethernet shield or Wifi sheild - Arduino? To control some LEDs through internet using Arduino UNO, which type of connection  is better ? Ethernet or Wifi? (Later, I may connect some relays instead of LEDs, and control (turn on and off) some devices using this setup).
The only difference I know is the wired and wireless connectivity.
Is there any other difference?

If you are beginner with Arduino its better to start with Ethernet Shield. Its much more easy to connect with Arduino.

WiFi Module - ESP8266 required some more knowledge, that you will learn in future.

The bought products are cheap, so you can start with Ethernet and after that to switch to ESP.