Problem with load cell and ADS1262 I'm using PROTOCENTRAL ADS1262 32-BIT PRECISION ADC BREAKOUT BOARD to read the voltage in simple a load cell.

The connections follows the instructions on its library

But I cannot make it work, the readings has lots of spikes and i cannot discover what is happening.

Can someone help?

This problem was solved on Texas Instruments Forum.
Thanks.

http://e2e.ti.com/support/data_converters/precision_data_converters/f/73/p/627185/2344271#2344271

From the TI forum:

  I noticed that you are polling data ready and then performing the data processing/serial output. The serial output operation is likely taking a long time and preventing you from capturing data at the faster data rates. You can try disabling the serial output and using an oscilloscope to see if you're able to reading data at the full throughput; however, when outputting this data over a serial interface you might not be able to capture and display all of the data...

  I would try capturing data to memory and outputting the serial data in batches (for example, output 10 samples of data at a time). This might give you a little more data throughput.


Sketch talks to Android via BLE on Serial2 but times out after 5 seconds when Serial cable disconnected or not present From an Android phone I am using the "Serial Bluetooth Terminal" app to communicate to an Arduino Mega 2560 with a Bluetooth Low Energy HM10 (Jaycar XC-4382) module connected via Serial2.

If the physical USB serial cable (Serial) is connected to Arduino the very simple sketch below works fine and runs continuously. When the cable is disconnected mid sketch or the power is cycle without the cable connected the sketch will run for about 5 seconds and then stop.

How can I prevent the sketch from timing out when the serial cable is disconnected?

int counter = 0;

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

void loop()
{
    Serial2.print(counter); Serial2.println();
    delay(1000);
    counter++;
}

The workaround is to switch to using SoftwareSerial, see code below. Data is continuously sent via Bluetooth from Arduino Mega to Android with or without the usb cable connected.

#include <SoftwareSerial.h>

// Connections
// Arduino HM10
// MEGA
// ----    ----
// 3.3v    VCC
// GND     GND
// 12      RX
// 13      TX

SoftwareSerial bte(12,13);    // RX, TX use (2,3) for UNO
int counter = 0;

void setup() {
  // set the data rate for the SoftwareSerial port
  bte.begin(9600);
  bte.println(counter);
}

void loop() { // run over and over
  bte.println(counter);
  counter++;
  delay(1000);
}


Can 1 arduino control 6 stepper motors? I want to make a single cell 3×2 Braille grid that has 6 up and down shafts each of which can be controlled by arduino using 6 stepper motors .

So will that work with 1 arduino uno and/or stepper driver?
How many drivers should I use or is there a better way for controlling those 6 up down shafts individually?
Can I use 16 channel servo shield for controlling those stepper motors?

A servo is not the same type of motor as a stepper. A servo is controlled by a somewhat PWM signal (somewhat, because the servos position will come from the absolute pulse length, not the duty cycle). A stepper motor needs to get the different phases driven in the correct order. This is done by a driver circuit for stepper motors and you cannot use the servo shield for this purpose without any extra circuitry.

You should use drivers explicitly meant for your type of stepper motor. Most drivers will have 2 inputs: 1 direction input (HIGH level means driving the motor in one direction, LOW level in the other) and 1 pulse pin. Everytime a pulse (pin going to HIGH, stay there for a short time and going back to low; or sometimes vice versa) is reaching this pin, the stepper will do 1 step. So to let the motor spin at a certain speed, you need to provide a specific number of pulses in a specific amount of time.

Since you want to drive all steppers individually, you need 6 drivers (one for each motor) and 12 output pins on your Arduino.

See the Stepper.h library in the IDE. I used it to control 7 Stepper motors (28BYJ-48) each with a simple ULN2003 driver board ($4-5USD for the 'unit') and control them from a '1284P (add in to the Arduino IDE). youtube.com/watch?v=5-9pqTQP_SQ Later reading suggests these little motors might be controllable with just 2 pulses (vs 4), I haven't done any experiments to confirm that; I played for a while just to find motor speeds/settings that resulted in smooth movements. We designed and 3D printed the white discs ourselves.
My plan eventually is to have 7 or 10 banks like this, make a kinetic sculpture kind of thing.


Returning struct from function generates 'does not name a type' compilation error I have a main.ino file that contains
struct EulerAngles {
  double roll, pitch, yaw;
};

void setup() {
  EulerAngles angles;
  angles = anglesCalc();
  Serial.print(angles.yaw);
}

void loop() {
  Serial.println("In loop");
  delay(1000);
}

and an angles.ino file that contains
EulerAngles anglesCalc(){
   EulerAngles a;
   // calculate a
   return a;
}

When I compile the program, I get a compile error in the main.ino file:
   code/so_examples/main.ino:5:1: error: 'EulerAngles' does not name a type
 void setup() {
 ^~~~~~~~~~~
code/so_examples/main.ino: In function 'void setup()':
code/so_examples/main.ino:7:12: error: 'anglesCalc' was not declared in this scope
   angles = anglesCalc();
            ^~~~~~~~~~
code/so_examples/main.ino:7:12: note: suggested alternative: 'angles'
   angles = anglesCalc();
            ^~~~~~~~~~
            angles
[Build] Error occurred.

How do I fix this? Note that struct is declared before all else, so this answer does not seem to apply.  I am using the Stino plugin for Sublime Text as the IDE.

I would avoid having multiple .ino files, because of the issues raised
in the other answers. If you want to split your code into multiple
files, the scheme that works reliably is to have:

a single .ino file, named like the containing folder, holding the
“main” program (this is Arduino-specific)
a pair of .h/.cpp files for each “module” implementing a sub-feature
of the program (this is common C++ practice).

Within the .h/.cpp pair, the .h file declares everything the compiler
needs for understanding code that uses the feature: type definitions
(including classes) and function prototypes. The .cpp file holds the
actual implementation.
Applying this scheme to your case would give:
my-sketch.ino (actually, with the name of the containing folder):
#include "angles.h"

void setup() {
  EulerAngles angles;
  angles = anglesCalc();
  Serial.print(angles.yaw);
}

void loop() {
  Serial.println("In loop");
  delay(1000);
}

angles.h:
struct EulerAngles {
  double roll, pitch, yaw;
};

EulerAngles anglesCalc();

angles.cpp:
#include <Arduino.h>
#include "angles.h"

EulerAngles anglesCalc() {
   EulerAngles a;
   // calculate a
   return a;
}

Note that including <Arduino.h> is only useful if the code uses the
Arduino core API. Otherwise you can omit it. The main sketch does not
need to include <Arduino.h> because it is implicitly included in the
.ino file by the Arduino IDE. There is no such implicit inclusion when
the IDE processes .cpp files.

Try to add struct at the first of function, such as:
struct EulerAngles anglesCalc(){
   EulerAngles a;
   // calculate a
   return a;
}


How can I pair a Bluetooth dongle on arduino Yun (openwrt-yun)? On my Arduino Yun (openwrt-yun, updated to latest version), I have a bluetooth dongle in the usb port; I have installed bluez-libs and bluez-utils (and python-bluez).  They show up as version 5.13.  hciconfig and hcitool work properly.  There does not seem to be any utility installed to pair with a device, nor can I figure out how to get pairing to work by editing config files.

I can find the device with hciconfig and hcitool, but rfcomm can't connect without the pin.  If I try the same sequence on my Linux laptop after pairing with the gui, rfcomm is able to connect, so I know the device is working properly (JY-MCU HC-06 on another Arduino).

All the recommendations I can find on the web indicate I should be able to use simple-agent or bluez-simple-agent, but they are not installed with these packages (there is no bluez-tools package for this distro).  If I manually copy the python script for the agent to the device and run it, it fails, saying that org.bluez can't be found with dbus.  There is no bluetoothd running, and no init script for any bluetooth demon.  None of the bt* tools are available.

I also found a description of how to set a pin code in /var/lib/bluetooth/[bt-addr]/pincodes (where bt-addr is my dongle address) containing a line of the form:

[device-addr]  [pincode]

but this seems to have no effect.

I have also tried settings in /etc/bluetooth/main.conf and /etc/bluetooth/rfcomm.conf, but I think they may only be for incoming connections.

Any help would be greatly appreciated.

It takes me some time to make it work :

1) update drivers

opkg update

opkg install kmod-bluetooth bluez-libs bluez-utils

2) add configuration files in directory /etc/bluetooth

root@Arduino:~# cat /etc/bluetooth/hcid.conf

options {
  autoinit yes;
  security auto;
  pairing multi;
  passkey "0000";
   }
device {
  name "OpenWrt";
  class 0x000100;
  lm accept,master;
  lp rswitch,hold,sniff,park;
  }

root@Arduino:~# cat /etc/bluetooth/rfcomm.conf

rfcomm0{
 bind yes;
 device 00:1B:C1:02:B0:F5;
 channel 1;
 comment "Holux M-1000";
 }

3) Reboot the card

4) test if all is OK

hciconfig

5) put the interface up

hciconfig hci0 up

6) Search for devices

hcitool scan

7) Look for Serial Port capability on the devices

sdptool search SP

8) bind the serial dev

rfcomm -i hci0 connect /dev/rfcomm0 00:1B:C1:02:B0:F5

9) see the information comming from the device (bluetooth GPS in my case)

cat /dev/rfcomm0

Bluetooth support on OpenWRT is broken, simply does not work.


How do I print multiple variables in a string? Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?

Currently I do something like this:

Serial.print("Var 1:");Serial.println(var1);
Serial.print(" Var 2:");Serial.println(var2);
Serial.print(" Var 3:");Serial.println(var3);

Is there a better way to do this?

ardprintf is a function that I hacked together which simulates printf over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.

It can be called similar to printf. See it in action in this example:

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

void loop()
{
  int l=2;
  char *j = "test";
  long k = 123456789;
  char s = 'g';
  float f = 2.3;

  ardprintf("test %d %l %c %s %f", l, k, s, j, f);

  delay(5000);

}

The output as expected is:

test 2 123456789 g test 2.30

The function prototype is:

int ardprintf(char *, ...);

It returns the number of arguments detected in the function call.

This is the function definition:

#ifndef ARDPRINTF
#define ARDPRINTF
#define ARDBUFFER 16
#include <stdarg.h>
#include <Arduino.h>

int ardprintf(char *str, ...)
{
  int i, count=0, j=0, flag=0;
  char temp[ARDBUFFER+1];
  for(i=0; str[i]!='\0';i++)  if(str[i]=='%')  count++;

  va_list argv;
  va_start(argv, count);
  for(i=0,j=0; str[i]!='\0';i++)
  {
    if(str[i]=='%')
    {
      temp[j] = '\0';
      Serial.print(temp);
      j=0;
      temp[0] = '\0';

      switch(str[++i])
      {
        case 'd': Serial.print(va_arg(argv, int));
                  break;
        case 'l': Serial.print(va_arg(argv, long));
                  break;
        case 'f': Serial.print(va_arg(argv, double));
                  break;
        case 'c': Serial.print((char)va_arg(argv, int));
                  break;
        case 's': Serial.print(va_arg(argv, char *));
                  break;
        default:  ;
      };
    }
    else
    {
      temp[j] = str[i];
      j = (j+1)%ARDBUFFER;
      if(j==0)
      {
        temp[ARDBUFFER] = '\0';
        Serial.print(temp);
        temp[0]='\0';
      }
    }
  };
  Serial.println();
  return count + 1;
}
#undef ARDBUFFER
#endif

**To print the % character, use %%.*

Now, available on Github gists.

int Money_amount = 55;

Serial.print(String("New amount: $" + Money_amount));

You will see on terminal:

New amount: $55


Measure total microcontroller current? So I have a Duemilanove board and am utilizing 7 output pins, I power a Pixy camera and pan/tilt servos from the ICSP header, i also power an HC-SR04 sonar snsor directly from the board.
Of those 7 output pins, 4 are PWMs for the motors (don't ask why), 3 are for servo control (tower pro mg-995)
when I try to output these 7 pins simultaneously things don't work, i get "components at a time" behavior. Like servos turn first, then the motors spin (servos stopped).
Initially we thought it must be a power supply problem (8 1.2v NiMh bat series) which powers the l298n h bridges (two of them) and also powers the board and servos. But now im starting to fear that it's the board itself and that it can't handle simultaneous outputs.
I've read from here (method #10) that taxing the board more than 200mA is a problem. But what exactly happens if you do just that? And is my case exactly like this one? If so, how to fix it?

Edit +

Here's how the circuit looks.

Edit:
Yes i do think there is a need for decoupling capacitors but im not sure where to put them. They dont seem to work. The bounty goes to the best answer on the proper decoupling of this circuit.
Edit:
Here's some images on the Pixy camera

Edit:
Actually from the original problem I noted when I posted this question, things don't work as expected. WHen the big servos move, the pan/tilt camera don't move when they are supposed to, or the motors briefly stop. I'm wondering if is also an Arduino idiosyncrasy because when I don't run the servo.attach(servo_pin)  code everything works fine.

My experience of high power draw from an Arduino is that it endlessly re-boots so maybe not the issue for you.

The Servo library and PWM pins are probably sharing the same timer therefore motors stop while servos are running.

You could try a different Servo library.

This article is useful to understand the timer/pwm/pin relationships

When power goes through a wire, it heats up the wire. The more current you draw, the more it heats up. The "wires" inside a chip such as the one that adjusts the power aresmall, which means it heats up more, and also it takes less to burn it out.

A fuse is essentially a very thin wire. If you draw too much current (amps) through it, it will burn out (melt the wire). Wires inside a chip or on a PCB are much the same, It may recover when it cools down, or not. Some devices have protection, some do not - you may find the arduino shuts itself off to protect itself, to restart after a period. Or it may not.

As has been suggested, you can bypass the board to power the h-bridge - there should be one or two pins to power the h-bridge separate from the signalling, specifically for this reason.

Also, if the board is powered by batteries, the batteries may not be able to supply the current, causing one or more parts not getting enough power.

If you do bypass the voltage regulator and use power directly from the power source, remember that you are using a different voltage - the voltage from the power source, not +5v.

If you are powering your board from USB, then be aware that there are limitations to the power able to be supplied via USB - the USB specs say 150milliamps; any higher power has to be negotiated with the host (PC), so you may get different answers for a laptop vs. a desktop vs. a mains power adapter.


nRF24L01+ RF24 library - can send but can't receive I'm prototyping out a board with temperature, humidity, windspeed sensors, and using an NRF2401+ board to send values to a Raspberry Pi base station that will record the data.

Using a Leonardo clone board, I'm able to successfully run the pingair_dyn sketch to send test payloads to the RPi and receive acks.  (So I know the RPi can send and recieve OK.)

Moving the same NRF2401+ to a breadboard setup with an ATMEGA328P-PU, the same sketch can send payloads which are received on the RPi, but always hits the timeout trying to get the ack (which the RPi is dutifully sending).

In fact when running pingair_dyn as a receiver, it just spins in the loop waiting for radio.available() to return true, which it never does.

The immediate problem is that radio.available() is always returning false.  So basically I can send but can't receive.

I have checked my wiring several times, and I'm mostly confident that it's right.

  CE - physical pin 14 (arduino digital pin 8 )
  CSN - physical pin 13 (arduino digital pin 7)
  SCK - physical pin 19, per atmega328 datasheet
  MOSI - physical pin 17, per datasheet
  MISO - physical pin 18, per datasheet

In the software, I construct the RF24 instance:

  RF24 radio(8,7);

Any ideas?  I tried swapping CE <--> CSN, then nothing worked.  Is there some wiring problem that would cause XMIT to work but RECV to fail?

I've tried putting a 2.2 uF capacitor across the 3.3V - GND as I've seen mentioned in other threads, but no difference.

Any suggestions on what is useful information to dig out of the RF24 library to give some idea of what's going on?

More background

Here is the RF24 debug info from the mega328

STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1    = 0xf0f0f0f0d2 0xf0f0f0f0e1
RX_ADDR_P2-5    = 0xc3 0xc4 0xc5 0xc6
TX_ADDR       = 0xf0f0f0f0d2
RX_PW_P0-6    = 0x20 0x20 0x00 0x00 0x00 0x00
EN_AA       = 0x3f
EN_RXADDR    = 0x02
RF_CH      = 0x4c
RF_SETUP    = 0x07
CONFIG       = 0x0f
DYNPD/FEATURE    = 0x3f 0x04
Data Rate    = 1 MBPS
Model       = nRF24L01+
CRC Length    = 16 bits
PA Power    = PA_MAX

Here is the debug info from the base station (Raspberry Pi):
pyRF24/examples/pingpair_dyn/

================ SPI Configuration ================
CSN Pin          = CE0 (PI Hardware Driven)
CE Pin           = Custom GPIO22
Clock Speed      = 8 Mhz
================ NRF Configuration ================
STATUS           = 0x0e RX_DR=0 TX_DS=0
MAX_RT=0 RX_P_NO=7     TX_FULL=0         RX_ADDR_P0-1     =
0xe7e7e7e7e7 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR          = 0xe7e7e7e7e7
RX_PW_P0-6       = 0x00 0x00 0x00 0x00 0x00 0x00
EN_AA            = 0x3f
EN_RXADDR        = 0x03
RF_CH            = 0x4c
RF_SETUP         = 0x07
CONFIG           = 0x0e
DYNPD/FEATURE    = 0x3f 0x04
Data Rate        = 1MBPS
Model            = nRF24L01+
CRC Length       = 16 bits
PA Power         = PA_MAX

The pins could be wrong for ATMega328.

It should be.

NRF24L01 - Arduino UNO
GND - GND
VCC - 3.3V
CE - 7
CSN - 8
SCK - 13
MOSI - 11
MISO - 12

or B. You need to connect a 500uF electrolytic capacitor to your NRF24L01+ VCC and GND pins directly. To reduce noise related issues. With clone arduinos/cheap regulators/clone NRFs then noise might start creating issues especially with receiving.

This is my simple code(sending and receiving)to control a servo by joystick,hope to help you.

//sending code

*include "SPI.h"

*include "NRF24L01P.h"

*define JOYSTICK_PIN A0

NRF24L01P rf24l01p;

uint8_t buffer[24];

uint8_t to[5] = {0x11, 0x22, 0x33, 0x44, 0x02};

uint8_t addr[5] = {0x11, 0x22, 0x33, 0x44, 0x01};

int8_t ret;

int val;

int pos;

void setup()

{
    Serial.begin(9600);

    rf24l01p.begin(27, 53, PWR_0dBm, AIR_RATE_2Mbps, 50, addr);
}

void loop()

{

    val = analogRead(JOYSTICK_PIN);

    pos = map(val, 0, 1023, 0, 179);

    buffer[0] = pos;

    rf24l01p.send_packet(to,buffer);

    delay(100);
}

...

//receiving code

*include "SPI.h"

*include "NRF24L01P.h"

*include "Servo.h"

*define SERVO_PIN 2

Servo myservo;

NRF24L01P rf24l01p;

uint8_t buffer[24];

uint8_t from[5] = {0};

uint8_t addr[5] = {0x11, 0x22, 0x33, 0x44, 0x02};

void setup()

{

    Serial.begin(9600);

    myservo.attach(SERVO_PIN);

    myservo.write(90);

    delay(100);

    rf24l01p.begin(9, 10, PWR_0dBm, AIR_RATE_2Mbps, 50, addr);

}

void loop()

{

    rf24l01p.recv_packet(from, buffer);

    if (buffer[0] >= 0 && buffer[0] <= 179)

    {

        myservo.write(buffer[0]);

        delay(15);

    }

}


Evaluating delay for Xbee I will explain my task in a simplified way. I'm communicating among 3 Xbee's.

The attached code is for the sender Xbee. This Xbee actually sends multiple values of value1 (here for simplification I assigned it to constant value 10). For finding the value1 it does some other calculations as well and then assigns it.

But I find that if I reduce or remove the delay(100) I end up receiving improper values. I guess delay gives a buffer time for data transmission but my question is how to do I calculate the minimum delay or how can justify that this is the delay needed ?

I hope you can understand my question. If not please comment I will give some more pertinent details.

  // Sender Xbee
    void setup()
    {
    Serial.begin(9600);
    }
    void loop()
    {
    int value1 = 10; // some hardcoded values to send
    Serial.print('H'); // unique header to identify start of message
    Serial.print(value1,DEC);
    Serial.print(","); // note that a comma is sent after the last field
    Serial.print('\n'); // send a cr/lf
    delay(100);
    }

Based on my experience with Xbee, I would say the limit is 50ms as Xbee can do the lowest sampling rate of 50ms.


Not understanding C++ arrays I'm attempting to re-write a library for the CD74HC4067 multiplexer.  There is a library available for this device on the Arduino Playground, however, it's limited in its functionality.

I have this as a private data member in the class header file:

uint8_t channelSelects[16][4];

And this in the class constructor:

CD74HC4067::channelSelects[16][4] = {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
};

And I'm getting this error:

cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka unsigned char}'

Could someone please explain what I'm not understanding here ?

Many thanks in advance.

If you have in your constructor this:

CD74HC4067::channelSelects[16][4] = ...

then you are trying to assign something into the element at position [16][4]. Thats why it's telling you

  cannot convert '' to 'uint8_t {aka
  unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like  0b00001000 ...

And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.

However if you want to rely on this array, the constructor should look like:

CD74HC4067::CD74HC4067() :
  channelSelects {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
  }
{
   // constructor code
}

(maybe one more {} enclosure, I'm not sure right now exactly)

EDIT: I'd go this way (if you need only one or two instances):

// ADC READ channel + Address selection pins
template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
class Mux16b {
public:
  void initPins () {
    pinMode(Addr0, OUTPUT);
    pinMode(Addr1, OUTPUT);
    pinMode(Addr2, OUTPUT);
    pinMode(Addr3, OUTPUT);
    pinMode(ADC_Chan, INPUT);
  }

  int readMux(uint8_t channel) {
    digitalWrite(Addr0, channel&1 != 0);
    digitalWrite(Addr1, channel&2 != 0);
    digitalWrite(Addr2, channel&4 != 0);
    digitalWrite(Addr3, channel&8 != 0);
    // maybe some delay to stabilize voltage at the ADC_Chan input ??
    return analogRead(ADC_Chan);
  }

  // not necessary but it's easier to use   mux(10) than mux.readMux(10)
  int operator()(uint8_t channel) { return readMux(channel); }
};

// analogRead from A0, Address pins: 4 9 5 2
Mux16b<A0,4,9,5,2>  mux;

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

void loop() {
  Serial.println(mux.readMux(15));

  Serial.println(mux(12)); // using overloaded operator ()

  delay(5000);
}


Can I use Visual Studio instead of Arduino IDE? I think that Visual Studio is a great product! I find the Arduino IDE is limited in its features. For example the Arduino IDE does not have:

Code prediction
Error highlighting
Previews of #define values
Peek at code definition
Jump to code definition
and many more...

Since the Arduino ino & pde file types are basically C++, Can I use the Visual Studio IDE instead of Arduino IDE?

To be considered as a replacement, Visual Studio must be able to:

Save & open ino & pde files.
Compile my code.
Download my code.
Use existing/custom libraries from the Arduino IDE.
Detect and display an Arduino project.

I would consider these features as a bonus:

Arduino board selection.
Debugging

Variable watch window
Breakpoints
Step through code

Simulation
Open the Arduino Examples
Automatic board detection
Serial Monitor

I only use Visual Studio for Arduino programming.
Arduino Plugin for Visual Studio

It's not exactly what you are asking, but maybe you would be willing to consider a solution based on Eclipse?

Eclipse has the advantage of being cross platform, so you can have the same experience no matter what your OS might be.

Although, for the sake of completeness, almost all you mentioned can be done even with vim, if adequately configured. But I wouldn't recommend it as first choice, if you have never used it before.


SIM800L module just repeating data sent via serial I've got a Teensy 2.0 with simple AltSoftSerial as displayed on image:

As you can see, when I send a command (or any other input via serial) the SIM800L module sends me the same input. I tried to switch the TX and RX wires on the module (in case I misconnected them), but then it returns nothing. When I connect the TX and RX wires directly to each other I've got the exact same result as if they are connected to the module.

The whole thing is connected in this way - computer is connected via USB to teensy, the SIM800L and Teensy are connected via software serial (RX to TX and TX to RX), the SIM800L module is powered from an external battery (it requires specific voltage between 3v4 and 4v4).

Is the module bad, or is it a wrong wiring? Why is the module not communicating and just returning what I sent to it?

EDIT 1:

I'm not particularly looking for mistakes in code, the code is most likely correct. I think the problem is probably somewhere around the SIM800L module.

The module shouldn't just repeat what it got, but it should replay with something like OK, or other answers.

You are asking it to repeat the data you sent. It working AS you wanted it to work in your program.

You asked it to see if there is anything sent and if there was, then print it. That's whats it's doing.

The USB serial connection is the same as the TX and RX pins on the arduino. You have to connect your sim800 on another serial port by using SoftwareSerialport, see examples here : https://www.arduino.cc/en/Tutorial/SoftwareSerialExample


Hardware Interrupt Triggered Randomly So there is this pretty generic part of my project that involves triggering an ISR that will flip a boolean value. I have set up the software side like so:

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), displayConvergence, FALLING);
}

void loop() {
  if(flashConvergence) {
    //Do stuff that takes several seconds
    delay(3000);
    flashConvergence = false;
  }
}

void displayConvergence() {
  if (!flashConvergence) {
    flashConvergence = true;
  }
}

The schematic is as follows:

simulate this circuit – Schematic created using CircuitLab

But the behavior of my circuit surprised me as the pin interrupt would get triggered randomly at a frequency at (guessing here) 3 times a second.

Weird, I thought. I fiddled around and found that when the boost converter's 180V is not connected to any load, the interrupt service triggers as expected, as in it starts working correctly. So I thought perhaps the issue was some noise introduced by the boost converter.

I modified the circuit by adding a capacitor across the switch:

simulate this circuit

I tried 1 uF at first, but that didn't help and neither did 10 uF. However, when I tried 100 uF (I thought decoupling capacitors are usually 0.1uF to 1 uF, is the value I am using too big?), things seem to be working as expected with the exception that when I hold the switch in the closed position for a long time, then let it go back in the open position, the interrupt service can be triggered randomly for a short period right after I let go of the switch.

Is my initial assumption that the ISR is triggering randomly due to EMI from the boost converter correct? Perhaps there are other causes I am not looking at? Is there a way to make this work 100% (as in solve the issue right after the switch is put in the open position)?

Thanks for the help!

It has come to my attention I never posted a followup to this but I was actually able to solve this problem by shielding the wire going from the switch to the arduino. The switch's wire was about 2 to 3 inches long and I wrapped aluminum foil around it, which shielded the signal from what I suspected was EMI induced by the switching converters.

An alternative approach is to detach the interrupt handler and use the internal pullup instead of external resistor (and capacitor).

const int BUTTON = 2;
volatile bool flashConverage = false;

void setup()
{
  setmode(BUTTON, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(BUTTON), displayConvergence, FALLING);
}

void loop()
{
  if (!flashConvergence) return;

  // Do stuff that takes several seconds
  delay(3000);
  flashConvergence = false;
  attachInterrupt(digitalPinToInterrupt(BUTTON), displayConvergence, FALLING);
}

void displayConvergence()
{
  detachInterrupt(digitalPinToInterrupt(BUTTON));
  flashConvergence = true;
}

The processing ("stuff that takes several seconds") will debounce the button (or at least ignore it :).

Cheers!


void loop() stops running after an hour or so So I have a program that measures temperature and humidity over time. Here isthe code I use:

#include <SD.h>
#include <SPI.h>
#include <DHT.h>
#include <Wire.h>
#include "RTClib.h"

#define DHTPIN 2
#define DHTTYPE 22
const int chipSelect = 10;

DHT dht(DHTPIN, DHTTYPE);
RTC_DS3231 rtc;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("DHT22 sensor reading");

  if(! rtc.begin()) {
    Serial.println("Could not find RTC");
    while(1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
}

void loop() {

  //temperature measurements
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();

  if( isnan(temp) || isnan(hum )) {
    Serial.println("Failed to read from DHT22 sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(hum);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println(" *C");

  //determining the date
  DateTime now = rtc.now();

  int dayy;
  int monthh;
  int yearr;

  int hours;
  int minutes;
  int seconds;

  String date;
  dayy = now.day();
  monthh = now.month();
  yearr = now.year();
  date = String(dayy) + String(monthh) + String(yearr);

  int seconds_passed; // how many seconds have passed since the start of the day: used for the data plot
  hours = now.hour();
  minutes = now.minute();
  seconds = now.second();
  seconds_passed = ((hours * 60) + minutes)* 60 + seconds;

  //writing to SD card

  if(SD.begin(chipSelect)) {
    Serial.println("Card is initialized! Ready to go!");
  }
  else {
    Serial.println("Error with initializing the card!");
    return;
  }
  Serial.println("Opening file...");
  String FileName;
  FileName = date + ".dat";

  File dataFile = SD.open(FileName, FILE_WRITE);

  if (dataFile) {
    dataFile.print(temp);
    dataFile.print(",");
    dataFile.print(hum);
    dataFile.print(",");
    dataFile.println(seconds_passed);
    dataFile.close();

    Serial.println("Written data to file and closed it");
    Serial.println(" ");
    Serial.print("Seconds passed: ");
    Serial.println(seconds_passed);
    Serial.println(" ");
  }
  else {
    Serial.println("Error with opening the file, trying again");
  }

 delay(1000);
}

It works like a charm, but for the fact that it stops running after an hour, maybe 1,5 hours.

Resetting the board seems to work, but I can't obviously sit there the whole time and reset the board. I use an Arduino Due. Did I program something wrong that something overflows or should I add some more code?

A year ago I had the same problem, it seems there is a bug with the String library. I recomed you this:
1- Easy: use the String library on development, but for the "release" change everything to use C native strings (char name [SIZE])
2- Complex (and worse in my op.): set an interrupt every half an hour (or whenever with margin before it crashes) that activates an output connected to the reset pin of the Arduino. I've seen this on the internet but couldn't make it work.
Link to Arduino Forum's thread


Speed sensors for sport Fair warning: I'm a newbie when it comes to Arduino, so if I'm not too great at describing things, let me know so I can learn!

I have recently built a fairly accurate laser timer to time sprinters through a section of a soccer pitch, giving a nice reading of their average speed through the zone.

The limitation is that we would love to be able to see their speed as a progressive measurement throughout the sprint.

My problem? I have NO idea where to start. Google has so far come up empty...

All I have is the following link, Best of the 2015 NHL All-Star Skills Competition, illustrating the sort of thing we would like to accomplish. The bit in question starts at around 0:35 when they are talking about sensors in the players' jerseys.

Any one able to point me in the right direction?

Kinovea is good but this would be post processing not live. You need record video and then you can track each runner on time. Another one is Typhon program but it involves programming and calibrating (then you can track live).

Your best bet would be to use a module of Gyro, Accelerometer and Magnetometer much like MPU-9150. These devices communicate using I2C and you can log in data about the direction and the change in direction as well as acceleration. Using this data you can easily find out the speed in a particular direction and even overall data like the average speed, distance travelled, etc.

Another idea is using the accelerometer to measure a jerk.A jerk can be taken as a footstep and using appropriate calculations you can find out how much a person has moved throughout the sprint.

You can use ultrasonic sensors too which would tell you the position of the sprinter from a point but they have their disadvantages like small pressure changes due to air will affect the readings and you won't get accurate reading.


Unexpected Delay Between For Loops I made some arduino code for leds that blink down a row and then back again, but when the program is run, there is an approximately 2 second delay in between the first for loop and the second. This is my code in the loop function:

int leds[] = {13, 12, 11};
int i;

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

  for (int i = 0; i < sizeof(leds); i ++) {
     pinMode(leds[i], OUTPUT);
  }
}

void loop() {
    for (i = 0; i < sizeof(leds); i ++) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
    for (i; i > 0; i --) {
       digitalWrite(leds[i], HIGH);
       delay(250);
       digitalWrite(leds[i], LOW);
    }
}

It really makes the program look weird when the LEDs are blinking on a breadboard. Keep in mind that this only happens after the first for loop, the second is continuous back to the first. Any idea why this might be and how to fix it?

The claim “The cause it that your 3rd led (2nd element in the array) is reapeted twice” is wrong.

Apparently that sentence is supposed to mean that the long delay is due to i being one too large, coming out of the first loop and entering the second one.  Indeed, i is too large, but that's because each element of the array is a 2-byte int, so that instead of for (int i = 0; i < sizeof(leds); i ++) being equivalent to for (int i = 0; i < 3; i ++), it is equivalent to for (int i = 0; i < 6; i ++).

Thus, one second goes by with an extra 4 occurrences of delay(250); in the first loop, and another one second with 4 extra occurrences of delay(250); in the other loop.

To correct the problem, write sizeof leds/sizeof leds[0] instead of sizeof(leds), and write for (--i; i > 0; i--) instead of for (i; i > 0; i --).

The cause it that your 3rd led (2nd element in the array) is repeated twice.

Try this instead:

int leds[3] = {13, 12, 11};

void setup() {
  for (int i = 0; i < 3; i++) {
    pinMode(leds[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < 2; i++) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
  for (int i = 2; i > 0; i--) {
    digitalWrite(leds[i], HIGH);
    delay(250);
    digitalWrite(leds[i], LOW);
  }
}


Generate 1.7 Mhz with PWM in Uno? I have this code:

void setup() {
  pinMode(11, OUTPUT);
  TCCR2B = 0;
  TCNT2 = 0;
  TCCR2A = _BV(WGM21);
  TCCR2A |= _BV(COM2A0);
  OCR2A = 249;
}

void loop() {
  soundBuzzer();
}

void soundBuzzer() {
  TCCR2B |= _BV(CS21);
}

void silenceBuzzer() {
  TCCR2B &= ~_BV(CS21);
  TCNT2 = 0;
}

(Got it from here).

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:

period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency

frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an even number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:

const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set PERIOD to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.

Edit: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the Trinket or the Digispark.

This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:

64 MHz ÷ 38 = 1.684 MHz

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.

configure the timer into one of the pwm mode and 50% dc, all in the setup().

ATtiny85 family has a PLL oscillator and is better suited for this.


Which sensor to detect light? I have a kit of 37 sensors as described here:

http://www.instructables.com/id/Arduino-37-in-1-Sensors-Kit-Explained/?ALLSTEPS
https://tkkrlab.nl/wiki/Arduino_37_sensors

I want to create a simple circuit:

if the light is detected - flash LED
if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...

Can you please advise me which sensor to get?

Shall I get a photocell  (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?

Number 23 in the list says photoresistor, corresponding to module KY-018 in your kit, which is what you called photocell (a photocell is another type of sensor to my knowledge).
As the name states, a photoresistor is a device changing it's resistance depending on the amount of light it detects/receive.

A photoresistor usually looks like:

In order to get a meaningful reading from an LDR you need to convert the resistance into a voltage which the Arduino's ADC can read. The simplest method is to use a voltage divider: the junction between the LDR (photoresistor) and R1 is the node to connect your analog pin to get your readings, which will be a voltage that is a proportion of the supply voltage (5V) defined by the ratio of the two resistances.

The KY-018 module mentioned above already provides all the necessary and provides you 3 pins: 5V, ANALOG and GND.

simulate this circuit – Schematic created using CircuitLab

No,  I would suggest you not bother with photocell, phototransisters nor light-dependent resistors.

Better answer is the 1750 light-detection and measurement module.

It connects by I2C and reads out a numeric value corresponding to the amount of light (Lux) it senses.

Very easy to set up.

I use one to measure the light of the sky so I can compare it to the output of my solar cells.

Here is a cool light meter project (complete with hookup instructions and code) that uses one to sense light and displays the results on a 7-segment display:

BUILDING A SIMPLE DIGITAL LIGHT METER USING ARDUINO AND BH1750FVI SENSOR


Not sure if my Arduino Uno is damaged When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:

avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

when I go to Tools > ports I can't find the USB port.
The Arduino still working and green ligh is on, so what is the problem exactly?

Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.

Try rebooting your Mac.

If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.

I was also facing this type of issue. But it has resolved itself now. I go to Tool >> Select Port after Select USB modem its work fine.


Can't get call / message from A7 gsm+gprs+gps module I am making a project using arduino uno & A7 gsm+gps+gprs module.my circuit connection is like this:

A7 UTXD -> arduino RX
A7 RTXD -> arduino TX
A7 GND -> arduino GND
A7 pwr_key -> A7 VCC5.0

When i make call from my mobile to A7,it's ok.But i cannot get call/msg from A7.
Here is my code for making call:

char phone_no[]="phone_no";

void setup()
{
Serial.begin(9600);
delay(200);
Serial.println("AT");
delay(1000);
Serial.print("ATD");
Serial.println(phone_no);
//Serial.println(";");
delay(10000);
Serial.println("ATH");
}

void loop()
{
}

What can i do now??? Please help me to fix it.I apologize for my poor english.

Increase your second delay to 2000 (ie. 2 seconds).

delay(2000);


Boolean function call with character pointer input - dont understand how to get updated pointer value Thank you for everyone's help in trying to find a solution. This library I'm working with was prewritten and is one of the most buggy hardware libraries I've had the misfortune to use. I have now solved to problem by reusing the response parsing code from the library and rewriting my own sequence to return the number using a completely different approach. Many Thanks again!

I am currently attempting to understand how this function works and am struggling. I want to be able to access the 'number' variable in my main function but currently when I do that I get nothing (as in "") when I try to printout the variable with:

Serial.println(incomingNumber);

I am currently preassigning the number as:

char incomingNumber[14];

at the top of my project file.
With a class initial setup of:

DFRobot_SIM808 sim808(&Serial);

I'm then later calling the function like this:

if(sim808.isCallActive(incomingNumber)){Serial.println(incomingNumber);}

This seems like I'm currently making a fundamental error in understanding data types but I'm a bit lost so any help would be really appreciated.

I havent included my entire project here because its currently quite long and spread across both the main and some library files but if anyone needs more info please ask and I'll upload the extras.

The function from the library I'm working with is included below:

bool DFRobot_SIM808::isCallActive(char *number)
{
char gprsBuffer[46];  //46 is enough to see +CPAS: and CLCC:
char *p, *s;
int i = 0;

sim808_send_cmd("AT+CPAS\r\n");
/*Result code:
    0: ready
    2: unknown
    3: ringing
    4: call in progress

  AT+CPAS   --> 7 + 2 = 9 chars
            --> 2 char
  +CPAS: 3  --> 8 + 2 = 10 chars
            --> 2 char
  OK        --> 2 + 2 = 4 chars

  AT+CPAS

  +CPAS: 0

  OK
*/

sim808_clean_buffer(gprsBuffer,29);
sim808_read_buffer(gprsBuffer,27);
//HACERR cuando haga lo de esperar a OK no me har閾哸 falta esto
//We are going to flush serial data until OK is recieved
sim808_wait_for_resp("OK\r\n", CMD);
//Serial.print("Buffer isCallActive 1: ");Serial.println(gprsBuffer);
if(NULL != ( s = strstr(gprsBuffer,"+CPAS:"))) {
  s = s + 7;
  if (*s != '0') {
     //There is something "running" (but number 2 that is unknow)
     if (*s != '2') {
       //3 or 4, let's go to check for the number
       sim808_send_cmd("AT+CLCC\r\n");
       /*
       AT+CLCC --> 9

       +CLCC: 1,1,4,0,0,"656783741",161,""

       OK

       Without ringing:
       AT+CLCC
       OK
       */

       sim808_clean_buffer(gprsBuffer,46);
       sim808_read_buffer(gprsBuffer,45);
        //Serial.print("Buffer isCallActive 2: ");Serial.println(gprsBuffer);
       if(NULL != ( s = strstr(gprsBuffer,"+CLCC:"))) {
         //There is at least one CALL ACTIVE, get number
         s = strstr((char *)(s),"\"");
         s = s + 1;  //We are in the first phone number character
         p = strstr((char *)(s),"\""); //p is last character """
         if (NULL != s) {
            i = 0;
            while (s < p) {
                number[i++] = *(s++);
            }
            number[i] = '\0';
         }
         //I need to read more buffer
         //We are going to flush serial data until OK is recieved
         return sim808_wait_for_resp("OK\r\n", CMD);
       }
     }
  }
}
return false;
}

You can't use Serial.println(array);. In fact, I'm not even sure how the compiler even let you do this...

A better approach would be to use Serial.write(array, sizeof(array));

Also, in order to ensure the function is even executing that portion of the code in the first place, you should but some debugging prints in the code. Like this:

     if (NULL != s) {
        i = 0;
        while (s < p) {
            number[i++] = *(s++);
            Serial.write(number[i++]); //-------- debug
            Serial.print(' '); //-------- debug
        }
        number[i] = '\0';
        Serial.println(); //-------- debug
     }

Also, proper use of whitespace is your friend ;)


How to produce multiple DC voltages for a single project So the title pretty much says it all, but for an example, I have an arduino board, 5-12 V, an LED bank 18 V, and an ultrasonic mister 24 V.

I know some brute force methods to power them from one outlet, but I was wondering if there is a more elegant way to get the voltage for each device with only one transformer instead of three. The solutions I've come up with are less than elegant, and only moderately compact.

I was just wondering what solutions you guys have employed and hoped I could find something helpful.

First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V.  You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use these).

That 5V can then be fed direct into the Arduino.

Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.

Typically you'll only have a single transformer in this sort of design, to get you down to your highest DC voltage. Then you'll create lower voltage rails from that. You can use any number of approaches depending on your needs, e.g. capacitive dropper (on the 24Vac output of the transformer), resistor divider (on your rectified 24Vdc).

But, most typically for hobbyist projects you'll want to be using a regulator IC, either a linear regular/LDO (low noise but poor efficiency) or a separate onboard SMPS IC (good efficiency but typically noisy).


Can tx and rx pins on the uno be used like regular digital pins? The uno has digital pins marked 0-13.

0 is marked as rx and 1 is marked as tx.
Can these two pins be used as regular digital pins if i am short of digital pins?

Yes you can perfectly use these 2 pins as long as your program does not use Serial.

EDIT: Serial data over USB goes through copper traces connected to the rx and tx pins, connecting them to the USB to serial converter chip.

You can, but it will disable the serial port.


What happens if there is a runtime error? What happens if there is a runtime error in a program? Will execution of the program just stop? Is there some way I can get the Arduino to tell me what the error is?

First, let's see a few examples of what can go wrong.

Uninitialized local variables

void setup() {
  int status;
  pinMode(13, OUTPUT);
  digitalWrite(13, status);
}

As pointed out by Edgar Bonet in the comments, local variables like status in the code above are not implicitly initialized by the C++ compiler. So, the outcome of the code above is indeterminate. To avoid that, make sure you always assign values to your local variables.

Things are a bit different with global and static variables:

  Global and static variables are guaranteed to be initialized to 0 by the C standard.

Source:
AVR Libc Reference Manual - Frequently Asked Questions - Shouldn't I initialize all my variables?

That means you shouldn't worry about initializing them to 0 in your code. In fact, you should really avoid it, as the initialization may waste memory. Only initialize them to values other than 0.

Memory overflow

int array[10];
int v = array[100];
array[-100] = 10;

The first problem here is that you don't know what will be assigned to v, but worse is that you don't know what you messed up with the assignment to position -100 of array.

Jump to an illegal instruction

void doSomething( void ) {
    for (int i = 0; i < 1000; i++);
}

void setup ()
{
    void (*funcPtr)( void );

    funcPtr = &doSomething;
    funcPtr(); // calls doSomething();

    funcPtr = NULL;
    funcPtr(); // undefined behavior
}

The first call to funcPtr() will actually be a call to doSomething(). Calls like the second one may lead to undefined behavior.

Other bad things that may happen

Well, you can run out of RAM, for example. What else. In any case, I think your program will keep running, probably not the way you intended it to.

Kinds of Protection

In computer systems, problems like these are usually dealt with at various levels:

By the compiler
By the programming language runtime (as in Java for example).
By the operating system or the processor (if your memory access a position outside the boundaries of the address space reserved to your program, the OS or the processor may have safety mechanisms to prevent that)

Arduinos only have limited protection of the compiler, and probably nothing else. The good news is that they aren't multi-tasked, so the only program being affected is yours. In any case, any of those bugs will lead to erratic behavior.

The Answers

The assumptions are the all of the problems I stated above are runtime problems.

  What happens if there is a runtime error in a program?

The program will continue and what happens will depend on the side-effects of the runtime error. A call to the null function pointer will probably make the program jump to an unknown location.

  Will execution of the program just stop?

No, it will keep going as if nothing extraordinary happened, probably doing what you didn't intend it to do. It may reset or act erratically. It may turn some inputs into outputs and burn a sensor or two (but that's highly unlikely).

  Is there some way I get the Arduino to tell me what the error is?

I don't think so. As I said earlier, the protection mechanisms aren't there. There's no runtime support from the language, no OS, no hardware checks for out-of-bounds memory access (the bootloader doesn't count as either). You just have to be careful with your program and probably set your own safety nets.

The reason for the lack of protection is probably because Arduino controllers are too cheap, have too little memory, and should not run anything too important (yes, there seems to be a disclaimer by AVR somewhere for you not to use the MCUs normally used by Arduino in life support systems).

The Arduino will reboot (i.e. it will relaunch setup() and loop()).


Detect if laptop is on or not? How would I safely connect an Arduino so that it can detect if a laptop is on or off?

The Arduino would be powered separately by a normal USB charger, since it needs to be turned on even when the laptop is turned off. So I'm thinking I can connect an input on the Arduino to one of the USB ports on the laptop somehow, but how do I do this safely?

Even if I play it safe and connect a current-limiting resistor between the USB voltage and input pin, and perhaps a voltage divider, is there still a problem with connecting one device to another like this? I'm thinking that since each has its own power supply from mains, could there potentially be a problem if I connect the USB port of the laptop to a pin on the Arduino?

Do need to use an optocoupler or relay between them? Or is there an even better way of doing this that I didn't think of?

If your chosen power supply is of a good quality and provides proper ground isolation then it shouldn't be a problem to connect the grounds of the two systems together.

However, since there are so many bad power supplies available on the internet (and even some "good" power supplies are somewhat iffy when it comes to grounding) it is safest to hedge your bets and add your own galvanic isolation.

The simplest method is to use an opto-isolator.  Use the +5V and GND from your computer's USB port (assuming it's not an always-on charging port - look for a lightning bolt symbol) along with a resistor (470Ω - 1kΩ is good) to drive the LED side of the opto-isolator. The other side then acts as a button to the Arduino:

simulate this circuit – Schematic created using CircuitLab

In this arrangement your input will be LOW when the PC is on. Also R2 could be replaced by the internal pullup of the GPIO pin (pinMode(PIN, INPUT_PULLUP);)

As I say, this most likely won't be strictly necessary, but for the minimal cost of an opto-isolator it's silly not to add that extra layer of protection. After all, an opto-isolator is cheaper than a new Arduino or (heaven forbid) a new laptop.

The only problems are that (a) the Laptop USB outputs 5V, and the arduino input should not exceed 3.3, and (b) when the Laptop is no longer powered, the 5V pin on its USB no longer has a defined state, and could theoretically spike.

Here's a simple and cheap way to do this with passives. The diode isolates the USB from any "back" voltage. The USB 5V is measured across the resistor, and I'd place a capacitor there to to absorb any voltage spikes from the laptop when it loses power. Finally, the second resistor also indirectly protects the digital input and acts like a voltage converter, between the 5V (4.5 after the diode) and the 3.3V the arduino wants to see. The over-voltage will simply be routed to ground via the chips internal protection diodes, and the current will be limited to about 120 microamps ( 4.5- 3.3 ) / 10K.

You could use an opto isolator, but this is a cheap solution that will work. You will have to share ground between the laptop's USB and your arduino (not shown in the diagram). That will not be an issue however. Especially considering all power adapters offer significant line-to-load isolation. By the way, the 1uF capacitor can be decreased to 100nF or less, depending on how quickly you want to respond to the power loss.

simulate this circuit – Schematic created using CircuitLab


Does the reset button work when not powered? I'm working on a project and my dad hit the reset button on my Arduino board, unknowingly. If it wasn't connected to any power source or computer, did it still reset? Do I have to upload my code to the board again? Or does the board need power to be reset?

The reset on an Arduino does not erase anything. It merely restarts execution of an already uploaded program. Also the AVR needs to be powered on for it to realize whether it has been reset.

Every time you power on an Arduino it automatically starts code execution from the beginning of the program in the flash memory.

The reset sets the processor and peripheral registers in initial state. This means that the program counter register (which marks the actual command the processor is working on) will be set to zero so the program starts from the very beginning.

The program is located in the ROM/flash which can only be erased with a flasher tool (in your case when you connect it to your PC) so a reset will not affect the program at all.


How to combine strings and text together? I'm trying to combine two strings (strings/int) together with text in below code:

int foo = String((char*)payload).indexOf(' ');
int message1;
int message2;

message1 = String((char*)payload).substring(0, foo).toInt();
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

client.publish(msg, String(message1 + " " + message2).c_str(), true);
// published value: 1 0

Instead of publishing "1 0" its publishing some weird values, what am i missing?

I wouldn't use the String class, but instead use the C functions to concatenate strings (like strcat, strncat).

You can use the itoa function to convert an integer to a string, see:

  https://stackoverflow.com/questions/9655202/how-to-convert-integer-to-string-in-c

Or use the sprintf function.

These are all standard C functions which gives you complete control of the buffer sizes to use. Handy because the Arduino Uno has just 2 KB.

After spending a good time on searching for an easy understandable formula, I found that i came across this question already in the past and saved the solution in other sketch (attaching it here for the next time!).

Below was the solution that worked now and then perfectly:

int foo = String((char*)payload).indexOf(' ');
int message1;
int message2;

message1 = String((char*)payload).substring(0, foo).toInt();
Serial.print(message1); // Returns 1

message2 = String((char*)payload).substring(foo + 1, length).toInt();
Serial.print(message2); // Returns 0

char combinedval[40];
strcpy(combinedval, String(message1).c_str());
strcat(combinedval, " ");
strcat(combinedval, String(message2).c_str());
client.publish(msg, combinedval, true);

// published value: 1 0


ble_write slows down my sketch causing problems (Blend Micro & NRF8001) I'm working on a prototype which uses the RedBearLabs Blend Micro with the NSC's nrf8001 ble chip, but have ran into a problem that I'm not sure how to solve.

I have two tactile buttons connected to the input pins on the Blend Micro, which are used to increase or decrease counters (integers) in my sketch that is in turn displayed on a OLED screen. When I use these buttons to manipulate the counter in offline mode (meaning that the bluetooth is not connected) I can repeatedly press the buttons very quickly and the counter is increased with every push - but when I connect to my phone and try to push the buttons with high frequency (>1-2 per second) the program is not able to react to every button interaction, causing only every second or third click to be registered.

The only thing that I do differently when I am connected is that I'm sending 5 bytes using "ble_write" (part of the RBL nrf8001 library), which seem to cause this delay resulting in missed clicks. Even sending one byte using "ble_write(X)" seem to slow down the sketch so much that this phenomena occurs.

Do any of you had similar problems and possible ways to solve this? I've been considering batching clicks together until I reach a certain amount and then send them at all once - this however may risk that a button is being pressed at the same time as the ble_write is executed, causing missed click.

Offline click looks like this:

if(digitalRead(A4)) {
while (digitalRead(A4)) {        }
offlineIn++;
localIn++;
totCount++;
sleepTimer = 0;
  }

And the online like this:

if (digitalRead(A4)) {
  while (digitalRead(A4)) {        }
  totCount++;
  localIn++;
  sleepTimer = 0;
  ble_write('0');
  ble_write('0');
  ble_write('0');
  ble_write('1');
  ble_write('1');
}

Thanks!

I've solved it by overclocking my blend micro to 16mhz (done in the Arduino IDE). Not a perfect solution but works. :)


Can I do something like this to simplify the code for arduino? Can I simplify the code in arduino where it doesn't promote any error.
Example:

Int led =13;
Blink = digitalWrite(led, HiGH);
             delay(1000);
             digitalWrite(led, LOW);
             delay(1000);

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

void loop(){
Blink
}

There are indeed some errors.

First, you cannot assign a function body to a variable.

So you have to rewrite the Blink function:

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

Also for calling a function, even without parameters, you should use ( and ):

void loop()
{
    blink();
}

Also you need to use the correct capitals or not:

int led = 13;

You can make it constant since it does not change:

static const int led = 13;

So all together you get:

static const int led = 13;

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

void loop()
{
    blink();
}

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

I suggest you read a book about C or C++ to get used to the syntax.

Also, note that int is written as int, not Int. Case matters.

And this should be byte, vs int, to save on memory:

static const int led = 13;

HiGH should be HIGH, all caps.


for loop running infinitely void writereg() {
  digitalWrite(latchPin, LOW);
  for (int i = 7; i >= 0; i--) {
    digitalWrite(clockPin, LOW);
    Serial.print("wswitch&&&&&&");
    Serial.print(i);
    Serial.print("----------------------");
    digitalWrite(dataPin, switches[i].stat);
    Serial.println(switches[i].stat);
    digitalWrite(clockPin, HIGH);
  }
  digitalWrite(latchPin, HIGH);
  touched = false;
}

I don't understand what's wrong with what I'm doing here, but this for loop runs into an almost infinite loop and prints crazily. I'm a newbie to electronics and Arduino and I don't understand what's wrong here. Please help.

This is my switch class:

struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.

This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).

Heavy use of String variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.

Here are my suggestions:

Replace all "..." string literals with flash-stored strings with F("..."). That will reduce the initial SRAM size used.
Replace all String variables with pure C-string (char* and char arrays) and use standard C string functions such as strcpy, strcat, strlen, strcmp, strchr... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
Use const whenever possible (instead of variables that waste memory)
Use the smallest type needed for each variable, e.g. avoid int (2 bytes) when you need to store a boolean value, prefer bool type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.

I have noticed that you have incorrectly declared the switches array.

Your code:

struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

It should be:

struct Swtch
{
  int num;
  bool stat;
  bool touched;
};

struct Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

Alternatively, you could make a typedef struct:

typedef struct
{
  int num;
  bool stat;
  bool touched;
}Swtch;

Swtch switches[8] = {{1, 0, 0}, {2, 0, 0}, {3, 0, 0}, {4, 0, 0}, {5, 0, 0}, {6, 0, 0}, {7, 0, 0}, {8, 0, 0}};

References:
https://stackoverflow.com/a/32185804/6075112
https://overiq.com/c-programming/101/array-of-structures-in-c/#initializing-array-of-structures
https://stackoverflow.com/a/3275389/6075112


How do I execute some code at a certain time without RTC module? I am building a project when I need my arduino to execute some code at two given hours of the day, for example one at 19:00 and another at 06:00. I know that with a RTC module I can do this easily, however how can I do that without a RTC module? I do not want to have to connect my arduino to a computer neither to the internet. It does not also have to be precise, a couple of minutes off would be ok.

My board is an Uno R3.

If you start with the "BlinkWithoutDelay" sketch that comes with the Arduino IDE, you can execute your code alternating between 11 hours and 13 hours.

// Power up the circuit at exactly 06:00.
unsigned long delayInterval = 0;
unsigned long previousMillis = 0;
bool twoHoursAdded = false;

void setup(){

}

void loop(){

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis >= delayInterval){

    // previousMillis = currentMillis;

    // Use this "method" of incrementing the previousMillis variable
    // instead of the code used in the BlinkWithoutDelay sketch.
    previousMillis += delayInterval;

    if(twoHoursAdded == false){
      delayInterval = 1000UL * 60UL * 60UL * 13UL;
      twoHoursAdded = true;
    }
    else{
      delayInterval = 1000UL * 60UL * 60UL * 11UL;
      twoHoursAdded = false;
    }

    // Your code here that is run at 06:00 and 19:00.

  }
}

"Down sides" to using this code.

If there is a "power failure", the timing will be off, WAY off until you reboot the Arduino at exactly the right time.
You have to power up the Arduino at exactly the right moment for "it's" timing to match your "clock" timing.

If it's within your budget, have a look at the DS3231 modules available on aliexpress.com / ebay.com. They have a lithium battery backup incase of power outage and are really easy to connect to your Arduino using I2C. There are several libraries on Github that simplify using the DS3231 modules.

I am not sure why you are opposed to the RTC or whether you were excluding all external circuitry for the solution. So, I am just throwing this out there...

A CMOS-4060 ripple counter can be programmed for just about any time period and using two of them would give you two separate time constants.

source Substitute the relay for a signal wire to the CPU.

The Cmos 4060 is a 14-bit binary counter. However - only ten of those bits are connected to output pins. The remaining bits - Q1, Q2, Q3 and Q11 - do exist. You just can't reach them.

The 4060 also has two inverters - connected in series across pins 11, 10 & 9. Together with R3, R4, R5 and C3 - they form a simple oscillator.

While the oscillator is running - the 14-bit counter counts the number of oscillations - and the state of the count is reflected in the output pins.

By adjusting R4 you can alter the frequency of the oscillator. So you can control the speed at which the count progresses. In other words - you can decide how long it will take for any given output pin to go high.

When that pin goes high - it switches the transistor - and the transistor in turn operates the relay.

In single-shot mode - the output pin does a second job. It uses D1 to disable the oscillator - so the count stops with the output pin high. .

If you want to use the timer in repeating mode - simply leave out D1. The count will carry on indefinitely. And the output pin will continue to switch the transistor on and off - at the same regular time intervals.

For example, if you want a period of 9 Hours - the Range table shows that you can use the output at Pin 2. You need Pin 2 to go high after 9 x 60 x 60 = 32 400 seconds. The Setup table tells you to divide this by 512 - giving about 63 seconds. Adjust R4 so that the Yellow LED lights 63 seconds after power is applied. This will give an output at Pin 2 after about 9 Hours.

If you increase the value of R3 - and reduce R4 by the corresponding amount - you can set the time delay more precisely. Select a value for R3 that takes you close to the time you're after. And use the reduced value pot - to make the fine adjustment. Note that even finer adjustments are possible with a multi-turn pot.

As mentioned with VE7JRO's solution, this solution (while being pretty accurate) will eventually drift with time and must be powered up at an exact time that is synchronized with the desired trip times.


Reduce current consumption on ATtiny85 I am trying to reduce current consumption on my project. Right now it is using ~1.28mAh, it should be possible to get it much lower (I am using AA batteries as the power source).

The ATtiny85 has its fuses set to run at 1MHZ, with BOD disabled.

I am using this board to mount the CPU. I desoldered the power LED and the regulator, feeding power directly from the batteries to the 5V input.

Nothing was connected to any other pins while measuring, just 5V and GND. The code was running in debug mode, so every 8 seconds it flashed a debug LED. I don't know for how much this could account.

Full code:

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

#define DEBUG (true)
#define INT_PIN (0)
#define OUT_PIN (2)
#define LED_PIN (1)

/***************************************************
 *  Name:        ISR(WDT_vect)
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Watchdog Interrupt Service. This
 *               is executed when watchdog timed out.
 *
 ***************************************************/
EMPTY_INTERRUPT(WDT_vect);
EMPTY_INTERRUPT(PCINT0_vect);

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Enters the arduino into sleep mode.
 *
 ***************************************************/
void enterSleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
  sleep_disable(); /* First thing to do is disable sleep. */

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
    for (uint16_t dbg = 0; dbg < 65535; dbg++);
    digitalWrite(LED_PIN, LOW);
  #endif
}

/***************************************************
 *  Name:        setup
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Setup for the serial comms and the
 *                Watch dog timeout.
 *
 ***************************************************/
void setup() {
  pinMode(INT_PIN,INPUT);
  pinMode(OUT_PIN,OUTPUT);
  pinMode(LED_PIN,OUTPUT);
  ADCSRA &= ~_BV(ADEN); // ADC off
  power_all_disable();
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Main application loop.
 *
 ***************************************************/
void loop() {
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(LED_PIN, LOW);
  /*** Setup the WDT ***/
  wdt_reset();
  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   * WDTCR on ATTINY85 / WDTCSR on ATMEGA
   */
  WDTCR |= (1<<WDCE) | (1<<WDE);
  /* set new watchdog timeout prescaler value */
  WDTCR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
  /* Enable the WD interrupt (note no reset). */
  WDTCR |= _BV(WDIE);
  // sleep for 8 seconds x 43200 = 96 hours = 4 days
  for (uint16_t i = 0; i < 43200; i++)
    enterSleep();
  wdt_reset();
  wdt_disable();
  GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT0); // Use PB0 as interrupt pin
  enterSleep();

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
  #else
    digitalWrite(OUT_PIN, HIGH);
  #endif
  enterSleep();
  PCMSK &= ~_BV(PCINT0); // Turn off PB0 as interrupt pin
}

Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!

Putting it to sleep is the best approach.

You can configure various sources to wake up the MCU.


Accelstepper.runToPosition() is working fine. Accelstepper.run() does nothing I have a complex sketch with Arduino Uno, Bluetooth Serial Com using altSoftSerial, serial com using SoftwareSerial and Serial communication with PC.

I want to move one stepper motor and stop it when a signal is received.
I use A4988 Pololu driver and NEMA 17 bipolar stepper motor.

This code is working fine.
      MyStepper.moveTo(position);
      MyStepper.runToPosition();

If I change the code to
      MyStepper.moveTo(position);
      MyStepper.run();
so that the running does not block my code the motor does nothing
Absolutely no movement.

The ground of the motor power supply is connected with the ground of Arduino. The motor is working fine with blocking movements.

You didn't include any code for us to see what the actual issue is, but I'm willing to guess that you didn't take into account that the run command requires repeated firing.

If your program comes to a point where there's an instance of runToPosition, the blocking function stops the program until the stepper reaches the position specified.

When your program comes to an instance of run(), it fires off a pulse and carries on reading. So you have to use a loop.

stepperMotor.moveTo(3000);
stepperMotor.runToPosition();
// reaches destination

stepperMotor.moveTo(3000);
stepperMotor.run();
// moves a single step

stepperMotor.moveTo(3000);
while (stepperMotor.distanceToGo > 0) {
stepperMotor.run();
}
// reaches destination

The reason you'd use run over runToPosition is to allow for continuous operations / parameters to be executed. For example, two stepper motors running simultaneously:

stepperMotor1.moveTo(5000);
stepperMotor2.moveTo(3000);
while ((stepperMotor1.distanceToGo > 0) && (stepperMotor2.distanceToGo > 0)) {
stepperMotor1.run();
stepperMotor2.run();
}
// Both motors will run, but will both stop when either of them reaches their destination.

Depending on the speed of your microprocessor, you can create some sophisticated instruction sets for your motor(s).

The problem is at blocking delays. The Run function is interrupted by any other action of program. So you have to call it all the time. A call to run is required in the loop and I wrote a simple mydelay function which solves the problem if you have to use delay for bluetooth communication or other purpose.

int mydelay(int j) {
  long endmillis;
  endmillis = millis() + j;
  while (millis() < endmillis) {
  MyStepper.run();
  }

I hope I help someone because it took me a while to figure this out as a newbie to Arduino.


Arduino Mega 2560 RFID Serial Communication I have an RFID reader: http://img.tradeindia.com/fp/1/641/264.jpg

Something like above along with ITEAD TFT shield & GSM Modem. The RFID reader has an RS-232 port as well as GND, TX and 5V pins. I am using an Arduino Mega 2560 board. I have connected the TX, GND of RFID reader to RX3 pin 15 / GND (pin) of Arduino. Note I am supplying 12 V to RFID via an adapter.

Note the ITEAD TFT shield consumes the TX0, RX0 pins—so I cannot make use of the RX0 and TX0 pins. Though I have not written the code for GSM modem.

Now while running the program below, I am getting junk output both in my TFT display as well as the serial monitor:

#define __AVR__
#include <UTFT.h>

// Declare which fonts we will be using
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];
UTFT myGLCD(ITDB24,59,58,57,56);
String myString = "";

void setup() {
   Serial3.begin(9600);
   myGLCD.InitLCD();
   myGLCD.clrScr();
}

void loop() {
  myGLCD.setFont(BigFont);
  if (Serial3.available()) {
    int inByte = Serial3.read();
     myString += String(inByte);
    }
    if(myString.length() == 10)
      myGLCD.print(myString, CENTER, 0);
}

TFT Screen output:

1310494848

Serial Monitor Output: non printable junk character.

The value is incorrect, I am pretty sure, what am I doing wrong?

I found that the ITEAD shield is sending or rather using RX0/TX0 pins very frequently—some data is going through.

BTW what is the functionality of http://arduino.cc/en/Tutorial/SoftwareSerialExample?

How can I use 3 different Serial I/Os individually at the same time without disturbing any other I/O?

First of all, try testing 1 functionality at a time to isolate the issue.
Now you do not know if the LCD is not working correctly, or if the serial communication with the RFID module is not working correctly. Connect it to a computer and test both independently.

When getting gibberish from a serial line, usually it means the baudrate doesn't match. Both devices have to send the same amount of bits per seconds in order to communicate with each other.

This is the Arduino example to test 2 serial lines (for Arduino Mega) at the same time: http://arduino.cc/en/Tutorial/MultiSerialMega

i think the RFID is a other baud rate e.g 115200.. i dont know the device, i dont know if this is the problem, but test it :)


How can I use an arduino as an intermediary step between my PC and a LED strip? Goal
My end goal is to have a NeoPixel LED Strip that I can control via software on my PC, with various automatic modes and manual control. Right now all I have is the idea and some research done, because I don't want to order parts if I can't get this working. That means no arduino, no leds, no power supply, and no experience with any of them.
What I know so far
I know enough Java to set up the software that would output some array of colors, including manual control and automatic modes like flashing/fading/etc.
From the research I've done, I'll need a microcontroller to make sure I output exactly the right signal(?) for my LED strip. Adafruit recommends an Arduino one or Arduino mega, which meet the timing requirements and have libraries available for use with NeoPixel products. Physically connecting the Arduino to the LED seems fairly easy.
What I don't know
Hardware and software wise, how can I transfer an array of color values from a java program to the Arduino?
This involves getting the data to a port on my PC, getting that to the Arduino via some wire/s, and making sure it's readable. I'd imagine sending an entire array to whatever input the arduino has would be difficult. Perhaps I could send a single color at a time together with an index, but that would probably add delay to the system.
On the software side, how do I set up the arduino to "forward" the input from my PC to the LED strip?
I'm not very comfortable with C, so this could be tough. How will I receive the data input? How easy and fast is it to turn that into output for the LED strip? What if I don't convert and output an update before I receive another one?
EDIT: It seems there are libraries available to deal with the actual data transfer, and encoding/decoding shouldn't be too hard after some thought. I think I'm going to use usb4java for communication between my PC and an Arduino, and roll my own mini "protocol" to convert. Then I'll use the NeoPixel libraries for the Arduino.

You should take a look at FadeCandy if you are dealing with NeoPixel LED Strip. Ived used that in conjunction with Processing (which is JavaBased) to send stuff into a 16x16 NeoPixel display. (4 8x8 matrix's linked together)
Fadecandy uses Open Pixel Control
http://openpixelcontrol.org/

I've got an example of it on youtube... https://www.youtube.com/watch?v=rz_U4dzjp1s&feature=autoshare


Problem with NFC on Arduino MEGA My Objective :

I am trying to send my Mifare's unique number with some other parameters to my server database. As soon as the tag come closer to NFC, it detects, and some additional details are passed to the server Database.

Steps done :

I have Arduino UNO, Arduino GSM shield and Adafruit NFC shield . I had tried my test with UNO and works well. But to add some more features, due to memory salvation it could not be achieved through UNO. Then we moved to MEGA.
There are some changes need to be done with MEGA to make [url]http://arduino.cc/en/Guide/GSMShieldLeonardoMega[/url] GSM shield coordinate with the microcontroller[Take the Pin 2 out from GSM shield and with jumper connect Pin 2 with Pin 10]. Then we did and we tested it with GSM web client example and worked fine.
Now to accomplish our goal, when we placed NFC shield above the GSM shield and executed same GSM web client example, it is not working. And Suddenly once in a blue moon it connects to the GSM network and works . But often, it fails.

[code]

/*
  Web client

 This sketch connects to a website through a GSM shield. Specifically,
 this example downloads the URL "http://arduino.cc/asciilogo.txt" and
 prints it to the Serial monitor.

 Circuit:
 * GSM shield attached to an Arduino
 * SIM card with a data plan

 created 8 Mar 2012
 by Tom Igoe

 http://arduino.cc/en/Tutorial/GSMExamplesWebClient

 */

// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP

void setup()
{
  // initialize serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;

  // After starting the modem with GSM.begin()
  // attach the shield to the GPRS network with the APN, login and password
  while(notConnected)
  {
    if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
      (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, port))
  {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.1");
    client.print("Host: ");
    client.println(server);
    client.println("Connection: close");
    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for(;;)
      ;
  }
}

What is the problem? and where is the problem ?

It is likely that placing the GSM shield between the Arduino Mega and the NFC shield is interfering with the GSM antenna.  Antennas react in strange and usually less useful ways when large conductors are placed nearby.

You could try reversing the order of attaching the shields, or you could try spacing the shields further apart using "stackable Arduino headers" (you can do a web search for suppliers).  If there is an option for an external antenna, that would be even better.

If you get GSM working, you might still have some trouble with the NFC shield, as it's possible that the GSM transmitter being so close could interfere with the NFD's circuitry - not because they use the same frequences, but just because any conductor so close might pick up electrical noise, and there will be various sensitive circuitry in the NFC electronics.

if your design allows , the NFC is available on a module rather than a shield allowing you to separate the GSM and NFC. like this on ebay


Isolating IR receiver from disruption? I'm using a simple IR receiver connected to the Arduino through A0 analog pin. The problem is that I want to stabilize the output of IR receiver when it's not receiving an IR signal from a specific IR source, or at least minimizing the disruption to a specific range that I can handle, no matter where its position, But in my case moving the IR receiver a few inches in any direction will results in different voltage output. the difference between values on disruption is very random to handle.

What can I do to isolate IR receiver, may be a specific material or a specific color?

I would suggest two things. First You could put electrical tape around the receiver in such a way that it will only pick up signals from a certain direction. Also you could use low and high pass filters to accept input only in the 38khz range(range of most infra red remotes).  Keep in mind that you will need a couple of rounds for it to work effectively.

Ir receiver should not be connected to an analog input but digital


Micro-servo 9g SG90 not rotating I have an Arduino nano. I am a beginner to Arduino, so I tired the example sketches. The "Blink" sketch worked well. So now I am trying to get this Micro Servo (9g SG90) to work. No codes built in or the ones if look up on internet are making it rotate. Would love to hear how Icould make the example program "Sweep" is work.

Servo sg90 is small and can be powered from your computer or laptop connected to the Arduino. The problem does not lie there, but maybe about your connection. Make sure about these things:

Brown is connected to GND
Orange is connected to VCC
Yellow is connected to digital PWM pins.

You could use this code that I am hooking up, with several servos and using external supply but if you try doing the same make sure all the motors are properly grounded.
#include<Servo.h>
Servo ServoBase;
Servo ServoLeft;
Servo ServoRight;
void setup(){
  ServoBase.attach(6);
  ServoLeft.attach(5);
  ServoRight.attach(3);
}

void loop(){
  ServoBase.write(140);
  ServoLeft.write(120);
  delay(1500);
  ServoBase.write(40);
  ServoLeft.write(30);
  delay(1500);
}

Are you by any chance, trying to run your nano from a 9v battery? They are about the weakest power sources available, despite their voltage. If so, try again with the nano powered from a USB port. You should have much better results.
If it is not due to a 9v battery or other weak power supply, then something else is wrong. Some things to check are:

The servo wiring;
The servo itself (try another SG90 if you have one);
The Nano's pin-driver (try a different - PWM - pin);
The code (make sure you wired the same pin the code uses, and that it uses a PWM pin)


Can't get software serial to work So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial.  I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa.  On my sending Arduino, I have the following code:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

void setup() {
  pinMode(2, OUTPUT);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.isListening()){
    digitalWrite(2, HIGH);
  }
  mySerial.write(5);
}

and on my receiving Arduino, I have:

#include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10);

void setup() {
  pinMode(2, OUTPUT);

  Serial.begin(9600);

  mySerial.begin(9600);
}

void loop() {
  mySerial.listen();
  if (mySerial.available()>0) {
    digitalWrite(2, HIGH);
    char inByte = mySerial.read();
    Serial.write(inByte);
  }
  digitalWrite(2, LOW);
}

(with D2 being hooked up to an LED for both).

I can't get it to read anything.  Nothing seems to be available for the receiving Arduino (the LED is off).  What am I doing wrong?

Sender:

SoftwareSerial mySerial(10, 11);  // Rx, Tx

Receiver:

SoftwareSerial mySerial(11, 10);  // Rx, Tx

  I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

  mySerial.listen();

You don't need that in this simple example.

I agree with Nick above but want to add this simplify your code like this:

if (mySerial.available()) {
    digitalWrite(2, HIGH);
    Serial.write(mySerial.read());
  }

I have had to catch serial data from a printer feed before and this turned out to be the best way to catch all the data if you place it in a variable first it has to change the variable every time that you receive a byte but this way it places all in a buffer then sends it out

BTW I had to save to a F-RAM device and that worked the same way but instead of sending it I had it saved to a variable while using ReadString() in stead of read().


Arduino due erase button and power switching Last days I have been investigatin schematics of arduino due board. The purpose of proper understanding of schematics in crucial for me, beacuse I indend to build myself my own board with some minor modifications.

I would really want to learn something from it and not just blindly copy stuff that are already done. In schematics there are two things that I do not understand. First is the working principle of erase button (see: erase button). I have my own idea how does it work, but would like to clarify the working principle from someone that know exactly what is the purpose of all the elements that are connected to erase button. Also, why is ERASE_CMD  line connected to Atmega processor?
 Second thing is switching of power supply between external power and both usbs (see: usb switch). Again, would someone please just brifly describe working principle? Here I really do not undertand why is there op amp added?

Thank you in advance.

Erase button:

USB switch:

PLEASE NOTE: Both pictures are taken from original arduino webpage: https://store.arduino.cc/due  (see: documentation -> schematics)

The asker posted the same question and received an answer here
There is discussion regarding the purpose of the Erase switch here


Arduino code on Raspberry? Is there any way to run Arduino sketches on Raspberry Pi (basically on Raspbian)? I have several projects that work on Arduino and I would like to run the exact same stuff on my Raspberry Pi. Is there a way to just put all the pins off the Arduino, put them on the Raspberry, then adjust the pin number settings in the Arduino sketch, and then run the program on Raspberry?

Given that most likely the Arduino code is accessing AVR specific registers, probably not, unless you have some compatibility library that redefines all the low level stuff.

I also wonder if you have the same set of peripherals available on the PI (ex: PWM generators and ADCs).

I would rather follow the "spirit" of the code you already have and re-implement it natively in you language of choice.

That answer is quite simple, no, this is not possible.


Implement Visible Light communication using Arduino I want to implement a simple VLC based communication system using two Arduinos and send messages/data/files between two PCs. For that I have a simple transmitter circuit with an LED on Tx side and a photo-transistor on the receiver side. The codes im using for transmission and reception are attached below, also the circuit image is attached below, but im unable to bring about any communication between the two PCs, the transmitter side works fine as the LED flickers indicating data is being transferred, but its not being received by the photo transistor. I don't know what im doing wrong. Any help would be appreciated, I am doing this as a part of my academics.
Transmitter Code :

void setup()
{
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  // Clear Timer on Compare Match (CTC) Mode
  bitWrite(TCCR1A, WGM10, 0);
  bitWrite(TCCR1A, WGM11, 0);
  bitWrite(TCCR1B, WGM12, 1);
  bitWrite(TCCR1B, WGM13, 0);

  // Toggle OC1A and OC1B on Compare Match.
  bitWrite(TCCR1A, COM1A0, 1);
  bitWrite(TCCR1A, COM1A1, 0);
  bitWrite(TCCR1A, COM1B0, 1);
  bitWrite(TCCR1A, COM1B1, 0);

  // No prescaling
  bitWrite(TCCR1B, CS10, 1);
  bitWrite(TCCR1B, CS11, 0);
  bitWrite(TCCR1B, CS12, 0);

  OCR1A = 210;
  OCR1B = 210;

  Serial.begin(2400);
}

void loop()
{
  Serial.println("testing testing testing");
  delay(500);
}

Receiver Code:

void setup()
{
  Serial.begin(2400);
  pinMode(13, OUTPUT);
}

void loop()
{
  // if incoming serial
  if (Serial.available()) {
    readSerial();
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
  delay(500);
}
void readSerial() {
  char val = Serial.read();
  Serial.print(val);
}

the transmitter works fine, but the receiver is not receiving anything, I don't know what i'm doing wrong.

The amplitude of the signal at the photodetector is small. Better use ADC for reading.

Your receiver(ldr) might not be accurate enough, rather try using an led as a receiver as well. You will just need to boost the signal then with something like a 1Mohm resistor in parallel with the receiving led.

You can use something like this as well, haven't tried it but it looks like it will work: http://www.instructables.com/id/Arduino-Communication/
maybe just a 1Mohm resistor instead of the 1Kohm one


How to send data from Arduino Uno with SIM900 GPRS to Firebase I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from here. Here is some code that I've tried:

AT
OK
AT+CREG?
+CREG: 0,1

OK
AT+CGATT?
+CGATT: 1

OK
AT+CIPSTATUS
OK

STATE: IP INITIAL
AT+CIPMUX=0
OK
AT+CSTT="att.mvno","",""
OK
AT+CIICR
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
OK
CONNECT OK

and

AT+CIPSHUT
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
OK
CONNECT OK

If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret?
Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. This site explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.