Error AT%13% With GSM/GPRS Shield I've been trying to control a relay with a GSM shield for an Arduino project. I haven't had any success with either the Software Serial or the GSM library. I've declared the GSM variable in debug mode and it gives me the error AT%13%.
Using Software Serial, it hangs at SIM900.read().
The SIM card connects to the network, I can see that on the board - the LED flashes every 3 seconds and gives me signals for incoming calls and SMSs.

I can't tell if the error is with the SIM card, the connections to the Arduino board, the power supply (12V) or something completely different. Here are the two code examples I'm using with the different libraries.

Anyone else getting this error? What is the best way to make it go away?

Thanks in advance for any help!

SoftwareSerial.h

#include <SoftwareSerial.h>
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int Relay1 = A2;
int Relay2 = A3;

void setup()
{
  Serial.begin(19200);
  //Set up relay control pins
  pinMode(Relay1, OUTPUT);
  digitalWrite(Relay1, HIGH);
  // wake up the GSM shield
  SIM900.begin(19200);
  delay(10000);  // give time to log on to network.
  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  // output contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
  Serial.println("Ready...");
  }

void loop()
{

  //If a character comes in from the cellular module...
  if(SIM900.available() >0)
  {
    inchar=SIM900.read();
    Serial.println(inchar);
    if (inchar=='#')
    {...}
    SIM900.println("AT+CMGD=1,20"); // delete all SMS
  }
}

GSM.h - in this case I haven't even gotten past the .begin() command. This code is from the example at http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS

#include <GSM.h>

// PIN Number for the SIM
#define PINNUMBER ""

// initialize the library instances
GSM gsmAccess(true);
GSM_SMS sms;
GSM3_NetworkStatus_t   gsmStatus;
// Array to hold the number a SMS is retreived from
char senderNumber[20];

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

  Serial.println("SMS Messages Receiver");
  char code = 'X';
  Serial.flush();
  gsmStatus = gsmAccess.begin(PINNUMBER,false,false);

  int retrycount = 60;
  while (gsmStatus != GSM_READY && retrycount-- > 0) {
    delay(1000);  // lower delay value could lead to unstable state
    theGSM3ShieldV1ModemCore.manageReceivedData();
    gsmStatus = gsmAccess.getStatus();
  }

  if (gsmStatus != GSM_READY) {
    Serial.println("\n[ERR]: GSM connection failed\n");
    Serial.flush();
    gsmAccess.shutdown();
    delay(250);
    digitalWrite(3,LOW);
  }

  Serial.println(" [DONE]");

  // connection state
  boolean notConnected = true;
  // Start GSM connection
  while (notConnected)
  {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY)
  {
      notConnected = false;
  }
    else
    {
      Serial.println("\nNot connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  Serial.println("Waiting for messages");
}

Check your baud rates. They appear to be different. That will cause problems.


NodeMCU backup sketch Is it possible to extract a backup of the sketch uploaded to a NodeMCU (as I know that it is possible to backup the firmware).

If so, using which tools?

esptool.py is 'avrdude' for the esp8266. it can read the flash too. but you must know the addresses. tha first copy of the application always start at address 0x1000. the length of the application area depends on the size of the flash and the size of the SPIFFS.

> esptool.py read_flash -h
usage: esptool read_flash [-h] [--spi-connection SPI_CONNECTION]
                          [--no-progress]
                          address size filename

positional arguments:
  address               Start address
  size                  Size of region to dump
  filename              Name of binary dump

optional arguments:
  -h, --help            show this help message and exit
  --spi-connection SPI_CONNECTION, -sc SPI_CONNECTION
                        ESP32-only argument. Override default SPI Flash
                        connection. Value can be SPI, HSPI or a comma-
                        separated list of 5 I/O numbers to use for SPI flash
                        (CLK,Q,D,HD,CS).
  --no-progress, -p     Suppress progress output


What causes Serial.available() to become false after Serial.read() gets data? As serial data bytes are being read from the serial buffer by Serial.read(), are they removed from the Arduino's 64-byte serial buffer altogether?

In my current situation I'm using SoftwareSerial, but this question applies to both software and hardware serial connections.

EDIT: Based on a comment from @dandavis, I'd like to further clarify my question

How does Serial.read() interact with Serial.available()? Let's say that I have the usual setup:

while( Serial.available() ) {
    Serial.read();
}

What causes Serial.available() to become false?

EDIT 2: Changed question title for even further clarification...

It is an internal buffer and only the pointer gets increased. It it visible in the source code off the project, located on github:

// Read data from buffer
int SoftwareSerial::read()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

This third line from the bottom is the important part, it wraps back to the beginning if the buffer space has run out. If you call Serial.read(), the pointer is moved to the next position. So with the next Serial.read(), you'll get the next byte, if available. The byte itself gets overwritten only after the wrap (circular buffer).


How can I sense when someone is sleeping with my Arduino? Ignore the stalker-like title.

I am thinking about creating a project with Arduino that can sense you sleep habits, when you're asleep, and how much you sleep. It would be convenient to not have to turn it on/off at night; it should know how to do this.

Some ideas that I have:

Motion sensor
Breathing patterns (if an Arduino microphone could even pick that out... I would be surprised if it could)
A RTC clock could assist in deciding It's midnight. Usual, Steve isn't asleep at this time on Fridays. He's probably not sleeping now. It won't always be there to help you, but you might be able to try to get more accurate results this way

How can I accomplish this? (Extra points for some sort of algorithm that can tell dozing off from a deep sleep.)

I actually did something like this, using a PIR Motion sensor.

The motion sensor is good enough to detect a person turning in their sleep, and my simple algorithm just counts movements per minute and when its over a threshold (found by trial and error), it sounds the alarm to wake you up.

The image above represents my body movements during a night. The spikes represent a high movements/minute.

  Here we see after about 30 minutes body motion was minimal. This suggests I was in a deeper stage of sleep during that time.

  The spike at 250 minutes (around 4:30AM) is when I woke up only to
  realize I could sleep for couple of hours longer. I recall the time
  being 4:38 when I looked at my clock and I was already facing it. This
  means I turned around to face the clock but actually "woke up" 8
  minutes later to see the time, and then turned back around (indicated
  by the shorter spike at 265).

  The data suggests I was not able to sleep very well (compared to the
  time period between 30 and 240 minutes) after waking up once and
  finally got up at 400 minutes (7:00AM), when I shut everything down.

Here are a couple of posts from my blog that have a lot more information.

Body Movement During Sleep
Intelligent Alarm Clock Hardware


Typedef struct not working I made this simple code but I'm getting the following error

exit status 1
'RGB' does not name a type

typedef struct
RGB
{
        double r;
        double g;
        double b;
};

RGB led;

RGB func(){
  RGB temp;
  return RGB;
}

I am not getting the error on "RGB led" but just on the function.
Does anyone know a solution for this? Thanks!

In plain C, structs are identified by "struc tags", which do not live in
the same namespace as type names. Thus, if you declare

struct RGB {
    ...
};

a variable of this type should be declared as

struct RGB led;

In order to avoid the inconvenience of repeatedly typing struct, a
common idiom is to define it as a type:

typedef struct {
    ...
} RGB;

RGB led;

The Arduino environment, however, is based on the C++ programming
language. In C++ struct tags are types, and you thus do not need the
typedef:

struct RGB {
    ...
};

RGB led;

This is the recommended idiom in C++: just remove the typedef.


Can I specify custom port names in the Arduino IDE on Linux? On Linux, if you have more than one USB TTY device, the USB port name (/dev/ttyUSBx) changes every time one is plugged in, and there's no easy way to know the new name without going and looking through dmesg.  It's trivial to set up a udev rule that creates a custom symlink so that my Arduino's FTDI can always be accessed through e.g., /dev/ttyArduino, and this is the standard procedure for persistent access to USB devices.

However, I can't make the IDE accept anything other than the /dev/ttyUSBx names.  Even directly editing preferences.txt is ignored.

Is there any way to instruct the IDE to use custom port names in order to access the Arduino through a symlink or other persistent name?

Consider using a device name of form ttyUSBnn, where nn is fairly large.  For example, in /dev you could say

sudo ln -s ttyUSB1 ttyUSB77

Then, ttyUSB77 shows up in the IDE's ports list and can be selected.

(I don't know how to set up that link using the udev system, but imagine it can be done.)


How to check 8266 module I am using an Arduino board with an ESP8266 module to connect to a WiFi device.
How do I check if the device is connected?

You can use:

AT+ CWJAP?

or

AT+ CIPSTATUS

to see if you're connected to wifi. (The first will tell you access point status, the second will tell you IP address.)


Digital pin output voltage fall down when driving a relay I'm trying to trigger 8 different 5V relays using arduino atmega 2560. the relays (70Ohm coil) are powered by an external 5V source, and im trying to trigger them through a driving stage which contains for each relay a npn transistor (2N3904) and 1kOhms resistor directly connected to digital pin of the arduino.
the relays in my application are supposed to be drived 2 by 2 not all of them at once.
My problem is that i dont succeed triggering the relay with digital pins of my arduino, once i connect it to the resistor the voltage of the digital pins falls down from 5V to 0.4V or less. The transistor needs only 7mA to be triggered, the output current of the atmega2560 pins is 20mA max.
i tried with an external 5V source, it triggers correctly showing 10mA maximum of current through the driving stage.
Thank you in advance for your help.
Best regards.

If the coil is 70 ohms and it's driven by 5V, it should draw about 5/70 = 71 mA.  That's pushing the 2n3904 a bit hard, and doesn't even account for inductive effects. (It's a small-signal transistor.)  Do you have an NPN power transistor to try, just as a test?  If its current gain (beta) is too low, use a Darlington configuration by combining it with your 2n3904.  (2n3904 base from digital out resistor, emitter drives power NPN base directly, both collectors are connected together to the bottom of the coil, and the power NPN emitter is the effective emitter of the just-created "super transistor" with high beta and power handling.)  Be sure to use an anti-kickback rectifier (1n4001)across the relay coil.


Conversion between boolean and int went wrong I have a small problem with conversion from bool array to int. It is working fine until it comes to the 12th cycle of while. I don't know why but this is really weird.

I try to paste here a code where I am doing this conversion.

int* BoolToInt(bool* set) {
  int* ret = (int*)malloc(3*sizeof(int));
  int sum0 = 0;
  int sum1 = 0;
  int sum2 = 0;
  //bool test[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1};
  for(int m=0; m<24; m++) {
    if(m<8) {
      sum0 += (int)set[m] * (pow(2,m));
    }
    if(m>7 && m<16) {
      sum1 += (int)set[m] * (pow(2,(m-8)));
    }
    if(m>15 && m<24) {
      sum2 += (int)set[m] * (pow(2,(m-16)));
    }
  }
  ret[0] = sum0;
  ret[1] = sum1;
  ret[2] = sum2;
  Serial.print("\n ret[0] = ");
  Serial.print(ret[0]);
  Serial.print("\n ret[1] = ");
  Serial.print(ret[1]);
  Serial.print("\n ret[2] = ");
  Serial.print(ret[2]);
  return ret;
}

And this is where I am using this function:

void Fitness(bool** set) {
  int maX = 0;
  int index = 0;
  int* temp;
    for(int i=0; i<10; i++) {
    int* phenotype = BoolToInt(set[i]);
    _fitness[i] = 1000/((phenotype[0] - _colours[0])*(phenotype[0] - _colours[0]) + (phenotype[1] - _colours[1])*(phenotype[1] - _colours[1]) + (phenotype[2] - _colours[2])*(phenotype[2] - _colours[2]) + 1);
    Serial.print("\n phenotype[0] = ");
    Serial.print(phenotype[0]);
    Serial.print("\n phenotype[1] = ");
    Serial.print(phenotype[1]);
    Serial.print("\n phenotype[2] = ");
    Serial.print(phenotype[2]);
    free(phenotype);
  }
  for(int i=0;i<10;i++) {
    temp = BoolToInt(set[i]);
    if(_fitness[i]>maX) {
      maX = _fitness[i];
      index = i;
    }
  }
  setColorOnSecond(temp[index]);
  free(temp);
}

As seen in the Fitness function, I have some debugging prints to see if everything is fine. My main is in the while cycle. Everything is fine and "ret" from BoolToInt function is the same as "phenotype" in Fitness, which is a good thing and this is what I want. But then the 12th cycle comes and phenotype[1] gives me 1200 as int. And of course everything in ret[] is fine(0-255). Am I doing something wrong?

NOTE: bool* set in BoolToInt is 24 bool array (yes 3 numbers as you can see).

NOTE 2: every previous cycle before 12th cycle is good and the result are equal.

Let me the first one to say that 1. Boolean to int conversion shouldn't be this complicated and 2. Much simpler ways to do what you are trying to do.

Like this.

If (bool) boolint |= mask;
  Mask = mask << 1;
  ...

You get the idea.


What does Arduino do in 15ms? I was wondering why there is a 15 ms delay between each iteration of a the main loop.

Code:
The following code shows the execution time expressed in microsec between each loop

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

void loop()
{
  Serial.println();
  Serial.print("Start: ");
  Serial.print(micros());
  Serial.print("/////////////////////");
  Serial.print("End:");
  Serial.print(micros());
}

Output:

Start: 789452/////////////////////End:821692
Start: 837292/////////////////////End:869532
Start: 885132/////////////////////End:917372
Start: 932972/////////////////////End:965212

Arduino needs 32,240 msec to print the messages to serial and to call the micros() function twice. And this it's fine. Now, considering the difference between the values of the End and the following Start, one question arises:

What does Arduino do between each loop?

Just check the sourcecode

for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

So it does a check if serialEventRun is True, and then a jump back to the beginning of the for-loop. And then a call to loop.

Also note that Serial.print is blocking if the TX-buffer is full. So you might want to add a delay somewhere to ensure the buffer is never full.


IR frequency difference I want to create a device that interfaces with the Light Strike Lasertag system using an Arduino Leonardo.

The Light Strike system uses not laser but regular infrared signals. According to a site that I found (http://www.meatandnetworking.com/projects/hacking-at-the-light-strike-laser-tag-game/) it uses 37.8 khz signals. I only found IR-receivers using 37.9 or 38 khz. Can I use them? How far can the modulation frequency differ?

Is there anything else I need to watch out for when creating an IR-interface?

Can I use 37.9 or 38 kHz IR-receivers for 37.8 khz communication?

Yes you can, it should be close enough. (I am assuming you are talking about some kind of prebuilt receiver that just receives the IR data and transmits it via RS232 or something like that)

I'd suggest you'd use a phototransistor and a IR diode for the communication. You will have a lot more control over what frequencies you are operating on. Altho it might take a bit more work to program it, the end result will be exactly how you wish.


Why is my real time clock getting the wrong time from my PC? I want my real-time clock to set its time as the time on my PC. However, when I run the following sketch, the real-time clock reports the time as being 32-33 seconds earlier than my PC says the time is.

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;

void setup () {
  Serial.begin(57600);
  Wire.begin();
  RTC.begin();

  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
// following line sets the RTC to the date & time this sketch was compiled
// uncomment it & upload to set the time, date and start run the RTC!
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

void loop () {
  DateTime now = RTC.now();
  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
}

I have also tried manually setting the time on the RTC, but I end up with the same problem: the RTC is always 32-33 seconds behind what I set it to. The lag happens as soon as I run the sketch. It seems very odd to me that no matter how I try to set the time, I end up with exactly the same error. I can tell the Arduino to report the time as being 33 seconds after what the RTC says it is, but this solution seems kind of sketchy, and I am worried that something is fundamentally wrong with my RTC or the way I am using it.

I am using an Arduino Uno with an Assembled Data Logging Shield from Adafruit. The data logging shield uses a DS1307 RTC. Has anyone had this problem before, or have any ideas about what could be causing it? Any help would be much appreciated.

The __DATE__ and __TIME__ are set when the code is compiling so they will naturally be behind since the code still needs to finish compiling and then be flashed to the chip.

See the Arduino Playground for an example of how to sync it to your computer over serial.

  TimeSerial.pde shows Arduino as a clock without external hardware.

  It is synchronized by time messages sent over the serial port.   A
  companion Processing sketch will automatically provide these messages
  if it is running and connected to the Arduino serial port.


Arduino drawing a bitmap on nokia 5110 lcd Hello I finally got my nokia 5110 lcd working, I have tested it by displaying bitmap images other people have made. I made my own image and then used lcd assistant to turn it into an array. First look at my code.

#include "U8glib.h"

U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6);  // CLK=8, DIN=4, CE=7, DC=5, RST=6

int x = 5;
int y = 5;

int level = 5;

const uint8_t rook_bitmap[] U8G_PROGMEM = {
0x7E, 0x82, 0x04, 0x8E, 0x7A, 0x42, 0xB4, 0x24, 0x08, 0xD8, 0x48, 0x08, 0x08, 0x0C, 0x02, 0x22,
0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1E, 0x11, 0x21, 0x22, 0x14, 0x3B,
0xD4, 0x25, 0x29, 0x68, 0xA8, 0xA8, 0x74, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};

void draw(void) {
  // graphic commands to redraw the complete screen should be placed here
  u8g.drawBitmapP( 5, 5, 3,18, rook_bitmap);

}

void setup(void) {

}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );

// y++;
  // rebuild the picture after some delay
  delay(1000);
}

The part that goes wrong is at u8g.drawBitmapP(5,5,21,18, rook_bitmap);
I know it is to do with the 21 and 18 being wrong because I don't know where to get those numbers. Is it the width and height of the image when it is in paint.net or what is it?

The 21 and 18 are the dimensions of the image. It's not just pixels though.

The first number (21) is the number of bytes in a row of the image - that is one eighth of the width in pixels.  The width must be a multiple of 8.

The second number is the number of rows in the image - basically the height in pixels.

The two numbers, when multiplied together, must equal the number of bytes in your array.

From the documentation:

  Description

  Draw a bitmap at the specified x/y position (upper left corner of the bitmap). Parts of the bitmap may be outside the display boundaries. The bitmap is specified by the array bitmap. A cleared bit means: Do not draw a pixel. A set bit inside the array means: Write pixel with the current color index. For a monochrome display, the color index 0 will usually clear a pixel and the color index 1 will set a pixel.

  Arguments:

  u8g : Pointer to the u8g structure (C interface only).
  x: X-position (left position of the bitmap).
  y: Y-position (upper position of the bitmap).
  cnt: Number of bytes of the bitmap in horizontal direction. The width of the bitmap is cnt*8.
  h: Height of the bitmap.

It would appear your image data is complete gibberish.  This is what I decode it to be:

 ######  #     #  #
 ###   # # ####  #    #
  # ## #  #  #     #
   ## ##   #  #    #
   #      ##     #
 #   #  #  ## #####

        #        ####
#   #   #    #   #   #
  # #   ## ###    # # ##
# #  #  #  # #     # ##
   # # #   # # #  # ###
  ##    ##


Arduino hangs after some time I am using Atmega328p with 5V power supply,
My Arduino getting hangs [or auto restarts] after some times.

I am using libraries:

Wire.h
CRC32.h
EEPROM.h
Arduino.h
TimerOne.h
RtcDS3231.h
SoftwareSerial.h
Adafruit_NeoPixel.h
avr/wdt.h

I have tried to search, some people are deny to use software serial library.

Not sure if this will fix your problem, but this is a major error:

  char buf1[8], buf2[6];
  sprintf(buf1, "%08lu", myvote.mydate);
  sprintf(buf2, "%06lu", myvote.mytime);

Take a look at sprintf function reference

  A terminating null character is automatically appended after the content.

So, the text buffers are too small. It should be at least:

char buf1[9], buf2[7];


İs there any way different way than GND's Arduino İ'm making  a project on my arduino uno when i figured out i had no more GND left to finish the circuit. İs there any other way to optimize, use pins as input maybe. İ tried whit other websites, however, they weren't much of a use. Can you show an example also.
Thank you sooo much in advance,
Dario

Dario,

There are only 3 ground pins on the Arduino Uno, but don't be afraid to "breakout" these pins with wire. It doesn't matter if you connect multiple component grounds together, as long as they are connected to ground with no resistance between them, the circuit will close.

Strip board and pin headers will help you here, try this: http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/


Inkjet Printer Robot Wheels I'm newbie about Arduino.
Can i build arduino robot wheels using Canon/Epson Cartridge inkjet printer?

The idea is like Drawing Robot

but i want to use cartridge printer instead of using a pen.

so after searching, and it look like ZUtAPocketPrinter

The Drawing Robot is using Trinket Pro
And ZUtAPocketPrinter is using Arduino (don't know using Uno/Nano/etc)

Can I use Trinket Pro or what types of arduino that i can use (Uno, Nano)?

And what hardware, sensor that require to scan/measure size of the paper?

And if there is tutorial, please share the link.

Usually a robot uses 2 identical motors for drive in order to change directions or go straight.  Usually a printer will only have 1 motor to drive the paper and 1 motor to drive the print head.  And usually they are not identical.  Making it difficult to build a useful robot.  Also, printers usually use stepping motors.  Most people building their first (small) robot usually use continuous servo motors.  This makes for an easy to build first (small) robot as seen in this picture:


how many processor cycles/time does it minimaly take to transmit 1 Byte via Serial? My understanding has been that the Serial transmission is indeed done (on the Arduino Uno) via the pins named TX->1 and RX<-0?
With this I assume that the Atmega has a machine code that would allow in 1 or processor cycles (125 or 62.5 ns) to set a byte (i.e. Port byte DDRD) as to forward exactly one bit of information for further processing to the ATmega16U2 "serial to USB" chip?

If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

No, it is not true.

You are assuming (wrongly) that the CPU is doing the UART communication.  It isn't.

The UART is a completely separate piece of hardware inside the chip.  It runs by itself.  The CPU merely places the byte to transfer into a special function register (SFR).  The UART then takes that and clocks it out through the IO pins at the right rate for the serial communication.  While that is going on the CPU is free to perform other operations.

The CPU can then either consult another SFR to determine if the transmission has finished, or utilize an interrupt that the UART will trigger when the transfer has been completed.


Arduino uno toggle switch help I am building a box that will start a genset. It has two buttons, run and stop.
I would like button run to be able to start (and remain constant) until pressed a second time, I have sussed this bit so far, but this is where I get stuck.
I would like the stop button to only stop the the engine (as a single function)
So my question is how do I integrate the second button (stop) to carry out this one task?

int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDRedPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode (LEDYelPin,OUTPUT);
pinMode (LEDGrnPin, OUTPUT);
pinMode (RELAYRedPin, OUTPUT);
pinMode (RELAYYelPin, OUTPUT);
pinMode (RELAYGrnPin, OUTPUT);
pinMode (buttonPinOff, INPUT);
}
void loop() {
buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);
if(buttonOld==0 && buttonNew==1){
  if (LEDRedState==0){
    digitalWrite(LEDRedPin,HIGH);
    LEDRedState=1;
    digitalWrite(RELAYRedPin,LOW);
    RELAYRedState=1;

    digitalWrite(LEDYelPin, HIGH);
    LEDYelState=1;
    digitalWrite(RELAYYelPin, LOW);
    RELAYYelState=1;
    delay (8000);
    digitalWrite(LEDYelPin,LOW);
    digitalWrite(RELAYYelPin,HIGH);

    digitalWrite (LEDGrnPin,HIGH);
    LEDGrnState=1;
    digitalWrite (RELAYGrnPin, LOW);
    RELAYGrnState=1;
    delay(2000);
    digitalWrite  (LEDGrnPin,LOW);
    digitalWrite (RELAYGrnPin,HIGH);
    RELAYGrnState=1;
  }
  else{
    digitalWrite(LEDRedPin, LOW);
    LEDRedState=0;
    digitalWrite(RELAYRedPin, HIGH);
    RELAYRedState=0;
    digitalWrite(LEDYelPin,LOW);
    LEDYelState=0;

  }
}
buttonOld=buttonNew;
delay(dt);

}

A general hint first: indent your code correctly. It makes it much easier to read and easier to spot logical errors.

Another improvement would be to name the pins with the same names as you name them when explaining the problem to us. I expected to find a int buttonRunPin and int buttonStopPin.

The first issue I see is:

buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);

This reads the same button twice. You probably wanted to read two different buttons: the "run" button and the "stop" button.

The next issue I see is:

delay(8000);
delay(2000);

During these 10 seconds, you can press and let go the button many times. But since there is no digitalRead() during that time, the button press will not be recognized.

The same applies to

int dt=100;
delay(dt);

If you press the button within these 100 ms, it will not be noticed.

Unfortunately, to fix that, you need to learn a completely new concept: interrupts. And even worse, not all pins support interrupts. On the Arduino Uno, it's only pin 2 and pin 3, which means you would need to change your hardware setup (because you use pin 12 and 13). Put both buttons from the pin to ground, so that it closes when pushed.

You would then prepare the interrupt in the setup() routine:

pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
pinMode(buttonPinOff, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);

You also define global variables for the state of the buttons:

volatile bool running = false;
volatile bool stopped = false;

volatile is needed here to prevent the compiler from optimizing too much. The compiler does not know about the interrupts and thus can't know when the variable changes.

Next, you need two methods that are being executed whenever an interrupt occurs, i.e. you press a button:

void toggleRun() {
    running = !running;
}
void toggleStopped() {
    stopped = !stopped;
}

Note: the above x = !x; pattern is a short and efficient form of

if (x == false) {
    x = true;
}
else if (x == true) {
   x = false;
}

Once you have all that, you don't need the two digitalRead()s any more.

I'm afraid I haven't understood what your code's supposed to do. You have a lot of state variables that seem to have no use and especially they don't correspond to the motors. E.g. once RELAYGrnState is set to 1, it never changes back to 0.

This is what I have in the end:

int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;

volatile bool running = false;
void toggleRun() {
    running = !running;
}

volatile bool stopped = false;
void toggleStopped() {
    stopped = !stopped;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(LEDRedPin, OUTPUT);
  pinMode (LEDYelPin,OUTPUT);
  pinMode (LEDGrnPin, OUTPUT);
  pinMode (RELAYRedPin, OUTPUT);
  pinMode (RELAYYelPin, OUTPUT);
  pinMode (RELAYGrnPin, OUTPUT);

  pinMode(buttonPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
  pinMode(buttonPinOff, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);
}

void doSomething() {
  digitalWrite(LEDRedPin,HIGH);   // red LED is on
  LEDRedState=1;
  digitalWrite(RELAYRedPin,LOW);  // red motor off? others unclear
  RELAYRedState=1;

  digitalWrite(LEDYelPin, HIGH);  // yellow LED and red LED are on
  LEDYelState=1;
  digitalWrite(RELAYYelPin, LOW);  // yellow motor off?
  RELAYYelState=1;
  delay (8000);
  digitalWrite(LEDYelPin,LOW);     // red LED on
  digitalWrite(RELAYYelPin,HIGH);  // yellow motor on

  digitalWrite (LEDGrnPin,HIGH);  // red and green LED are on
  LEDGrnState=1;
  digitalWrite (RELAYGrnPin, LOW);  // green motor off
  RELAYGrnState=1;
  delay(2000);
  digitalWrite  (LEDGrnPin,LOW);    // red LED on
  digitalWrite (RELAYGrnPin,HIGH);  // green motor on
  RELAYGrnState=1;
}

void doLess() {
  digitalWrite(LEDRedPin, LOW);     // red LED off
  LEDRedState=0;
  digitalWrite(RELAYRedPin, HIGH);  // red motor on
  RELAYRedState=0;
  digitalWrite(LEDYelPin,LOW);      // yellow LED off
  LEDYelState=0;
}

void loop() {
  if(running){
    if (!stopped){
      doSomething();
    }
    else{
      doLess();
    }
  }
  delay(dt);
}


Arduino Motor Shield It seems that I can't get the DC Motor function to work while also having servos driven off the other ports :(

#include "Arduino.h"
#include <Servo.h>

int pinI1=8;//define I1 interface
int pinI2=11;//define I2 interface
int speedpinA=9;//enable motor A
int pinI3=12;//define I3 interface
int pinI4=13;//define I4 interface
int speedpinB=10;//enable motor
int spead =220;//define the spead of motor

Servo SteeringServo;  // create servo object to control a servo

void setup()
{
  // Steering servo pin setup
  SteeringServo.attach(5);  // attaches the servo on pin 9 to the servo object

  pinMode(pinI1,OUTPUT);
  pinMode(pinI2,OUTPUT);
  pinMode(speedpinA,OUTPUT);
  pinMode(pinI3,OUTPUT);
  pinMode(pinI4,OUTPUT);
  pinMode(speedpinB,OUTPUT);

  Serial.begin(9600);

}

void forward()
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
     digitalWrite(pinI3,LOW);
     digitalWrite(pinI2,LOW);//turn DC Motor A move anticlockwise
     digitalWrite(pinI1,HIGH);
}
void backward()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
     digitalWrite(pinI3,HIGH);
     digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
     digitalWrite(pinI1,LOW);
}
void left()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,HIGH);//turn DC Motor B move clockwise
     digitalWrite(pinI3,LOW);
     digitalWrite(pinI2,HIGH);//turn DC Motor A move clockwise
     digitalWrite(pinI1,LOW);
}
void right()//
{
     analogWrite(speedpinA,spead);//input a simulation value to set the speed
     analogWrite(speedpinB,spead);
     digitalWrite(pinI4,LOW);//turn DC Motor B move anticlockwise
     digitalWrite(pinI3,HIGH);
     digitalWrite(pinI2,LOW);//turn DC Motor A move clockwise
     digitalWrite(pinI1,HIGH);
}
void stop()//
{
     digitalWrite(speedpinA,LOW);// Unenble the pin, to stop the motor. this should be done to avid damaging the motor.
     digitalWrite(speedpinB,LOW);
     delay(1000);

}

void loop()
{
  left();
  delay(15000);
  stop();
  right();
  delay(1000);
 stop();
 // delay(2000); Already commented out
  //forward();
 // delay(2000);
 // stop();
// backward();
  delay(12000);
  stop();
}

Your code:

int speedpinA=9;//enable motor A
...
int speedpinB=10;//enable motor
...
 analogWrite(speedpinA,spead);//input a simulation value to set the speed
 analogWrite(speedpinB,spead);

See https://www.arduino.cc/en/reference/servo

  On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

(My emphasis).

So, you can't do that, exactly. Perhaps choose other pins for the analogWrite, pins that analogWrite supports, that are not 9 and 10.


Why Won't my Serial Read value stay the same I am trying to write to serial to control the brightness of an LED. When I initially type in a value such as '50' or '100', the LED lights up, but then the 'ppm' value drops down to '10' and just stays there (regardless of what I enter in initially. Any idea why this is occurring?

int ledpin1 = 3;
int pwm = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(ledpin1, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // reads input to serial monitor
  if (Serial.available() > 0) {
    pwm = Serial.read();
  }

  analogWrite(ledpin1, pwm);
  Serial.print("PWM value is: ");
  Serial.println(pwm);
  delay(1000);

}

When you type "100" you aren't sending the number 100. You're sending the characters "1", "0", "0", and whatever selected line ending you have (CR, LF, or CR and LF).

So if you have CR+LF for your line ending you're reading the numbers 49, 48, 48, 13 then 10.

You need to read the characters as they arrive and group them into a representation of the number (up until you get the line ending), then convert that representation into an actual number.

Reading Serial on the Arduino


How to use the HC-05 properly? It all started when I was working on my Arduino project, which involves an Arduino Nano, an HC05 module and a bunch of sensors (DHT 11, soil moisture and LDR) with Blynk App. Everything worked as it should (compiled properly) but there was no transfer of data (HC05 was paired).

At that time before pairing, the HC05 was blinking rapidly and after pairing it was blinking twice rapidly every 5 seconds. Note I connected everything as the example said... (You know HC05s TX RX to HW Serial Pins vice-versa).

So later I tried again with everything stripped out (took out all sensors and just the barebones sketch) and added the button widget in the app to control the Nano's onboard LED). Again everything worked as it should but there was no connection between the HW and the Blynk APP (it was not switching on the LED).

Then I tried with an another Bluetooth app and it didn't work as it should. Then I got to know something's wrong with the board itself. So I tried to boot it into AT command mode with this Guide. But it wasn't accepting any commands (NO replies).

So what do I do?

NOTE: I didn't get any relevant question so sorry for that. And do you need anything else?

Edit: It worked. I dont really know how. I think there was maybe a problem with the voltage divider but not sure. Thanks for your time and answers.

Maybe you use the wrong baudrate with your hardware serial. Your tutorial states, that 38400 baud is the default, but I found other sources (HC-05), that say the default is 9600 baud (which is also true for my HC-06 modules). Try 9600 baud and if it still doesn't work try some other standard baudrates.


Low power + Logging motion detection Scenario: I would like to monitor my closet's door as I highly suspect a family member is opening and using my items without permission. To respect privacy and also because my closet is nowhere near a power mains, I don't need video nor audio recording. I also do not need indicator lights etc because I intend to turn it on when I go to work and check the logs on the SD card when I return home. A typical day would require the device to run for 12 hours minimally.

Aim: Is it possible for Arduino to achieve the following,

Run on batteries for at least 1 month
Detect motion
Logging the detection motion onto a text file in a SD card

Or do I have to look elsewhere for this functionality?

Current understanding: I am aware Arduino can run on batteries though I've never been able to get it to last more than 3 hours. Probably has to do with me not using the low power mode or something and that my batteries were being stepped up. I also know that Arduino has some PIR motion sensors though I don't quite remember how power hungry these sensors are. I have NEVER tried logging onto an SD card using Arduino. This sums up my experience with Arduino.

Any advice would be much appreciated. Thank you.

You would be better off with a bare ATmega chip than an Arduino - you want to eliminate extraneous circuitry like a USB converter, regulators with quiescent current draw, and any resistors pulling signals against their usual state.  Fortunately the ATmega chip has a fairly wide voltage range, especially at 8 MHz or below, so you can use something like 3 cells, alkaline or rechargeable, over most of their range.

An SDcard is neither necessary, nor a good idea.  If your circuit won't be discovered you can probably hold the data in static ram while the ATmega sleeps; if not, the quantity of data would probably not exceed the on-chip EEprom and would certainly not exceed that of a 4 megabyte SPI flash. Either of these will be far more robust (and low power) in a battery powered situation than an SD card.  They will also be simpler to support in software.  Either an SPI flash or an SDcard will probably have a narrower supply range the the ATmega and require a regulator - you may be able to enable that only when you need to access the memory.

Your main power consumption win however will be sensors.  If you can use a contact sensor - either a direct switch, or a magnetic reed one, that will result in the lowest power consumption.  Your next option might well be an accelerometer chip, specifically if you choose one which can run in a micropower mode and fire a wakeup interrupt to the MCU when it detects that a door it is mounted on is being opened.  Anything with light is likely to have much higher power consumption and could well be impractical, unless you figure out how to operate it in short bursts with a lengthy inactive time in between.


Expected unqualified ID before numeric constant After debugging and having some conflicting declarations about analog pins, I finally thought it was done, after compiling I got this error:

32:0,
1:
31:12: error: expected unqualified-id before numeric constant

2:5: note: in expansion of macro 'B1'

I can't understand what this means. What's wrong with my code down here?

// don't judge me if it's too long and overcomplicated :P I'm still new xD
int AA1 = 0;
int B1 = 1;
int C1 = 2;
int D1 = 3;
int AA2 = 4;
int B2 = 5;
int C2 = 6;
int AA3 = 8;
int B3 = 9;
int C3 = 10;
int D3 = 11;
int B4 = 12;
int C4 = 13;
int sec = 0;
int min1 = 0;
int min2 = 0;
int hour1 = 8;
bool hour2 = 0;

void setup() {
  pinMode(AA1, OUTPUT);
  pinMode(B1, OUTPUT);
  pinMode(C1, OUTPUT);
  pinMode(D1, OUTPUT);
  pinMode(AA2, OUTPUT);
  pinMode(B2, OUTPUT);
  pinMode(C2, OUTPUT);
  pinMode(AA3, OUTPUT);
  pinMode(B3, OUTPUT);
  pinMode(C3, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(B4, OUTPUT);
  pinMode(C4, OUTPUT);
}

void loop() {
  OutputOn();
  delay(1000);
  sec++;
  if(sec == 60) {
    sec = 0;
    min1++;
      if(min1 == 10) {
      min1 = 0;
      min2++;
        if(min2 == 6) {
        min2 = 0;
        hour1++;
          if(hour1 == 10) {
          hour1 = 0;
          hour2 = 1;
        }
        if(hour2 == 1, hour1 == 3) {
          hour1 = 1;
          hour2 = 0;
        }
      }
    }
  }
}

void OutputOn() {
  digitalWrite(B1, LOW);
  digitalWrite(C1, LOW);
  digitalWrite(D1, LOW);
  digitalWrite(A2, LOW);
  digitalWrite(B2, LOW);
  digitalWrite(C2, LOW);
  digitalWrite(A3, LOW);
  digitalWrite(B3, LOW);
  digitalWrite(C3, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(B4, LOW);
  digitalWrite(C4, LOW);
  if(min1 == 1) { digitalWrite(AA1, HIGH); }
  if(min1 == 2) { digitalWrite(B1, HIGH); }
  if(min1 == 3) { digitalWrite(B1, HIGH); digitalWrite(AA1, HIGH); }
  if(min1 == 4) { digitalWrite(C1, HIGH); }
  if(min1 == 5) { digitalWrite(C1, HIGH); digitalWrite(AA1, HIGH); }
  if(min1 == 6) { digitalWrite(D1, HIGH); digitalWrite(B1, HIGH); }
  if(min1 == 7) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); digitalWrite(B1, HIGH); }
  if(min1 == 8) { digitalWrite(D1, HIGH); }
  if(min1 == 9) { digitalWrite(D1, HIGH); digitalWrite(AA1, HIGH); }
  if(min2 == 1) { digitalWrite(AA2, HIGH); }
  if(min2 == 2) { digitalWrite(B2, HIGH); }
  if(min2 == 3) { digitalWrite(B2, HIGH); digitalWrite(AA1, HIGH); }
  if(min2 == 4) { digitalWrite(C2, HIGH); }
  if(min2 == 5) { digitalWrite(C2, HIGH); digitalWrite(A2, HIGH); }
  if(min2 == 6) { digitalWrite(C2, HIGH); digitalWrite(B2, HIGH); }
  if(hour1 == 1) { digitalWrite(AA3, HIGH); }
  if(hour1 == 2) { digitalWrite(B3, HIGH); }
  if(hour1 == 3) { digitalWrite(B3, HIGH); digitalWrite(AA3, HIGH); }
  if(hour1 == 4) { digitalWrite(C3, HIGH); }
  if(hour1 == 5) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); }
  if(hour1 == 6) { digitalWrite(C3, HIGH); digitalWrite(B3, HIGH); }
  if(hour1 == 7) { digitalWrite(C3, HIGH); digitalWrite(AA3, HIGH); digitalWrite(B3, HIGH); }
  if(hour1 == 8) { digitalWrite(D3, HIGH); }
  if(hour1 == 9) { digitalWrite(D3, HIGH); digitalWrite(C3, HIGH); }
  if(hour2 == 1) { digitalWrite(B4, HIGH); digitalWrite(C4, HIGH); }
}

It's supposed to be code for a clock (if it wasn't obvious enough) hooked up to 4 7-segment decoders, also connected to 4 7-segment LED displays.

Bad luck. There is a file within Arduino called "binary.h", and it contains a define called "B1". Which means you may not use "B1" as a variable. In my opinion, that file "binary.h" is totally unnecessary.

In the preferences you can turn on extra output for the compiler and turn on line numbers. The compiler will tell what is wrong, but you have to know how the compiler does that. The first compiler error is the most important.

".../hardware/arduino/avr/cores/arduino/binary.h:31:12: error: expected unqualified-id before numeric constant #define B1 1" means that the compiler was reading the file "binary.h" and at line 31 it noticed something it did not understand and it has to do with "B1".


Uploading sketch problem I just plugged my arduino and click upload, it shows this error:

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

Sketch uses 948 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

In the Arduino IDE check for the available ports. Be sure that the COM Port on Windows or ACMO port on Linux based OS is selected.

If the problem continues then check if the port is allowed in Windows and Linux.


First time arduino attempt. 4 switch inputs controlling 8 LED outputs This is my first venture into Arduino. I am unsure which one to use even for this. As this will be a dedicated unit, and size is a small priority, the smaller the better.

Here is more info on the scheme I am looking for.

Switch 1 on turns on LED groups 1 and 2

Switch 2 on turns on LED groups 3, 4, 5, 6, 7 and 8

Switch 3 on turns on 1 for say 500 ms, then turns 1 off, turns on 3 for 500 ms, then turns off 3, then turns on 5 for 500 ms, then turns off 5, turns on 7 for 500 ms, then turns off 7, then loops back and turns on 1 repeating the cycle.

Switch 4 on turns on 2 for say 500 ms, then turns 2 off, turns on 4 for 500 ms, then turns off 4, then turns on 6 for 500 ms, then turns off 6, turns on 8 for 500 ms, then turns off 8, then loops back and turns on 2 repeating the cycle.

Will I need an Arduino uno, nano or micro?
I am hoping this will be an easy to do project in order to learn the world of Arduino

Micheal well easy solution is to use arduino nano as its bread board friendly and easy as it comes with the arduino IDE installed, well if size is what you are looking for then digispark attiny 85 can also do the task and its size is almost equal to a coin but for that youll need to install it in the arduino IDE which is a bit difficult.
if you need any help with attiny 85 you can come here


Reading and processing a PWM on AtTiny45 I have this question and I can't find answers!

I wanted to use an AtTiny45V (due to low voltage requirements, it will run at 1.8 volts) to read a PWM from an Arduino, and then process this information.

Explained better:

let's say, I hook up one pin of the AtTiny to an Arduino pin (named connection), and in the IDE I write:

AnalogWrite(connection,X)

I want the AtTiny to write high on a port based on the X value.

Example:

X = 20 writes high on AtTiny PB5

X = 25 writes high on AtTiny PB5 and PB3

etc...

So, basically I want to read the duty cycle from the Arduino PWM and let the AtTiny do something based on duty cycle value.

Is this possible?

Thanks

You don't need to read the duty cycle, just the time that the PWM signal is high. First wait for the input pin to go high, then start a timer, wait for the signal to go low again, and finally read the timer value. If other tasks need to be performed concurrently then use pin change interrupt to detect the high and low transitions.

If the ATtiny is running Arduino software then the solution is even easier - just use the pulseIn() function.

This technique works for all PWM values except 0 and 255. With these values the pin stays low or high permanently, so there are no transitions to time. The easiest way around this is to simply avoid transmitting 0 or 255.

Alternatively you could pass the PWM signal through an RC filter to produce a 'DC' voltage, then read it with the ADC. However this will slow the response time down, and the signal will produce intermediate values as it goes from one voltage to another. To get good resolution the RC filter would need to have a long time constant, and you might have to average several readings to get a stable value.


Voltage on analog pin arduino when arduino turned off So can I put a voltage from 0v to 5v on an analog Arduino pin before actually turning the Arduino on? And still read the analog pin correctly when turned on?

All the GPIO pins have protection diodes in them. The are arranged, effectively, like this:

simulate this circuit – Schematic created using CircuitLab

The internals of the ATMega chip can be visualised for this purpose as a small resistor:

simulate this circuit

If you apply a voltage to the input without anything applied to Vcc you effectively connect the input to ground through the diode and the internals:

simulate this circuit

That means that too much current flows through the diode and potentially breaks it. And that's the least of your worries. The rest of the circuitry in the chip is subject to the same rules - any voltages that can flow back up to the Vcc rail the wrong way through parts of the circuitry in order to get down to ground risk breaking things.

It's almost as bad as connecting the power to the chip backwards. In effect your GPIO pin is acting as Vcc and powering the chip - badly.


Can't replace SoftwareSerial by Serial1 on Mega board This sketch runs well with SoftwareSerial define and the monitor displays device modbus values. But now, i want to replace SoftwareSerial by Serial1
and i have no data.

This is the sketch with SoftwareSerial:

#include <SoftwareSerial.h>
#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  RS485Serial.begin(9600);
}
void loop()
{
  delay(500);
  if (RS485Serial.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = RS485Serial.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  RS485Serial.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

And the sketch i tried with Serial1 (pin 19(Rx) and 18(Tx)):

#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  Serial1.begin(9600);
}
void loop()
{
  delay(500);
  if (Serial1.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = Serial1.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  Serial1.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

Can you help me to find my mistake ?

what is the best way to solve it, using Serial1?

With either serial device, you need to collect characters until you have an entire message. If every message will be a fixed number of bytes, you can wait until the return value of the Serial::available() call indicates it has that many characters, then collect them into a buffer and process them. But this assumes you'll never get a badly-formed message. If you do, the incoming bytes will get out of sync with your program.
A better way is to collect bytes into your buffer (but do nothing with them) until you have a complete message (by byte-count, newline character, or however you need to recognize that it is complete) or your buffer is about to overflow, and then either process them, or if your buffer filled and the contents doesn't look like a valid message, discard it and try to re-synchronize with the source. That may mean reading and ignoring bytes until you get a newline, and dealing with the fact you got a garbled message, or telling your source to restart or reset. The exact method (or whether you even want to bother detecting bad messages) depends on the particular situation. Will someone die if you fail? Will something catch fire, burn parts, lose weeks worth of good data, ... ? Or is this an experiment whose consequence of failure are zero or at least not worth any effort to detect it?


5v to 4.3v Regulator - For SIM800 module I want to build a simple voltage regulator  3.8-4.2V with atleast 2A Peak Current Capability for my GSM Shield (It doesn't have regulated power supply), I don't want variation or it may burn the board.

Using voltage divider won't help here as there can be variations.
Somewhere i read LDO are for for this task but i am able to get only 3.3v regulator with 800mA supply.

Can i use 3.3v to power the same ?

I planned to use 3.7v LIPO battery

That's what your SIM800 module is intended to be directly powered by, without any intervening boost or buck converter.

Behind all the misdirection of a title that doesn't describe what you are actually trying to do, your question is an exercise in going around in a circle right back to where you started.  Don't try to convert energy from the lithium cell to some other voltage and then from there to the allowed input range of the SIM800 (which is very intentionally that of a single lithium cell), rather use the parts as they were intended to be used.

  i guess it has current 800mA..

No, it has a capacity of 800 milliamp hours, not 800 milliamps.

A phone or RC model type lithium cell you would find today would have a "C" rating of 10 or better, but even if we assumed one of only 5, that would predict that your cell should be expected to be able to support pulse loads of 5 times the one-hour draw rate, which would be .8 * 5 = 4 amps.


Why cannot I input arrays as digitalWrite arguments? I am making my own "7 segment LED driver". I know there is a lot of examples on the internet, I just want to try my own. But I have a piece of code that does not work and I don't know why. Can somebody explain to me why it is not working?

When I put in this, it works:

digitalWrite(pins[0], one[0]);
digitalWrite(pins[1], one[1]);
digitalWrite(pins[2], one[2]);
digitalWrite(pins[3], one[3]);
digitalWrite(pins[4], one[4]);
digitalWrite(pins[5], one[5]);
digitalWrite(pins[6], one[6]);

So of course I tried using for():

for (byte i = 0; i >= 6; i++)
  {
    digitalWrite(pins[i], one[i]);
  }

And this does not work. But why? I think it should. Btw. pins is const byte array and one is const bool array.

Thanks in advance for any suggestions!

You've written the for loop incorrectly.

for (byte i = 0; i >= 6; i++)   <-- ERROR HERE
  {
    digitalWrite(pins[i], one[i]);
  }

That first line should be for (byte i = 0; i <= 6; i++). i begins at zero, which is less than six, and the loop only runs while i is greater than 6.


When I connect the Vcc and GND of my circuit to my Arduino, it is powered off? When I connect the Vcc and GND of my circuit to the 5v and GND in my Arduino, it is powered off and stops working. What is the reason and how shall I fix it?

Reference: Serial to Parallel Shifting-Out with a 74HC595

Note: if you are changing something have the power off.

The first thing to try is unplug the IC. If it powers up after the IC is removed it is Possibly the IC is bad; However measure the Voltages on the proto board where the IC is inserted, be sure Pin 16 is +5V when referenced to pin 8.  Check the data sheet for the correct pinout, I do not know what IC you are using. If the voltage is correct it is pointing more to a bad IC.

The final check for the IC is to insert the IC and remove the ground lead to the LEDs.  If the system comes up then the problem is not enough power to drive the LEDs as is. If it does not come up replace the IC.  Even a momentary reverse voltage or a ESD (Electro Static Discharge) incident will damage the IC, we know is is going to fail, we do not know when.

Be sure your resistors are at least 300 Ohm or higher, with that resistance the LEDs when all on will draw a total of 80mA. If you want to do the calculations try this link: "http://www.onlineconversion.com/ohms_law.htm".

If you want to check the LEDs, remove the IC and connect +5V one at a time to the wire that goes to the resistor from the IC.
Good Luck,
Gil


Keep Alive for Arduino Sometimes the arduino locks up for some reason. It would be nice to know why, but the problem is more general. I have found a hardware keep alive that resets the controller if it doesn't respond:
Arduino Keep Alive with AT-Tiny
This would work, but i wonder if there are there features like this built in to any of the processors that can be used in the Arduino environment (ESP8266, ESP32, or the like).
Maybe folks know of a processor with the "Keep Alive" feature?
How would i determine if this "keep alive" feature is present for a specific processor?
Thanks for any suggestions!
Mark

Reference link: https://create.arduino.cc/projecthub/rafitc/what-is-watchdog-timer-fffe20

Watchdog timers can be found in the datasheet. If there is no intervention to this module by the software, the MCU will be reset. basically, restarting all the functions.
It is a bad idea to use WDT to solve your particular topic. You should try to fix the issue
The external watchdog timers (Example: ADM8320) is more reliable than internal ones


Arduino - Function -> return Cstr instead of string I have following function for my Arduino:
String readLine() {
  String received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n' or ch == '\r') {
      if (ch == '\r')
      {
        //get rid of the \n
        myFile.read();
      }
      return String(received);
    } else {
      received += ch;
    }
  }
  myFile.close();
  hasFile = false;
  return received;
}

This function is used to return a line from a text file on a SD card. Since I do have to do quite some things on the returned string, I would like to have it as cstr instead of string to increase performance. But I am not able to convert this function to one that returns a Cstr. I tried this but it does not work:
char* readLine() {
  char* received = "";
  char ch;
  while (myFile.available()) {
    ch = myFile.read();
    if (ch == '\n' or ch == '\r') {
      if (ch == '\r')
      {
        //get rid of the \n
        myFile.read();
      }
      return received;
    } else {
      received += ch;
    }
  }
  return received;
}

Currently I am converting it after the function returns it, by using c_str(). It works, but I dont like it and would like to return a Cstr in the first place.
How can this be done?
Thank you!

You cannot work with c-strings like with Strings. You need to use the standard c-string functions (like sprintf(), strcpy() and siblings) or directly access the char array.
This gives the following problems with your code:

See this line:
  char* received = "";

Here you create a pointer to a constant empty string. But this will NOT create a buffer, where you can put data. If you want to define a buffer to put the data in, you need to define an array:
  char received[30] = "";

where 30 is the size of the array and thus the buffer has space for 29 characters (30 minus the one character, that is needed for the terminating null character). Now you could use a counter variable to save the current position in the buffer and set the array elements to the received character:
  int position = 0;
  ...
  received[position] = ch;
  position++;

Then, when you reached the end of the buffer or you received end of line, you would end the data in the buffer with the null character:
  if (ch == '\n' || ch == '\r' || position == 29) {
      if (ch == '\r')
      {
          //get rid of the \n
          myFile.read();
      }
      received[position] = '\0';

Now you have the second problem: When defining a variable inside the function, it will become invalid, when you exit the function. You try to return a pointer to char, which will point to a non-valid memory location. Thus you cannot simply return an array, that was created inside the function (outside of dynamic allocation). Here commonly an external buffer is provided to the function by reference as a pointer. The function will then write into that buffer and does not need to return it.
  //defining the array outside of the function, for example at global scope
  #define BUFFER_SIZE  30
  char received[BUFFER_SIZE] = "";
  ...
  void readLine(char *buffer, int size) {
      ...
      // Here you can use buffer as a simple char array
      buffer[position] = ch;
  }

Here I also provide the size of the array as parameter, so that the function can make sure not to exceed that (because that will give you bad and difficult to troubleshoot problems). Then, when the function has run, the read data is now in the received character array. This way you don't need to use multiple buffers and also don't need to copy data between buffers.


Is it possible to count rising edges of a 4 MHz clock on an Arduino Due and trigger an interrupt like all 4'000'000 edges? I am struggling with my Arduino Due and the Timer Counter functionallity. The following is what I am trying to achieve:

I want to execute a function to a specific point of time or more precisley after a specific amount of rising edges given by an external clock signal with a frequency of approx. 4 MHz. Thus I read the Atmel Datasheet, Section 36, Timer Counter. My approach was to trigger an interrupt every rising edge and increment a counter variable until I reached the desired amount of rising edges and call my function then. I can confirm that I am in fact counting rising edges with my current approach but I am reading way too slow. Is there any kind of register or hardware counter which automates the counting process. Like I set the register to a specific value and wait for an overflow, execute my function and reset the register? From my web research I found that this is possible on the Uno and Mega but I could not find anything for the Due and to be honest I am a bit overwhelmed by the Atmel Datasheet. Why not just use an Arduino Due or Mega then? I need the 3.3 Volts of the Due and from what I found the Uno and Mega are 5 V devices.

This is my code:

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

// clock divisors corresponding to CAPTURE_CLOCK_SELECTION
static const uint32_t divisors[5] = { 2, 8, 32, 128, 0};

volatile uint32_t captured_pulses = 0;
volatile uint32_t captured_ra = 0;
volatile uint32_t captured_rb = 0;
volatile float frequency, duty_cycle, active_time;

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_LDRB_FALLING     // RB Loading: falling edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_ETRGEDG_FALLING  // External Trigger Edge: Falling edge
 );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);
  NVIC_EnableIRQ(CAPTURE_IRQn);

  // enable interrupts
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_LDRBS;

  // start timer counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Loop code. Will be executed repeatedly after setup completed.
*/
void loop() {

 // Serial.print("Captured rising edges: "); Serial.println(captured_ra);
} // loop

/*
* Function:  CAPTURE_Handler
* ------------------------------------------------------------------------------
*
*/
void CAPTURE_Handler() {
 if ((TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL) & TC_SR_LDRBS) == TC_SR_LDRBS) {
   captured_pulses++;
   // captured_ra = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RA;
   // captured_rb = CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RB;

   if (captured_pulses == 4164303) {
    captured_pulses = 0;
    // specific_function_call();
   }
 }
} // CAPTURE_Handler

Thanks for your time, any help is grealty appreciated.

First of all excuse my inactivity but as you know it's crazy times right now. However I finally figured it out, it's for sure not the most elegant solution but it meets my requirements. Thanks for your help @KamilCuk.

Here is my code if anyone may ever have the same problem as I did. External signal goes on Digital Pin 2. Works fine with a 4.2 MHz external clock.

// define capture channels
#define CAPTURE_TC TC0
#define CAPTURE_CHANNEL 0
#define CAPTURE_IRQn TC0_IRQn
#define CAPTURE_Handler TC0_Handler
#define CAPTURE_ID ID_TC0
#define CAPTURE_PIN 2
#define CAPTURE_CLOCK_SELECTION TC_CMR_TCCLKS_TIMER_CLOCK3

/*
* Function:  setup
* ------------------------------------------------------------------------------
* Setup code. Will be executed once.
*/
void setup() {

  // init serial connection
  Serial.begin(115200);
  Serial.print("Initializing...");

  // configure the PIO pin as peripheral
  const PinDescription *config = &g_APinDescription[CAPTURE_PIN];
  PIO_Configure(config->pPort, config->ulPinType, config->ulPin, config->ulPinConfiguration);

  // enable timer peripheral clock
  pmc_enable_periph_clk(CAPTURE_ID);

  // configure the timer
  TC_Configure(CAPTURE_TC, CAPTURE_CHANNEL,
    CAPTURE_CLOCK_SELECTION   // Clock Selection
    | TC_CMR_LDRA_RISING      // RA Loading: rising edge of TIOA
    | TC_CMR_ABETRG           // External Trigger: TIOA
    | TC_CMR_CPCTRG           // RC Compare
  );

  // configure TC interrupts
  NVIC_DisableIRQ(CAPTURE_IRQn);
  NVIC_ClearPendingIRQ(CAPTURE_IRQn);
  NVIC_SetPriority(CAPTURE_IRQn, 0);

  // enable interrupts and start counter
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_IER = TC_IER_CPCS;                  // enable RC Compare Interrupt
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_CCR = TC_CCR_CLKEN | TC_CCR_SWTRG;  // the datasheet said I need this
  NVIC_EnableIRQ(CAPTURE_IRQn);                                                  // enable interrupts

  // set the trigger value for RC_Compare
  CAPTURE_TC->TC_CHANNEL[CAPTURE_CHANNEL].TC_RC = 4164303;

  Serial.println("ready!");

} // setup

/*
* Function:  loop
* ------------------------------------------------------------------------------
* Main code. Will be executed repeatedly.
*/
void loop() {

} // loop

/*
* Function:  CAPTURE_Handler respectively TC0_Handler
* ------------------------------------------------------------------------------
* Timer capture trigger. Will be executed if TC0_RA == TC0_RC
*/
void CAPTURE_Handler() {
  // reset status register
  TC_GetStatus(CAPTURE_TC, CAPTURE_CHANNEL);

  // do something
  Serial.println("Trigger");
  // function_call()
}


Digispark clone not recognised when plugged in When I plug in my digispark clone the computer doesn't make any sounds or some kind of acknowledgement that it has been plugged in. Anyone know why this may be or is it just a dodgy clone?

The Digispark does not use a "standard" USB-to-Serial chip but is dependent on a special bootloader called "micronucleus" that makes it (sort of) act like a USB device.

Below is a description of the steps you need to perform for a Windows system and the Arduino IDE.

First, you will need to install a Windows driver for Micronucleus: Zadig USB driver

If your ATTiny is recognized by Windows after performing the driver installation, then all is fine and you can skip to step 4.

If Windows still does not recognize your Digispark clone, its ATTiny processor might not have come with micronucleus pre-programmed and you need to perform steps 2 and 3. Unfortunately this is for advanced users and might be difficult if you're inexperienced with electronics and/or Arduino.

Download Micronucleus from Github
Follow This tutorial from Digispark to install micronucleus on your ATTiny. You will need another Arduino (Uno, Nano, Mega, Mega2560, ... or clone) for that.
Then follow This tutorial from Digistump to enable the Arduino IDE to program your Digispark clone directly from USB.


No "Huge APP partition scheme" (ESP32) I recently downloaded the expressif ESP32 library and I'm trying to run the CameraWebServer example. Attempting to compile it results in the following error:
Sketch uses 2529577 bytes (192%) of program storage space. Maximum is 1310720 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.

I can reduce this number (192%) to 120% by changing partition scheme from "Default" to "No OTA (Large APP)". Online I've seen people using a partition scheme called "Huge APP", which I believe would solve my problem, but I don't see that option in Tools. Only "Default", "Large App" and "Minimal SPIFFS" (which doesn't work either).
How can I get the "Huge APP" partition scheme option in Arduino IDE?

I was able to fix the issue by editing the boards.txt file and adding the following lines:
lolin32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
lolin32.menu.PartitionScheme.huge_app.build.partitions=huge_app
lolin32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728

This will add a "Huge APP" partition scheme to WEMOS Lolin32.


Are the GND pins of an Arduino identical to GND of its power supply? What would happen if I connected a fan as shown in the following picture:

+12V is supplied by the power supply that also powers the Arduino.
GND, however, is connected to a GND pin of the Arduino instead of the power supply.

I guess that would not work? Or are GND from the Arduino and GND from the power supply identical in this case?

If you read the accepted answer, please also note the comments below. The power consumption of the consumer (fan) is important.

"Ground" is just a lump of metal and each ground "pin" is connected to it. That includes the ground connection in the barrel jack. It's all one thing.
Wherever you connect your fan's ground to it's all ground.  That is, as long as all grounds external to the Arduino are connected, ultimately, to the Arudino.


Arduino Fio and BC127 communication I am using an ArduinoFio and a BC127 (datasheet). I'm having troubles getting the serial connection working properly from the Arduino to the BC127 and viceversa. I wasn't able to communicate with the BC127 and I don't know if is because isn't correctly powered on or something else.

I've connected pin 0 of the BC127 to GND, pin 33 to 3V3 and pin 41,42 (RX, TX) to the TX, RX arduino's pins.

I've tested with the tester that all wires are connected, but the BC127 seems dead.

Any help is appreciated :|

There's a couple of things I would try.

First: Don't use the native Arduino TX/RX pins, they should be left alone to talk to the computer. Use SoftwareSerial instead in start a separate serial connection.

Second: Check that Arduino TX pin (that you declared in softwareSerial) is connected to the BC127 RX and vice versa. Unlike just about every other connection in electronics, serial connections need to have their pins reversed so that TX talks to RX. It's an easy mistake to make and one I've made when not paying attention to what I was doing.

Third: Flow control.

If the BC127 sends data when the Arduino isn't listening the data could be lost, to prevent this the BC127 won't send until the Arduino signals it is ready through flow control.
See the BC127 datasheet page 8, pins 40 and 43. Trying tying UART_CTS to 3V3 and UART_RTS to Ground. That should cause the BC127 to be in a constant 'send' state.

Lastly I'd hook up a couple of LEDs to pins 37 and 38. They should give you some sort of status indication that could be useful in debugging future problems.


Send big amouts of data to PHP script via gsm module SIM800L I'm looking for a way to get lots of sensory data from my Arduino Micro to a PHP script.
My current attempt is using the following AT-commands:

Sent: [AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54]
Res: [AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_]

As you can see I send a long GET-parameter to my server with shortened parameter Names like t0 for temperature sensor number zero, l for light and so on.

In the response from my SIM800l I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.

After that command when it tries to finish the HTTP request I get a lot of errors as AT-command responses and no GET data arrives on my script.

I check wheter or not data has arrived with the following function on my server:

ob_start();
echo "Var_dump of GET\n";
var_dump($_GET);

echo "Var_dump of POST\n";
var_dump($_POST);
$vd_res = ob_get_clean();

file_put_contents('postdump.log', $vd_res."\n",FILE_APPEND);

When typing some data directly into the browser it saves my sent data in postdump.log so I'm pretty sure the SIM-module can't handle the given amount of data.

Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

Do you have any idea how I can send bigger amounts of data all at once? For energy saving purposes I would prefer if it would be possible in only a single request.

Do a POST request. You can send huge amounts of data in the body.

  In the response from my SIM800l I get back a string with exactly 63 characters, so I assume there's some lenght limitation there on the SIM-module.

Nope.

I guess you're doing something like:

sendCommand("AT+HTTPPARA=URL,www.example.com/newData.php?data=t0_20.75,l_0.00,m_584,h_42,td_22,d_21x44x54");
delay(1000);
printResponse();

The problem there is that you're relying on the internal buffer of SoftwareSerial (or HardwareSerial if you use a real serial port). You wait for a predefined time for characters to arrive, and then after that time print them out.  The serial code has a 64 byte buffer.

I see that kind of code all over the place, and it's the worst possible way of reading serial. Whoever posted the first instance of such code and started this chain of evil should be taken outside and shot.

Instead you must read the serial properly. Being lazy like that doesn't work.

Read this blog post to learn more about reading serial data properly.


estimating battery run time I have a project which runs a continuous loop and listens for the push of a button to light an led and activate a servo motor on an Arduino Uno (R2). The arduino is powered by 4 AA batteries, and the servo is powered by a 9V. I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this? As a side note, if anyone spots a way to improve battery life in my sketch / wiring, I'd love to know.

Below is my code and attached is the wiring diagram for the project (minus the batteries).

    #include <Servo.h>

const int buttonPin = 2;     // the number of the pushbutton pin
boolean buttonPushed = false;

const int ledPin =  13;      // the number of the LED pin

const int servoPin = 9;
Servo servo;
int angle = 0;
int servoStartAngle = 90;
int servoEndAngle = 10;

boolean servoActivated = false;

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int photoCellPin = 2;
int photoCellThreshold = 500;
int photoCellActivated = false;

void setup() {
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);

  servo.attach(servoPin);
  servo.write(servoStartAngle);

}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  int photoCellVal = analogRead(photoCellPin);

  if (photoCellVal > photoCellThreshold){
   photoCellActivated = true;
  } else {
   photoCellActivated = false;
  }

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW && buttonPushed == false) {
    // turn LED on:
    buttonPushed = true;
    Serial.println("button pushed");
  } else if (buttonState == LOW && buttonPushed == true){
   buttonPushed = false;
   Serial.println('deactivate');
  }

  if (buttonPushed == true){
   digitalWrite(ledPin, HIGH);
  } else {
   digitalWrite(ledPin, LOW);
  }

  if (buttonPushed && servoActivated == false && photoCellActivated == true){
    servoActivated = true;
    Serial.println("activate motor");

    for(angle = servoStartAngle; angle > servoEndAngle; angle--){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
  } else if (buttonPushed == false && servoActivated == true){ //deactivate
    for(angle = servoEndAngle; angle < servoStartAngle; angle++){
      servo.write(angle);
      Serial.println(angle);
      delay(15);
    }
    delay(200);
    servoActivated = false;

  }

  delay(200);
}

I'm wondering how long I can leave this running off battery power. Does anyone know how to estimate this?

If your circuit draws 1A @ 12V, a 12V 1Ah battery will power it for approximately one hour. A 9V alkaline typically contains about 565mAh. You can use the datasheets to sum all the power consumption, but its probably easier just to measure it with a multimeter.

  As a side note, if anyone spots a way to improve battery life in my
  sketch / wiring, I'd love to know.

-Check out the ATTiny series (parametric); they are tiny, low-power, and Arduino-compatible; perfect when you only need a couple of pins.

-Use an interrupt to monitor the button's pin; the MCU can sleep until the interrupt fires.

Generally:
1) The interrupt will set a flag so main() knows that something happened, then wake the processor.
2) Main() resumes, checks the flag, turns on/off the LED accordingly, tells the servo where to go, waits for the servo to get there (delay()), clears the flag, and then puts the MCU back to sleep.

-As others have pointed out, delay() is bad. delay() tells the MCU to do nothing (NO-OP) repeatedly, for a period of time. This is different from having nothing to do because it's asleep.


How can I make a power button for my project powered by a USB powerbank? I've solved the battery power supply issue for my Arduino project by simply connecting a USB powerbank. However, I just realised that I can't come up with a good way to add an on/off button! There doesn't seem to be a way to turn the Arduino off using software. My second solution would be to cut up the USB cable (or an extension chord) and solder a switch onto the 5V wire.

Is there a more convenient solution that I'm missing?

You could put the microcontroller into sleep-mode. Then use a button (connected to one of the interrupt pins) to wake it up.

But depending on what Arduino board you are using, and what other sensors etc you've connected to the board, this might not save that much current. For example on the UNO board the usb-to-serial converter is always on, so while your MCU is sleeping and trying to save power, the usb-to-serial continues to draw current.

But adding a switch to a usb-cable would be a lot simpler.

PS doesn't the powerbank have an on-off switch?


Arduino power sources Is it safe to connect a USB input to an Arduino (Nano) at the same time as an external regulated 5V supply to its 5V pin is connected, assuming the supplies have common grounds ? Will (I hope) the external 5V be used so as to not draw too much current out of the USB supply ?

From the Arduino Nano at Arduino.CC:

  The Arduino Nano can be powered via the Mini-B USB connection, 6-20V unregulated external power supply (pin 30), or 5V regulated external power supply (pin 27). The power source is automatically selected to the highest voltage source.

Or, take if from the schematic:


MQTT for GSM/GPRS sheild I want to publish sensor data to server using MQTT protocol via GPRS/GSM modem.

I googled MQTT for Arduino, AQTT Arduino available only for Ethernet shield or will MQTT Arduino Ethernet shield work in GSM modem?

Nick O'leary published an MQTT client for Arduino.
I use it extensively.  You can find it here: http://knolleary.net/arduino-client-for-mqtt/.
Once you have established a tcpip connection you can use this library to send/receive via the MQTT protocol across a GPRS/GSM modem.  I have used it successfully on:

the Arduino GSM shield
the Seeeduino GPRS IoT panel
a Freetronics Arduino Mega connecting via ethernet to a TPLink MR3020 router


How safe is it to use my body as part of a circuit? I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.

I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.

This is actually great for my project!... unless it's not safe. So I'm looking for two things:

A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.
A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.

There is quite a bit of related information at How much voltage is “dangerous”?. That link seems to have enough information that there isn't a lot of point of repeating it all here.

There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is 12V (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.

I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.

That page mentions that 60V is getting into the range where you might get a shock.

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.

I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.

I = V / R
I = 5 / 1500000 = 0.000003 A


Arduino nano getting powered through analog input? I noticed something today. I am powering the Arduino Nano from a battery and a 5v step up converter. That works just fine and I'm getting a stable 5v output. I have a second cable coming out from the battery which plugs right into analog input A0 set as input so I can measure the battery voltage. However when I disconnect the battery from the usb plug and leave the voltage sensing cable connected to the analog input the power led stays on. I want it to shut down and be disconnected from the power source and have the voltage sensing cable still connected.
How can I fix this?

Power is flowing from the analog pin, through the internal clamping diodes, to the Vcc line. Those diodes are however not designed to handle that much current, so don't continue doing this.

Either also disconnect the ground wire from the battery, or simply add a resistor between the battery and the analog pin. Something like 10k. That way less than a mA of current will be clamped, and the arduino will stay off.


How can I switch a 1.5V buzzer with my Arduino? I want to make my alarm clock “smart”. I'm very new to this stuff, that is, the hardware side. The programming shouldn't present too many problems.

I’m currently experimenting with a simulator (http://circuits.io) and want to start with controlling the alarm’s buzzer with my Arduino.

I did some reading on transistors and this is what I came up with:

I’ve turned pin D3 to high and hooked it up to the base of a NPN transistor. I’m trying to run 1.5V through the transistor, but nothing happens. Any thoughts?

You simply need to ground the circuit. In row E on your breadboard just under where you connect the - of the battery, connect that to the ground pin on the UNO. This causes the buzzer to start working.


How to deep sleep ATtiny/ATmega (to run for years with batteries) but still detect a button press? Question (TL;DR): what is the optimal method to deep sleep (to run an ATtiny45 or ATmega on batteries for 1+ year) but still be able to detect a button press? Is it possible to deep sleep until a button is pressed?

I'm using a classic "debounce" method to detect a button press:

int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;

void setup() {
  pinMode(2, INPUT);
}

void loop() {
  int reading = digitalRead(2);
  if (reading != lastButtonState) { lastDebounceTime = millis(); }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == HIGH) {
         // Button pressed, do something here!
         // In my actual code, it sends a packet via RF 433 Mhz
      }
    }
  }
  lastButtonState = reading;
  // snore(20);          // TinySnore here
}

My ATtiny45 should run during 1 year on 3 AA batteries, so I added a deep sleep using TinySnore. It works, and made the consumption go from more than 1mA to 0.2mA (@1 Mhz).

I know it's possible to go down to 5 µA if I snore(1000); but then obviously it won't be able to detect a button press.

I tried various sleep values: snore(10);, snore(20);, snore(50);, etc. but I didn't get consistent results.

Thus the question: how to deep sleep until a button is pressed?

I was thinking about using attachInterrupt() but then what kind of sleep should we use? snore()? delay()?

ATTINY's are designed to easily do this since they can wake from power down sleep mode by a pin change...

Basically you want to...

Connect a normally-open push button between an IO pin and ground.
Enable the pull-up on the IO.
Enable the pin change interrupt on the IO pin.
Enable interrupts.
Enter "power down" sleep mode.

When the button is pushed, it will connect the IO pin to ground, which will cause a pin change interrupt, which will wake the chip from sleep.

Note that you do not need to do anything in the pin change ISR (you can use the EMPTY_INTERRUPT compiler macro). If the ISR is empty, execution will pick up on the line after the sleep upon waking.

While in deep sleep, the chip will use an astonishingly small amount of power.  For example, an ATTINY25/45/85 running off of a 3V coin cell at room temp will use less than 0.2uA...

A typical CR2032 coin cell is rated for 235mAh to 2V, so at this rate we'd expect to be able to wait for a button press like this for 100+ years.

IRL the battery will likely self discharge and physically deteriorate long before then (rated at 1% per year), but still not too shabby.


cast double to long leads to unexpected results I wrote a little program to show my problem:

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

  double K=39.85;
  double a=K*100;
  Serial.print("a= ");
  Serial.println(a);

  long val_long = 0;
  val_long = a;
  Serial.print("val_long= ");
  Serial.println(val_long);
}

void loop() {
}

I get this back from my Arduino uno:

a= 3985.00
val_long=3984

I've been pondering for a long time and can't find the mistake! Why is the long value decremented by one? Can anybody help me please?

The problem is that float numbers are seldom an exact representation. So the float is stored as the closest number that is exactly representable as a float, namely
10446438 × 2−18 = 39.84999847412109375.

When you multiply this by 100, you get 16322559 × 2−12 = 3984.999755859375.

And than casting to an int or long results in 3984, not 3985.

so whenever you cast a value from a float or double to an int or long, you always should add 0.5 (so all values from [x - 0.5, x + 0.5) are rounded to x assuming x >= 0, thus:

val_long = int(a + 0.5);

Beware of negative values, see therefore https://www.cs.cmu.edu/~rbd/papers/cmj-float-to-int.html

Better is to use the round function, see comment of Edgar Bonet below.

UPDATE

See comment of Lightness Races with Monica

In case it's not wanted to round up, but you still want 39.84999847412109375 to be 39.85, than you have to add a value that has the value of the least significant bit (actually slightly less but that is impossible to define). In most cases, it's best to add half the significance you want. So if you need two decimal accuracy, add 0.005.


Can't make ultrasonic sensor work with motor controller I just started using Arduino Uno, I can't get the ultrasonic to work ,with motor controller board, the output value is always zero.

Just to make sure I'm talking about the correct stuff:
I used this guide to try to make it work (look at the picture how did I connect the parts).

And this is my code:

#define trigPin A4//Attach Trig to port 8
#define echoPin A5//Attach Echo to port 7
#include <AFMotor.h>
//SMARS Demo 2 with Line sensor

AF_DCMotor R_motor(2); // defines Right motor pin
AF_DCMotor L_motor(1); // defines Left motor pin

int lmotorpin1 = 3;
int lmotorpin2 = 5;
int rmotorpin1 = 6;
int rmotorpin2 = 9;
int distancecm = 0;
//const int trigPin = 18;
//const int echoPin = 19;

// defines variables
long duration;
int distance;
void setup() {

  Serial.begin(9600); // sets up Serial library at 9600 bps

  //changes the following values to make the robot drive as straight as possible
  L_motor.setSpeed(200); // sets L motor speed
  R_motor.setSpeed(140); // sets R motor speed

  R_motor.run(RELEASE); //turns L motor on
  L_motor.run(RELEASE); //turns R motor on

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
      Serial.println(trigPin);
    Serial.println(echoPin);
  distancecm = mdistance();
  if (distance < 5) {
    L_motor.run(BACKWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
//    L_motor.run(FORWARD); //moves motor L Forward
//    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
  }
  else {
    L_motor.run(FORWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
  }
}

int mdistance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  Serial.print("Duration: ");
  Serial.println(duration);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

As you can see I tried different pin numbers but it always 0 ....

what do you think can be wrong?

The motors work.
Motor Controller: KEYES L293D Motor Control Shield
Sensor: Ultrasonic Ranger V2.0

Pin numbers 0 and 1 are reserved for the Serial monitor which you're using on the board.
The function int mdistance() should return an integer.
You also didn't seem to set the motor pins as OUTPUT.


Can Arduino be used as an FDTI Programmer? I would like to program my ESP 8266 WiFi module. But I don't have an FDTI right now is there any way to use Arduino Uno as FDTI Programmer then use ESP without it.

Yes. Tie the reset pin on the ISP connector low to keep the ATmega328P in reset, then you can connect pins 0 and 1 to the ESP module to communicate using the Uno's USB-UART bridge. Since the pins are labelled from the perspective of the '328P, connect TX to TX and RX to RX.


How to implement the Arduino Extended Database library in a custom class? I am struggling to implement a custom class that uses the Arduino Extended Database Library (EDB.h). The purpose of my custom class is to manage my application's internal database.

While searching for a solution I found this, which seems very relevant: the code and goal are the same as mine.

But my problem with that Q&A is that I am not able to implement the given solution as I don't fully understand the way it should be written.

For the sake of trying to give the best support for explanation, I upladed the code below. Feel free to explain me how to modify it.

Thank you.

EDIT: Following duplicate comments, I'll try to be more precise in my question.

It is difficult to answer this question because I'm not sure what you have managed to achieve.  Sorry if some of it seems a bit basic.

Look at Majenko's answer to the question.  If you want to use this EDB class then you need to define two functions:

  void configWriter( unsigned long address, byte data );
  byte configReader( unsigned long address );

You need to be able to access the single instance of these functions from anywhere in the code, so the need to have global scope.  When they are global you can assign them to pointers by using the function name and no brackets/parenthesis.  i.e.

aPtr = configWriter;

So the call to create the EDB instance would be:

 configDB = new EDB( configWriter, configReader );

Now you could create the EDB instance using a class member function.  To do this you have to make the function a static member, which means it has no access to the class's data. (in its simplest terms static means there is only one of the things it is referring to) i.e.

class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

Essentially its the same thing, but the code is compartmentalised better and you end up with neater code.

However, if you are only ever going to have one instance of the myEDB class then you can have a static member variable that hold the value of this.  You set this value in the class constructor.

class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
    myEDB() {pInstance = this;}
  private:
    static myEDB* pInstance = nullptr;
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

When configReader or configWriter is called it checks to see if the member pInstance has a non null value, if it doesn't then it creates a new instance.  The then use this pInstance to access the functions and variables for the instance of the class.  (This is the design pattern for a single instance class or singleton).

SO what should YOU do?

Start simply, define two global functions that do what you need as per the top of this answer.  If you get stuck, if you need more info feel free to ask or comment.


Change range of IR programatically I am building a IR-based laser tag system. The basics are working fine. One feature, that I want to have, is different weapon modes with different ranges.

How can I change the range of an IR transmitter with as little hardware as possible, or at best, completely in software?

Consider using a Sharp Distance Sensor in addition to your shoot / confirm-hit inferred LED & receiver.

This Sharp distance sensor is specified to detect objects that reflect IR light from 100 cm-500 cm.

  How can I change the range of an IR transmitter with as little
  hardware as possible, or at best, completely in software?

I believe the sensors produce an analog output that can feed into an Arduino's ADC.  So software (by itself) can be used to adjust the threshold distance.

Similar devices I have used have a narrow sensing field.  They only reported the distance to objects directly in front of them.  Also, I found they were effected by defective (burning out?) florescent light sources.  We assumed failing florescent light sources produced IR radiation similar in frequency as used by the sensor's IR emitter.  Also, the analog output is slightly stair stepped in the unit we tested.  I say this in case you were expecting to use increase relative accuracy of several readings if not precision of any given reading.