LEDs not working with tone() function I have a strange issue. I have 3 LEDs, each is supposed to beep with a correlated tone... Imagine the beginning of a racing game (beeping with traffic lights). Here's my code:

#include "pitches.h"

//Beginning Melody
int melody[] = {
  NOTE_C3, NOTE_C3, NOTE_C4
};

//Beginning Note Durations
int noteDurations[] = {
  2, 2, 1
};

int redLight = 3;
int yellowLight = 5;
int greenLight = 6;

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

  pinMode(redLight, OUTPUT);
  pinMode(yellowLight, OUTPUT);
  pinMode(greenLight, OUTPUT);
}

void loop() {
  playBegin();
  delay(5000);
}

void playBegin(){
  int lightColor = 1;

  for (int thisNote = 0; thisNote < 3; thisNote++) {

    if(lightColor == 1){
      analogWrite(redLight, HIGH);
    }else if (lightColor == 2){
      analogWrite(yellowLight, HIGH);
    }else{
      analogWrite(greenLight, HIGH);
    }
    lightColor++;

    int noteDuration = 1000 / noteDurations[thisNote];
    tone(11, melody[thisNote], noteDuration);
    delay(1000);
    noTone(11);

    analogWrite(redLight, LOW);
    analogWrite(yellowLight, LOW);
    analogWrite(greenLight, LOW);
  }
}

Originally, the 3 LEDs would light up correctly. The red light is plugged into Pin 3, the yellow light into Pin 5, and the green light into Pin 6. HOWEVER, when I added in the tones, the red light (in Pin 3) doesn't light up. The 3 tones still sound off correctly, and the yellow and green LEDs work perfectly fine. This is ONLY not working for the red LED, it just doesn't light up while the 1st tone happens.

When I take out the line of code where tone() is, it works fine and the red light will turn on at the correct time again. This is ONLY happening when the tone() function is included.

To be clear, this is the exact line of code that is affecting the red LED:

tone(11, melody[thisNote], noteDuration);

Furthermore, I swapped the pins of the yellow and red LEDs to see if it was an issue with the red LED, and it was not. It's whatever LED is plugged into Pin 3, and again, ONLY when the tone() function is in the code as well. I'm not sure how they're conflicting. This does not appear to be an issue with my hardware.

I'm working with Arduino Uno. If you need anymore info, let me know.

Thanks!

You have a timer conflict.

tone() uses a timer, and analogWrite() on certain pins uses the same timer.

Quite why you're using analogWrite() though, with HIGH (which equates to 1) as the duty cycle I don't quite understand. I would have though digitalWrite() would be a better choice. A duty cycle of 1 would be pretty much invisible anyway...


How can measure the 3-axis accelerations? i'm a student who is studying the Arduino.
I want to measure acceleration using arduino and any sensor. i looked at some acceleration sensors (ex, MPU6050, AXDL335), but they were just measuring gravity, not axial acceleration.

Could you tell me any sensor that can measure the axis-acceleration available with Arduino?

There is no difference between gravity and other kinds acceleration. Gravity is the constant downward acceleration of ≈9.81 m/s². You cannot feel any difference between the force of gravity and the force you would experience on a surface without gravity that's accelerating upwards at 9.81 m/s².

You can use the gyroscope to keep track of the orientation of the sensor, so you know the downward direction of gravity, and can correct your accelerometer measurements for it.

The problem is that gyroscope orientation measurements are subject to drift. To correct the orientation for drift, the accelerometer is used (because it can measure the direction of gravity, so you know what the downward direction is). The accelerometer only measures the exact acceleration due to gravity if the sensor is not accelerating, of course, but that's most likely not the setup you're going to use an accelerometer in.

As you can see, this is kind of a chicken and egg problem.
Luckily, there are advanced sensor fusion algorithms and complementary filters available that combine the accelerometer and gyroscope measurements, and give you a pretty good approximation for both.
I've successfully used Madgwick's algorithm for a quadcopter.
Depending on your use case, you'll have to tweak some coefficients to indicate if you rely mostly on the gyro or the accelerometer data. The MPU6050 has a DMP that can run sensor fusion algorithms on the chip itself, so the Arduino doesn't have to deal with that.


Risks of ftdi_eeprom? - TX always high after flashing I flashed an Arduino Nano compatible with ftdi_eeprom and the following config:

vendor_id=0x0403    # Vendor ID
product_id=0x6001   # Product ID

max_power=0     # Max. power consumption: value * 2 mA. Use 0 if self_powered = true.

###########
# Strings #
###########
manufacturer="FTDI"     # Manufacturer
product="Arduino Nano"  # Product
serial="arduino_1"      # Serial

###########
# Options #
###########
self_powered=false  # Turn this off for bus powered
remote_wakeup=false # Turn this on for remote wakeup feature
use_serial=true     # Use the serial number string

# Normally out don't have to change one of these flags
BM_type_chip=true       # Newer chips are all BM type
in_is_isochronous=false     # In Endpoint is Isochronous
out_is_isochronous=false    # Out Endpoint is Isochronous
suspend_pull_downs=false    # Enable suspend pull downs for lower power
change_usb_version=false    # Change USB Version
usb_version=0x0200      # Only used when change_usb_version is enabled

########
# Misc #
########

filename="eeprom.new"   # Filename, leave empty to skip file writing

My corresponfing udev rules work and I get /dev/arduino_1 after connecting.

However. After the flash, everything seems to work, But: The TX-LED is constantly on. Even, when the device is not sending. Why?

Update & solution

First, I removed this line, because it threw warning messages (outdated)

# BM_type_chip=true         # Newer chips are all BM type

Then I studied the schematics of the Nano and figured out, that RX and TX  LEDs are indeed connected to CBUS0 and CBUS1. So, I added two lines to my config

  cbus0=RXLED
  cbus1=TXLED

Which had the effect, that now both RX and TX where constantly on. So, I finally read the manual which says on page 11, that the commands in question need a trailing #. I updated my config again:

cbus0=RXLED#
cbus1=TXLED#

Extra:

Indeed, I had to install ftdi_eeprom to get the job done

 apt-get remove ftdi-eeprom
 apt-get install swig libusb-1.0-0-dev libconfuse-dev doxygen
 git clone https://github.com/legege/libftdi.git
 cd libftdi.git
 cmake .
 make
 make install
 ftdi_eeprom/ftdi_eeprom --flash-eeprom myconfig.conf

The ftdi_eeprom utility re-writes the entire EEPROM, not just the selected bits you have chosen.  That includes the "CBUS" pin configurations.

You need to check on the Nano's schematic which LED is connected to which CBUSx pin on the FTDI and set it accordingly.  You do that in your config using:

cbus0=TXLED
cbus1=RXLED

for example.

Possible settings for the CBUS pins are:

TXDEN
PWREN
RXLED
TXLED
TXRXLED
SLEEP
CLK48
CLK24
CLK12
CLK6
IO_MODE
BITBANG_WR
BITBANG_RD
SPECIAL

Except CBUS4 which only has the functions:

TXDEN
PWRON
RXLED
TXLED
TX_RX_LED
SLEEP
CLK48
CLK24
CLK12
CLK6

There is a chance that your pre-packages version of ftdi_eeprom doesn't support those settings, so you will need to download and compile the latest version from source from here: https://github.com/legege/libftdi

Also during testing I accidentally changed the VID of one of my boards thus rendering it unresponsive.  I did that by omitting the 0x from the VID and PID numbers.  Extreme care should be exercised using thin utility.  I have submitted a patch to allow the specification of a default VID for recovery from such situations.


Pass Several Values to Library Unfortunately I have yet to learn C++ though I have experience with C# and other non-C languages. After trying for the past 5 hours to pick up what I can from Stack and other sites I haven't found a workable solution that actually works with Arduino IDE (hence why I'm posting here and not stackoverflow).

Im trying to create a simple library to handle some analog inputs. I need to be able to compare the value from a pin to a list of values and handle the result accordingly. I can easily send the number of the pin to the constructor and read it. My issue is actually defining that list from the setup() function.

The list can be variable in length so I can't hard code an array in the library class and then pass values one by one. I can pass the length in the constructor but then I'm not really sure how to use it to initialize the array length without having the values to assign.

In C# or other languages I'd either use a list or pass the array directly. Neither of these seem to be an option with C++ (or at least I couldn't pass the array correctly). How could I solve this problem? If it helps I'm using a teensy++ 2.0.

If the list is a static list you could conceivably pass a pointer to it in the constructor. Example:

class myClass {
  const int num_;
  const int * values_;

  public:

  // constructor
  myClass (const int num, const int * values) : num_ (num), values_ (values) { }

  // other stuff here

  // demo
  void printThem ();
};  // end of class myClass

void myClass::printThem ()
  {
  for (int i = 0; i < num_; i++)
    Serial.println (values_ [i]);
  } // end of myClass::printThem

const int NUMBER_OF_VALUES = 6;
const int myValues [NUMBER_OF_VALUES] = { 22, 33, 44, 55, 66, 77 };

// make an instance of the class with the wanted values
myClass foo (NUMBER_OF_VALUES, myValues);

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  foo.printThem ();
  }  // end of setup

void loop ()
  {

  }  // end of loop

That is the simple method. The values in the list are passed to the constructor as a pointer, the class remembers the list and uses it when necessary.


How I can connect module GSM SIM800L? I bought a GSM module, and I want to connect it with Arduino but I have a problem.

I linked GSM SIM800L with regular LM2596 12 V 2 VA I changed tension to 5 V, So far the GSM is working but if I connect TX_ARDUINO with RX_GSM the module enters in the loop of the restart.

The picture explains the montage.

Follow this tutorial on how to connect your Sim800l with Arduino.


Arduino to mysql database? I found a lot of methods on the internet and I was wondering what would be the best method to send data from sensors connected to Arduino to a MySQL database in a WAMP server continuously.

There is no absolute "best" way, there is only the way that "works best for your situation".

In a nutshell, the different methods that I can think of, and their pros and cons, are:

Simple HTTP GET with parameters

Quick to implement, light weight, but not very secure or robust. Perfectly fine for things like "send the temperature once a minute" etc, but crafting very long GET requests with lots of parameters can severely impact on both your RAM and your sanity.

HTTP POST request

Like the GET request it's fairly simple to implement, but needs more RAM since you need to know the size of the data you're sending first so you can send a Content-length header.  You can send much more that way though, assuming you have the resources for it.

SOAP

This is basically HTTP POST but with a specially XML formatted body.  It has the advantage that it's a standard protocol for transferring data and commands around the place, so there are plenty of resources to help you.  The main problem is crafting the XML at the Arduino side.

Custom TCP

Connect to a special port to communicate with your own software.  You define all of the protocol, but you have to write all (or most) of the software too.  This can be more like a serial connection to your computer but through the network.  Good for sending larger amounts of data, such as images from a camera, etc.

Custom UDP

If you want to send lots of small values very frequently this is probably the best bet.  Harder to implement than most of the others, but the light-weight nature of UDP means you can send data much more rapidly.  Of course, with UDP, you run the risk of losing packets since it's very much a "fire and forget" protocol - you send a packet and hope it gets there.  Fine if you don't mind missing the odd bit of data, say for higher speed temperature logging.  Of course, you have to write the server side software yourself, but there's plenty of resources to help you with that online.

So it's really not a case of "best" but "most suitable".  Define what the data is and how often you want to send it, then think about how complex you are willing to get with your programming.

Nine times out of ten a simple HTTP GET request fits the bill.


How to replace String objects with char arrays while still using string methods I am running the following code on my ESP8266 (AI-Thinker ESP8266MOD).

I send an HTTP GET request and a pin is set to high for a 1/2 second.

However, after some time (sometimes 1hr, 2hrs, 12hrs, totally random), it stops responding to HTTP requests.
I think it might be because of heap fragmentation due to the String objects I'm using.

Questions:

How can I replace the request (in loop()) and s and text (in GenerateResponse()) objects with  char arrays?
After I replace the String objects with char arrays, how can I use the indexOf() method and + operator on the char arrays?

Will this approach help with heap fragmentation?

Is it possible to find out if heap fragmentation is the problem?

#include <ESP8266WiFi.h>

const char* ssid = "myWifi";
const char* wifiPassword = "y76ggS";
const char* passwordToOpenDoor = "/81"; //password should begin with a slash

const int doorPin = 5;

WiFiServer server(301); //Pick any port number you like
WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.println(WiFi.localIP());

  pinMode(doorPin, OUTPUT);
  digitalWrite(doorPin, 0);

  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, wifiPassword);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  server.begin();
  Serial.println("Server started. Diagnostics info:");
  Serial.println(WiFi.localIP());
}

void loop() {
  client = server.available();
  if (!client) {
    return;
  }

  while(!client.available()){
    delay(1);
  }

  String request = client.readStringUntil('\r');
  client.flush();

  Serial.println(request);
  if (request.indexOf(passwordToOpenDoor) != -1) { //Is password correct?
    GenerateResponse("Password is correct");
    OpenDoor();
  }
  //Got a GET request and it wasn't the favicon.ico request, must have been a bad password:
  else if (request.indexOf("favicon.ico") == -1) {
    GenerateResponse("Password is incorrect.");
  }
}

void OpenDoor() {
  digitalWrite(doorPin, 1);
  delay(500);
  digitalWrite(doorPin, 0);
}

void GenerateResponse(String text) {
  Serial.println(text);
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Content-Type: text/html\r\n\r\n";
  s += "<!DOCTYPE HTML>\r\n\r\n";
  s += "

" + text + "
";
  s += "\n";
  client.flush();
  client.print(s);
  delay(1);
}

You already received good answer about some general ideas for
replacing String objects with C strings. Here I will try to add some
more tricks more specifically targeted to your actual situation.

I can see two places in your program where the use of String shines by
its convenience, and replacing it with C strings will require some
effort. The first is the use of Stream::readStringUntil(char) for
getting the first request line. Here
I see no better option (see edit below) than reading
the stream one character at a time, and putting those characters into an
array:

const size_t input_buffer_length = 256;

// Read a line of text up to the first '\r'.
// Returns a NUL-terminated string, without the final '\r',
// into a statically allocated buffer.
// Warning: this never times out.
const char *readline(Stream &input)
{
  static char buffer[input_buffer_length];
  size_t pos = 0;  // writing position within the buffer
  int c;           // current character
  while ((c = input.read()) != '\r') {
    if (c >= 0 && pos < sizeof buffer - 1) {
      buffer[pos++] = c;
    }
  }
  buffer[pos] = '\0';  // terminate the string
  return buffer;
}

You would use it like this:

const char *request = readline(client);

For more robustness, you may want to add a timeout. Note also that this
implementation is no reentrant, as it uses a static buffer. This is not
an issue for your use case.

Edit: As noted by hcheung in a comment, you do not need to implement
this readline() function, as you can use
Stream::readBytesUntil(), which handles the timeout
and is provided by the Arduino core:

char buffer[input_buffer_length];
client.readBytesUntil('\r', buffer, input_buffer_length);

The other place is the usage of String::operator+=(const char *) for
generating the response. Here I would advice you against using
strcat() or strncat(): these will require extra memory to store the
concatenated string which you probably do not need. Instead, you can
simply print() the pieces one by one:

void GenerateResponse(const char *text) {
  Serial.println(text);
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("<!DOCTYPE HTML>");
  client.println("");
  client.print("

");
  client.print(text);
  client.println("
");
  client.flush();
  delay(1);
}

Alternatively, you can make use of the implicit concatenation of string
literals in order to reduce the number of calls to client.print():

void GenerateResponse(const char *text) {
  Serial.println(text);
  client.print(
      "HTTP/1.1 200 OK\r\n"
      "Content-Type: text/html\r\n"
      "\r\n"
      "<!DOCTYPE HTML>\r\n"
      "\r\n"
      "

"
  );
  client.print(text);
  client.print("
\r\n");
  client.flush();
  delay(1);
}


Atmel studio 7 - my own libraries I like to use AS7 to make my programs.
I know c and some c++, but how things work from there I'm green.
I would like to know if there is a folder where I can store my own homemade c and h library files where they get to be available for all my projects.
Now I copy all the files into each of my projects and this works but I find it a bit tedious.

You should create your library as a separate project: File->New->Project and select C or C++ static library:

Add your library modules in this project. When building, this will create lib{your_project_name}.a file (in Debug or Release folder) - your library object file you can use in your other projects.

Usually I include in the same solution both the library project and target project (just library project file, sure the library and it's files resides in single place):

ORDO is the library name.

Some check list:

Include the library file in Libraries folder (shown above)
Specify the path to the library *.a file for linker (Toolchain->AVR/GNU Linker->Libraries). Note that there should be different paths for Debug and Release configurations.
Specify the path for library include files (Toolchain->AVR/GNU C or C++ Compiler->Directories)
In some cases, F_CPU definition might be needed for library project too (same as in your project, under Symbols).
When changes are made in your library files, use Build solution (F7) when building, if not - you can use Build project (which will be faster).

Setting project dependencies shall also lead to rebuilding the library automatically when needed (not tested, I usually just hit F7 :).


IR controlled light dimmer I am doing a project on Arduino controlled light dimmer circuit...

I have a separate circuit for zero crossing detector and IR receiver but when I am combining both of them in arduino then my IR receiver stops working and zero crossing interrupt is not detected...

Here is my code:

#include <IRremote.h>
int RECEIVE_PIN = 8;
int AC_LOAD = 3;
int dimming;

IRrecv irrecv(RECEIVE_PIN);
decode_results results;

void setup()
{
    Serial.begin(9600);
    irrecv.enableIRIn();
    pinMode(AC_LOAD, OUTPUT);
    attachInterrupt(0, zero_crosss_int, RISING);
}

void zero_crosss_int()
{
    int dimtime = 75*dimming;
    delayMicroseconds(dimtime);    // Off cycle
    digitalWrite(AC_LOAD, HIGH);   // triac firing
    delayMicroseconds(10);         // triac On propogation delay
    digitalWrite(AC_LOAD, LOW);    // triac Off
}

void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.print("0x");
        Serial.println(
        results.value, HEX);
        delay(50);

        if(results.value==0xE13DDA28)
            dimming = 120;

        if(results.value==0xAD586662)
            dimming = 80;

        if(results.value==0x273009C4)
            dimming = 20;

        irrecv.resume();
    }
}

Can anyone help me with this????

What you've described (without source code and/or a circuit diagram) sounds like you'll probably be using interrupts at least for the zero crossing detection. And probably the IR receiver too. The IR receiver is going to be your problem since the zero crossing is a very quick flag set and you're out of the interrupt.

On the other hand, the IR detection is going to take time, and if you're doing THAT in an interrupt you're going to be missing dozens of crossings.

To mix the two you can leave the zero crossing in it's own interrupt, but you're probably better off handling the IR in the loop via a state machine.

Since you say that neither are working, I'm going to hazard a guess and you're using the same interrupt or badly implemented them (possibly a timer and interrupt clash) and until you post some code people here aren't going to be able to help you any more than that.


Why Wire.write twice? I'm checking an example for the MPU6050 and got to this part

Wire.beginTransmission(0x68);           //begin, Send the slave adress (in this case 68)
Wire.write(0x1B);                       //We want to write to the GYRO_CONFIG register (1B hex)
Wire.write(0x10);                       //Set the register bits as 00010000 (1000dps full scale)
Wire.endTransmission(true);             //End the transmission with the gyro

Serial.begin(9600);                     //Remember to set this same baud rate to the serial monitor
time = millis();                        //Start counting time in milliseconds

/*Here we calculate the gyro data error before we start the loop
 * I make the mean of 200 values, that should be enough*/
if(gyro_error==0)
{
  for(int i=0; i<200; i++)
  {
    Wire.beginTransmission(0x68);            //begin, Send the slave adress (in this case 68)
    Wire.write(0x43);                        //First adress of the Gyro data
    Wire.endTransmission(false);
    Wire.requestFrom(0x68,4,true);           //We ask for just 4 registers

Why is there two consecutive wire.write() in the begining and only one later? Is it different somehow?

The truth is, the Arduino Wire library sends the data only if endTransmission is called. Until then it collects the data in TX buffer. The version of the write function used in your snippet adds a byte to the TX buffer.

With I2C usually the first byte written is the address of the register to write. Then the data follow. In case of the first part in your snippet the data are only one byte long.

In the second part, first the register address is sent with write and then the data from this register and 3 following registers are requested.


Setting timer3 in CTC mode - conflict with servo library I would like to set up a timer in order to call a function 800 times per second. I'm using the Arduino Mega and Timer3 with a prescaler of 1024. To choose the prescaler factor I've considered the following steps:

CPU freq: 16MHz
Timer resolution: 65536 (16 bits)
Divide CPU freq by the chosen prescaler:
16x10^6/1024=15625
Divide the rest through the desired freq
62500/800=19.
Put the result + 1 in OCR3 register.

I've used the following table to set registers of TCCR3B:

The error

It is impossible to compile the code. This is the error returned by the compiler:

  Servo\Servo.cpp.o: In function '__vector_32': C:\Program Files
  (x86)\Arduino\libraries\Servo/Servo.cpp:110: multiple definition of
  '__vector_32' AccelPart1_35.cpp.o:C:\Program Files
  (x86)\Arduino/AccelPart1_35.ino:457: first defined here c:/program
  files
  (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
  Disabling relaxation: it will not work with multiple definitions

The code

volatile int cont = 0;
unsigned long aCont = 0;
void setup()
{
 [...]
  // initialize Timer3
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3A);
  // enable global interrupts:
  sei();
}

void loop()
{
 // Print every second the number of ISR invoked -> should be 100
 if ( millis() % 1000 == 0)
 {
   Serial.println();
   Serial.print(" tick: ");
   Serial.println(contatore);
   contatore = 0;
 }
}

[...]

// This is the 457-th line
ISR(TIMER3_COMPA_vect)
{
    accRoutine();
    contatore++;
}

void accRoutine()
{
  // reads analog values
}

How to solve the conflict with the servo library?

SOLUTION

Conflict solved using the following code. It compiles but the counter associated with the 800Hz timer doesn't increment its value.

volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

Since the main problem has been solved, I've created another question here related to the problem of the counter incrementation.

Unfortunately, The Servo library reserves output compare A (OCR*A) on timers 1,3,4, and 5 when loaded on an arduino mega. Each can only have one ISR, so you will not be able to define your own TIMER*_COMPA_vect while you use Servo without modifying the library.

However, each hardware timer is equipped with 2 output compare registers. Servo does not claim any TIMER*_COMPB_vect interrupts, so those are free to use, and work exactly the same.

You should watch out for the Servo libraries activities, it could change the configuration of your timer. The default order is on megas is 5,1,3,4 and to give each 12 servos. It only configures the timer once it needs it, so you should be fine using timer 3 until you add that 25th servo.

To change your code, use OCR3B instead of OCR3A (the Output Compare Registers) and set bit OCIE3B instead of OCIE3A in TIMSK3 (the Output Compare Interrupt Enable bits). Then you to change your ISR function to  ISR(TIMER3_COMPB_vect){}

CTC mode only works with OCR3A, but if you set TCNT3 to 0 in your interrupt function you can get similar behavior. Remember to remove the line that turns CTC mode on using WGM12.


How can I load fonts into Adafruit GFX for TFT display (ILI9341) I get a compile error when I try to set a different font in Adafruit GFX on a TFT display on my Arduino Uno.

I'm testing a new TFT shield for Arduino equipped with an ILI9341 by using the Adafuit GFX libraries and examples. The test program supplied with the library works fine out of the box displaying text and all kind of drawings on the screen.

However, the standard font built into the Adafruit GFX library is "blocky" to save memory space. They do provide other fonts, but I get an error when I try to invoke them.

The segment of code that throws the compile error is this one:

unsigned long testText1() {
  tft.setFont();    // When I remove this line the sketch compiles OK
  tft.fillScreen(BLACK);
  tft.setCursor(0, 50);
  tft.setTextColor(RED);
  tft.setTextSize(13);
  tft.println("1234");
}

When compiling I get this error:

  "error: ‘class Adafruit_ILI9341_8bit_AS’ has no member named ‘setFont’"

According to Adafruit's GFX manual, the setFont() procedure allows to define a new font or revert to the standard one.

I examined the libraries and nowhere could I find a procedure to select a font, yet the example has declarations like these below, so changing fonts should be possible:

#include <Adafruit_GFX_AS.h>
#include <Adafruit_ILI9341_8bit_AS.h>
#include <Font16.h>
// #include <Font32.h>
// #include <Font64.h>
// #include <Font72.h>
#include <Font7s.h>
#include <Load_fonts.h>

I would like to load the 7segment font with:

tft.setFont(&Font7s);

Does anybody have experience to share loading these fonts?

Looking further into documentation on the Adafruit website they indicate that indeed, their GFX library published on GitHub does not handle different fornts.

Case closed :-)


MOSFET to dim LED backlight I have built the following to dim the brightness of the LED backlight of a display:

I am using a BS170 MOSFET (the diode is no extra part but included in the MOSFET, according to the datasheet). The BL pin is the supply of the LED backlight. (I have left out all other pins.)

Unfortunately, it does not work. Even if I set the PWM pin to 255, the backlight does not light (actually it's completely off). If I short BL and Vcc, it lights up as it should.

Also, the voltage readings confuse me: I measure 3.3 V on the gate and drain against ground, 1.5 V on source against ground (= the voltage across the backlight) but only 1 V if I measure drain against source.

So my questions are:

Shouldn't this add up to 3.3 V?
More importantly, why do I get only 1.5 V at BL?
Most importantly, what do I need to change? Different MOSFET? No MOSFET?

The primary aim of controlling the backlight is to be able to switch in off completely, thus reducing power consumption. (Being able to dim it is only a plus.)

EDIT

I should have added details about the display. It's one of those:

I haven't found a datasheet / specs for exactly this model. Most datasheets I found refer to a different version that is not 5 V compatible. A very similar model is described here.

Concerning my question I haven't found information on how much current the backlight would draw. Therefore I didn't want to drive it directly from the PWM pin. (Actually I could just measure it...)

Summary:
It looks as though you can just drive BL directly with the PWM-output.
What happens when you do?

Details:

(1)  As shown, even  if the circuit did what you wanted, all you would be doing is providing a rail to rail (0V to 3.3V ) signal to the BL pin. You can do this by connecting PWM-out to BL directly.
Does this work?

If the LCD and Arduino used differing power supplies the MOSFET may be useful.

(2) To use circuit almost as-is you need a PChannel FET.
Swap Drain and Source and it will provide PWM to the BL pin. When BL is high the FET is off. When BL is low the FET is on. The FET used must turn on with about 3V between gate and source.

(3) To use the N Channel BS170 you must drive the gate +ve above the source by an amount that is enough to just turn it one "plus a little more". This is called Vth (Vthreshold). The BS170 has Vth ~= 1.8V at low currents. Vth varies somewhat between samples. When you connect the gate to +3.3V the FET tried to turn on but as the source rises it reduced Vgs until it reaches about Vth. Raising the source above this level reduced Vgs to below Vth so the FET is not turned on.
ie this is what a=accounts for the 1.5V that you see as 3.3V - 1.8V = 1.5V.

To use the BS170,
connect the source to ground,
connect drain via a say 1k resistor to +3.3V,
connect drain to BL,
drive gate with PWM.

BUT why does not just driving BL with PWM do what you want?
A data sheet for the display would be useful.


Count RISING edges of a wave form by using ARDUINO I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V.
So I have in output a square wave (5V - 0V).
I would like to count how many times I press the button, by using an Arduino MEGA AT2560.
I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times.
For example: I press the button 5 times, but the counter has arrived to 30!

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

unsigned int count_hall_f = 0;

void setup()
{
  Serial.begin(9600);
  attachInterrupt(0, interrFront, RISING); //18
}

void loop(){

}

void interrFront() {
  count_hall_f++;
  Serial.println(count_hall_f);
}

An example of the result is:

1 <- I pressed here
2
3 <- I pressed here
4
5
6
7
8
9
10
11
12 <- I pressed here
13
14
15
16

I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a page about switches - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.

Example schematic:

Results on input pin:

(Maths supporting that figure on the above page).

Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.


How to remote control Arduino using an old 2.4Ghz toy remote controller? I have been wondering how to remote control my arduino robot using an old 2.4ghz car toy transmitter which has 4 buttons, up down left and right.
I have the nRF24L01(+) 2.4GHz transceiver to use it as a receiver.

Is there anyway to detect the signals going out from the remote controller and use them to make my arduino works,
I am a newbie so i am sorry if any mistake.

Thanks guys!

You have two options:

Use an nRF24L01+ on the Arduino and dismantle the controller to rip out the innards, replacing them with another Arduino and another nRF24L01+.
Do not use the nRF24L01+, instead, rip apart the car and salvage the receiver from it, then work out how you can wire that to the Arduino.

The car's controller will not talk to the nRF24L01+. Yes, they may be in the same frequency band, but they do not talk the same language. After all, your WiFi is on the same band and that doesn't talk to the car, and your microwave, which is also 2.4GHz, doesn't sit and watch satellite TV all day. As you can see the 2.4GHz band is used by a huge number of devices (the band is actually getting quite crowded) and everything talked to everything else in the same band it would be utter chaos.


Floating power supply for Arduino - Is it still connected to the USB ground? I am trying to power my Arduino Mega 2560 from a benchtop power supply. I plan to essentially feed in a 9V supply directly on the Vin pin and connect the GND pin to the floating ground pin on the power supply. I noticed on the schematic that the UGND is connected to GND through this jumper. On the Arduino that I have these two pins are tied together. Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

What is the best way to float the Arduino? Would it be ok to remove the jumper connection between UGND and GND? Or should I try something like a linear USB isolator like this?

Does this mean that even with the external power supply the Arduino will be connected to the UGND, and in effect the protective earth?

Yes.

  Would it be ok to remove the jumper connection between UGND and GND?

No. I don't know quite why they provided that jumper. I can see no scenario in the datasheet where it suggests the two can be separate.

  Or should I try something like a linear USB isolator like this?

If you want it to float then you need galvanic isolation on all USB pins. The device you link to will do that for you. There are others as well.

Personally in these situations I prefer to use a wireless communication system so there is no worry about grounds and isolation - it's naturally isolated.


Slowly increase speed using PWM arduino I'm trying to control the speed of a DC motor using PWM. Here is my code so far:

int motor = 9;
int fadeValue = 5;

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

void loop() {
  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
  if (fadeValue==245) {
    fadeValue=255;
    break;
  }
}

I want the motor to slowly increase it speed then stay high. However, the loop keep repeating.

Thanks in advance guys.

However, the loop keep repeating.

That's the whole point of loop(). If you want some code to run only once after the program starts put it in setup():

int motor = 9;
int fadeValue = 5;

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

  for (int fadeValue = 5 ; fadeValue <= 245; fadeValue += 10) {
    analogWrite(motor, fadeValue);
    delay(100);
    if (fadeValue == 245)
    {
      fadeValue = 255;
      break;
    }
  }
}

void loop() {
}


FastLED-driven strip acts weird when using PN532 A LED-strip (WS2812B, 46 pieces, PIN 8) and an Adafruit PN532 RFID shield (IRQ 2) are attached to my Arduino Mega 2560.
The GRB based strip seems to be working fine with FastLED in the beginning, I can confirm this by cycling through all three base colours in setup().
Once I call nfc.readPassiveTargetID(...) and use an NFC tag on it, things start to get weird. Whenever I comment out the line, it works properly again.
The colors RGB are randomly swapped (as if I had passed a different color ordering), brightnesses may change randomly as well, and sometimes a few LEDs in the beginning or end of the strip have different brightness/color as the rest.
As I have put the brightness down to 32, I'm sure it's not a power problem.
My assumption is that there is either some memory corruption, or some PIN interference with the two libraries, although I don't know why it would do it. Please find my code below, any help is appreciated.
  #include <FastLED.h>
  #include <Adafruit_PN532.h>

  #define LED_COUNT 46
  #define LED_DATA_PIN 8
  CRGB leds[LED_COUNT];

  #define PN532_IRQ (2)
  #define PN532_RESET (3) // Not connected

  Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

  void setLeds(CRGB color) {
    Serial.print("setLeds("); Serial.print(color.r, DEC ); Serial.print(","); Serial.print(color.g, DEC ); Serial.print(","); Serial.print(color.b, DEC ); Serial.println(")");
    for (int i = 0; i < LED_COUNT; i++) {
      leds[i] = color;
    }
    FastLED.show();
  }

  void ledStartSequence() {
    setLeds(CRGB::Black);
    for (int crtLed = 0; crtLed < 23; crtLed++) {
      leds[crtLed] = CRGB::Blue;
      leds[crtLed + 23] = CRGB::Blue;
      FastLED.show();
      delay(20);
    }
    Serial.println("Red");
    setLeds(CRGB::Red);
    delay(1000);
    Serial.println("Green");
    setLeds(CRGB::Green);
    delay(1000);
    Serial.println("Blue");
    setLeds(CRGB::Blue);
    delay(1000);

    Serial.println("Off");
    setLeds(CRGB::Black);
  }

  void initLeds() {
    FastLED.addLeds<WS2812B, LED_DATA_PIN, GRB>(leds, LED_COUNT);
    FastLED.setBrightness(32);
  }

  void initSerial() {
    Serial.begin(9600);
    Serial.println("Hello!");
  }

  void initNFC() {
    nfc.begin();
    uint32_t versiondata = nfc.getFirmwareVersion();
    Serial.print(versiondata);
    if (! versiondata) {
      Serial.print("Error: Didn't find PN53x board");
      while (1); // halt
    }
    // Got ok data, print it out!
    Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX);
    Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC);
    Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC);

    nfc.SAMConfig();
  }

  void setup() {
    initSerial();
    initLeds();
    initNFC();
    ledStartSequence();
  }

  void loop(void) {
    Serial.println("Waiting for an ISO14443A Card ...");
    setLeds(CRGB::Red); // only displayed correctly in the first iteration
    uint8_t success;
    uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
    uint8_t uidLength;

    success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
    /*
     *  Here's where things start to go nuts!
    */
    delay(1000);
    setLeds(CRGB::Green); // usually not displayed correctly
    delay(1000);
    setLeds(CRGB::Blue); // usually not displayed correctly
    delay(1000);
  }

After spending way too much time on the code, I figured that it had to do with something entirely different:
The RFID reader created an RF interference on the data wire towards the LED strip... Shielding it properly did the trick, no matter which pin is being used.
Thanks for the help anyway.


Running commands from string I have a string:

string s="digitalWrite(8,LOW);"

Is there any way to run it as a code?

This is actually pretty simple:

if (s == "digitalWrite(8,LOW);") {
    digitalWrite(8,LOW);
}

Obviously, it will not work is s contains any other string... If you
want something more general, that is able to interpret a wide range of
possible commands, you will have to define a language, and write an
interpreter for that language. From the example you give, it seems you
would like your language to look like C++. This is most likely a bad
design choice. If you want an interpreter that understands the whole C++
language: forget it. You will never fit something this big into an
Arduino Uno.

Here is, for inspiration, a very simple interpreter I
wrote that understand the following commands:

mode <pin> <mode>: pinMode()
read <pin>: digitalRead()
aread <pin>: analogRead()
write <pin> <value>: digitalWrite()
awrite <pin> <value>: analogWrite()
echo <value>: set echo off (0) or on (1)

You can use it a basis for writing your custom interpreter. Otherwise
you can do a Web search for “Arduino interpreter”: you should be able to
find interpreters implementing a wide variety of languages, including
compact binary languages (Firmata), Forth (another one),
Lisp, Basic, and even a C-like language.


Compiled sketch vs text file size OK,so this is my first program written via the Tinkercad utility. I have saved the program as a text file, and it equates to about 22K.

My simple question is, when uploaded / compiled to the actual board, is the size increased or decreased? I plan to use the Nano (32K) If it shrinks or stays roughly the same, I should be OK. However,if it 'bloats' due to extra C code ...

** As someone used to working with sub routines, arrays and variables, found it a bit of a hassle that everything has to be in one loop, only conditional statement breaking the flow - leastin TinkerCAD. And when you want to control 8 LED outputs, having to switch each one on and off via a digital write line. For example, the four output lines below:

11001100
01100110
00110011
10011001

... needs 32 digital write commands !! (And whilst the above is 4 lines, there are nearer 150 similar lines in final code, hence it's size)

The way I wrote it using ths above utility was something like:

for(counter=0; counter<4; counter){
if (counter==0){
    digitalWrite(2, HIGH);
    digitalWrite(3, HIGH);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
  }
if (counter==1){
    digitalWrite(2, LOW);
    digitalWrite(3, HIGH);
    digitalWrite(4, HIGH);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, HIGH);
    digitalWrite(9, LOW);
  }
//etc
}

The size of the text file and the size of your compiled code are impossible to relate. The compiled size purely depends on what your code consists of, not the size.

To find out how much room your code will take on the chip you need to compile it. The IDE will then tell you how much flash and RAM it takes.

For example:

Sketch uses 3730 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 157 bytes (6%) of dynamic memory, leaving 2403 bytes for local variables. Maximum is 2560 bytes.


Do AVR delay functions (_delay_us() and _delay_ms()) use timers? I'm trying to determine if the AVR delay functions _delay_us() and _delay_ms() use timers in such a way that I can't use those timers for other functionality in my code. If so, what timer does it use?

For reference I'm using an Arduino Uno with ATmega328, but I imagine if it's an AVR function it must work similarly on other devices.

No, these macros expand to calls to __builtin_avr_delay_cycles(),
which are compiled into delay loops. It should be noted that:

the arguments to these macros should be compile-time constants, they
can be floating point
the macros are cycle-accurate, e.g. _delay_us(0.125) will take
exactly two CPU cycles on an Uno
whereas the CPU time used by the call is exactly what you ask for,
the physical time will be larger if the call gets interrupted.


Problems on convert byte[] to String I'm reading a RFID Card from RC522 and send the data to my computer. My problem is the conversion of byte[] to String or std::string.

#define SIZE_BUFFER     18
#define MAX_SIZE_BLOCK  16

byte buffer[SIZE_BUFFER] = {0};
byte tam = SIZE_BUFFER;

// get data
status = mfrc522.MIFARE_Read(bloco, buffer, &tam);

  Serial.print(F("\nDados bloco ["));
  Serial.print(F("]: "));

// printing...
 for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      Serial.write(buffer[i]);
      str += String(buffer[i]);
  }

OUTPUT:

Dados bloco []: asdas

So, it's ok! But if I try make a string:

  String str = "";

  for (uint8_t i = 0; i < MAX_SIZE_BLOCK; i++)
  {
      str += String(buffer[i]);
  }
  Serial.println(" ");
  Serial.println(str);

The output is:

97115100971153232323232323232323232

What is the correct way to create a String from byte[]?

byte and char are the same. If you set 0 as string terminator after last character in the buffer, you get a zero terminated string. If you really must use String, you can create an instance with a constructor that takes zero terminated string.

buffer[tam] = 0;
String str((char*) buffer);

Let in the buffer a place for the zero. (char*) is cast that says that the byte array is a char array.

Note: Don't use String class in a MCU, use zero terminated character arrays.


Using Arrays and LED's to represent Piano Scales I am trying to use addressable LED's to show various piano scales using the semi notes formula for each scale as an array and an input to indicate the starting note.

int MajorScale[] = {2,2,1,2,2,2,1}; //represents the semi notes in a major scale
int t= 8 //represents the led number that represent the first C on the keyboard

The following leds should light up -

(8, 8+2, 8+2+2, 8+2+2+1, 8+2+2+1+2, 8+2+2+1+2+2, 8+2+2+1+2+2+2 , 8+2+2+1+2+2+2+1)  // This is first C Major Scale on the Piano

so..
(8,10,12,13,15,17,19) // This is first C Major Scale on the Piano where 8 is the first c

Then light up all the other C Major scales available on the piano limited by the number of keys on the piano in this case 76 keys

As there are 12 notes for each octave , add this to the array

if i take just the C note

8, 8+12, 8+12+12 ,8+12+12+12, 8+12+12+12+12  etc

My code so far just lights up the semitone that i set up in the array

enter code here
#include "FastLED.h"
#define DATA_PIN 5
#define NUM_LEDS 76
#define BRIGHTNESS 10
CRGB leds[NUM_LEDS];
int MajorScale[] = {2,2,1,2,2,2,1};
int delayValue = 1000;

void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
FastLED.clear();
}

void loop() {
for(int i = 0; i <=6; i++)
{
    leds[MajorScale[i]] = CRGB::BlueViolet;
    FastLED.show();
     delay(delayValue);

}

FastLED.clear();
}

Your current code will not show all notes of a scale. Only the notes at 1 and 2 will light up, since you don't sum up the numbers, that you have stored in MajorScale. But I think it is not a great idea to sum them up programatically, since this is a constant and you don't win much by representing the data this way. Instead you should directly initiate the MajorScale variable with the summed up values:

int MajorScale[] = {0, 2, 4, 5, 7, 9, 11};

Then you can enclose your for loop with another for loop, that adds an offset corresponding to the octave:

for(int j=0; j<NUM_LEDS; j+=12){
    for(int i=0; i<=6 && MajorScale[i]+j<NUM_LEDS;i++){
        leds[8+MajorScale[i]+j] = CRGB::BlueViolet;
        FastLED.show();
        delay(delayvalue);
    }
}

So we set the LED number 8+MajorScale[i]+j. 8 for the offset to C, MajorScale[i] as the position of the note in the current octave and j for the offset of the current octave relative to the C.

Note, that this is not tested in any way.


Arduino Uno with ESP8266 Wifi transceiver or ESP8266 NodeMCU board? I already have an Arduino Uno, and I want to learn Internet-of-Things. I'm planning to use an ESP8266 since it's cheap. Should I purchase an ESP8266 Wifi transceiver module to use with my Arduino Uno or just buy an ESP8266 NodeMCU board?

Is there any advantage using an ESP8266 NodeMCU board to using my Arduino Uno with an ESP8266 Serial transceiver module?

In my opinion, it is more desirable to program the ESP8266 directly. I'm always shivering when I see a Uno (ab)using the ESP8266 as a WiFi bridge when the ESP8266 already has everything needed for the project. Of course, this is highly project specific.

Advantages of programming an ESP8266 directly:

you learn about a new MCU and architecture (XTensa vs AVR)
you learn to use a new Arduino Core (Arduino-ESP8266)
ESP8266 is way more powerful than the Arduino Uno

80MHz (overclockable to 160MHz) vs 16 MHz
~40kB free RAM at startup vs 2 kB
4 MB Flash vs 32kB
can use an RTOS like FreeRTOS
Flash can be used as filesystem (e.g. for a HTTP(S) server)
==> we can build way more complex projects

WiFi radio and stack directly on the processor, no need to get information via a serial bridge

higher speed, more direct control over sockets etc.

you can try out other frameworks and languages, such as

Micropython
esp-open-rtos
the NodeMCU firwmare (Lua language)
Espressif's NON-RTOS / RTOS SDKs

easier to move to its big brother, the ESP32 (Dual-Core XTensa LX6 @ 240MHz, WiFi + BT, 4MB Flash, 520kB RAM (+4MB PSRAM optional), tons of peripherals and accelerators) for even more complex projects

Disadvantages:

only 1 ADC input (vs. 6) with a voltage range of 0 to 1.0V (unlike the normal 5V range on the Uno)

remedy: external ADCs via I2C / SPI (e.g. MCP3008)

3.3V device, must be careful when connecting to existing 5V devices or shields

remedy: logic level shifters, voltage regulators

less number of available digital GPIO pins (9 vs 13)

remedy: external GPIO expanders via I2C/SPI (e.g. PCF8574, MCP23017)

In summary, I think a good way of acquiring a better skillset is to try to explore and program a new board directly vs programming the old board and slapping the new one on top over serial. I hope this gave a rough overview of why an ESP8266 might be better (or worse) for a certain project.


while(1) inside if conditional if (!MDNS.begin("esp8266")) {
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }

I know this will result in an infinite loop if the if conditional is never satisfied, however I was wondering if this code would still result in an infinite loop if say, after 3 iterations the if conditional is satisfied?

Or if something like:

while(!MDNS.begin("esp8266")) {
   delay(1000);
}

is different?

Code from: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266mDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino (line 58)

In the first case, the first time, that the outer if statement becomes true, the code will go into the while(1) loop and will be stuck there forever.

The second code is different, since the while loop will check at each start of it's iteration, if the condition is still met. If not, it will exit, so not necessarily an infinite loop.

Going into an infinite loop, if something fails to initialize is often done in the microcontroller world, especially when initializing external hardware. A reset loop (restarting until it works) is mostly not fitting there, because often it is not just waiting for a resource to become free. Often this is used for serious problems, for example external hardware not being there or functioning. Imagine trying to use an external GPS chip, but the chip is not there. It should be there, since the device is build this way. Why should a reset loop be better here? The problem won't get away with time. Or imagine, that the initialization fails, because the GPS chip is broken. Trying to interface such a broken chip repeatedly might break even more things. Either way, someone has to look at this, to fix the problem. It will not go away by itself.

I would say, that the failed initialization in the library above is such a situation.


Why must I reload ArduinoCreateAgent-1.1-windows-installer-chrome every time I restart my computer? What am I missing that this is happening?
Used to use a laptop (with Create Agent installed on hard drive) which never had this problem.
Now using a Windows 10 desktop and the On-line Create Agent.
Unless I reload the Arduino Create Agent, I always get the 'No Plug-In Connection' error message, please see screen capture.  Device manager recognizes the Arduino Uno and assigns COM3 to the USB connection, please see screen capture.

Thank you to all who have suggested corrective action for my posted communication problem.  After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor.  Next I installed the Arduino Create Editor as a fresh/new install.  Magically, all of my communication issues with the Arduino Uno have been corrected.  Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.


Voltage and Current and Arduino I put a LED into 3.3V of the arduino and Ground, and it blew my LED violently, smoke was everyone, the whole half top of the led blew up across my room.

However, when i program the arduino with Pin13 HIGH per say, it will not blow up. Will be lit brightly. (Both using no resistors). However, if I plug mroe stuff in the board, for example, a lcd screen, rotary switches, and pushbuttons for my program, the LED dims to such a low brightness I cannot see.

Why is this? How Do I fix it?

Schematic:

Note, that i am using a mega, and some of it is slightly changed, and LED is being powered from A0 (Or Pin 54 on Mega)

You must use a resistor. See The care and feeding of LEDs

  How Do I fix it?

Use a current-limiting resistor.


Arduino exercise that i have no idea how to do The messages received by the Arduino take the form: $ Ba, Pb, Rc #
Where $ represents the beginning of the message, # represents m, and B, P, and R are characters representing B button, P period and R repetition.

`a 'designates the button to be read, which can be 1, 2 or 3.
`b 'designates the time (in seconds) that the button should be expected to be pressed.
`c 'designates the number of times the button is expected to be pressed during the indicated period.

For example, with the message: $ B2, P4, R2 #
you want to know if button 2 has been pressed twice for four seconds. If condition is verified, then the Arduino must send the message $ MSG, TRUE # where MSG represents the message received without the start and m message characters. Otherwise, you must send the message $ MSG, FALSE #.
Incoming messages must respect the format presented. If not, the condition is not checked and the message $ NOK, MSG, KON # must be sent as a response.
I have no idea how to do this since im new to arduino

To begin, forget the Arduino for a moment and assume the task of determining true or false from $....# message. Think about what you would have to do, step by step, to accomplish this. (e.g.: Read the buttons; Record the time and the button states. Is there a message from the Serial port beginning with '$'? Then read the rest of the message. etc.) Then, for each of those steps, do the same thing again: write down the smaller steps to accomplish what that step requires. Do that until you can't break it down any further.
Those small steps should each look like something you could do in C++ code (sometimes called "Arduino" code, but it's really C++). Start replacing each English (or your language) steps with the C++ equivalent. Do this until all of the human-language steps are written in C++.
There will inevitably be mistakes. Fix one or a few at a time. When you're stuck, ask here, something like "Here is my (well formatted) code. I tried [this]. I expected to see [that]. But what happened instead was [something else]. How can I fix it?"; or: "I am getting this error message [with its complete text including any line numbers, please] from the compiler. What does it mean, and how could I have found that out on my own?"
Small steps....


Using displays with Arduino Uno Does anybody know if there is any documentation available online on basic information about using displays with Arduino Uno? I've never used displays before and would very much appreciate some basic information on the different types etc..

Any information that can help me choose what display I want to buy for my next project will be helpful.

for ex: Right now I don't even know what a shield is in context to a display and whether or not I should look for one in my purchasing my display.

The Arduino website has a list of LCD displays and link with more information about each one. For controlling the display you may want to look at Arduino's LiquidCrystal Library.

If you are looking for a step by step guide for using a lcd display with the Arduino, there is a nice guide on Adafruit.


Use 5V SD-Adapter on 3.3V System I want to use a Catalex Micro SD Card Adapter in Combination with my Arduino MKR GSM 1400. The problem is, that the Arduino uses 3.3V to operate but the SD Adapter needs 5V (or at least 4.5V) to operate properly. Can I just use the 5V output of my Arduino to power the adapter, or will a higher voltage destroy the arduino when using it over a longer period of time? And if so, how can I use my MKR GSM 1400 with a SD-module? Maybe by unsing a step up/down converter in my circuit or just switch to a module that uses 3.3V?

The SD card is a 3.3 V device. The 5 V module with SD card adapter steps down the voltage for powering the card and has logic level conversion for card's SPI pins.

If you want to connect SD card to a 3.3 V board it is better to use a simple breakout board without power and signal conversion.

I do not recommend you to connect a 5 V SPI device to MKR SPI pins without logic level conversion.

EDIT: smajli analyzed in his answer the logic level conversion chip used on the adapter you use. it doesn't output more than 3.3 V and you can use it powered from 5 V. but it is still a workaround.


How to choose between AM230x and DHT22 temperature and humidity sensors? I'm looking forward to getting an accurate humidity and temperature sensor.

Right when I decided to go with a DHT22 module, I saw AM230x (AM2301, for example).

How do I choose between DHT22 and AM2301?

The AM2301 and the DHT22(AM2303) are similar in a number of ways, both in price, specs, ranges and power consumption. They are usually cased a bit of a differently, with the DHT22/AM2303 being packaged with four pins (only three are in use), and the AM2301 (formerly called DHT21) is packaged with three cables and a small plug inside of the case.

I would choose based on the usage, if I'm going to use the sensor on a breadboard or a socket (going for the DHT22 pinned version), or if I'm going to have it standalone (the cabled one).

Here are links to the datasheets:

https://kropochev.com/downloads/humidity/AM2301.pdf

https://www.adafruit.com/datasheets/DHT22.pdf


I want to program multiple arduino at once I am aware that using a USB Hub you can attach multiple arduino to one computer and either upload code one by one or use bash script to upload code on all arduinos together. But you can attach only as many arduino to a computer. I need to prgram around 100 arduinos/atmega ICs at once. Is there a way to do so?
There are other methods that I found online like programming ICs over Wifi network. But that require a lot of WiFi chips connected to arduino. I cant setup that. Also that doesn't seems cost effective.
Also Arduino sells their uno and other boards with pre-installed blink program. They must be doing batch programming only (multiple ICs at once). Any idea how they do this?

Arduino, the company, may sell on enough volume to make it worthwhile to get the microcontroller manufacturer to program the microcontrollers durin the production process
This wouldn't cost them extra if they already get the bootloader pre-programmed. I've read programming ICs is a service available to high volume customers.
I guess low volume makers use fixtures that use the ICSP headers, pogo sticks or IC clips and which trigger the programming on contact using a microswitch etc.
I suspect Adafruit do something of this sort, see GIFs and video discussing testing at
https://www.adafruit.com/product/2458


Why does my Arduino 3.3v fluctuate? For some reason, my 3.3v on my Arduino is fluctuating a lot, and I am not sure why.
The multimeter is measuring dc voltage and is connected between GND and 3.3v of an Arduino Mega.

The multimeter works fine. Connecting between 5v and GND gives 5V on multimeter.

Arduino output voltages may "fluctuate" a few mV but what you showing us in that gif is really unstable.

What you should be doing is:

Disconnect everything from Arduino except the power source
measure the voltage again;

Is it stable? the problem was because of pulling too much current that causing voltage drop and instability .

Is it unstable?

Try checking with another MM and/or change auto-range to manual.

Is it stable when measuring the voltage with another MM? something was wrong with your previous MM.

Still unstable?

Connect the Arduino to a 9V power adapter and disconnect the USB cable.

Measure the voltage again, if it's stable the problem was because of some error in the cable or USB power source.

Voltage is still unstable?

change the 3.3V voltage regulator.

It should fix the problem if not report back to do some more in-depth problem solving.


How would I include Arduino libraries using AVR-gcc without the IDE? I am writing my own code for the Arduino Uno. I compile my code with AVR-gcc, and then upload it with AVRdude. I am not using the Arduino software, but I do have it installed and working on my PC. I want to include some of the Arduino libraries in my project, like Wire.h for example.

I realise that I could either copy the source file to my current working directory or include the entire path, like: #include "/usr/share/arduino/libraries/Wire/Wire.h" but the issue with that is Wire.h includes Stream.h which includes Print.h which includes...you get the idea. These different libraries are not kept in the same place either. I would have to hunt up and down chains of files, copy them and then use them locally. This does not seem like a good option to me.

Including them like I normally would using the IDE doesn't work at all, which is not surprising.

So, how can I use these libraries in my project without all the pain of finding them manually?

Since you will end up using a significant portion of the Arduino core
library, the easiest path is to accept the idea that you are now writing
“Arduino sketches” rather than plain C++ code. Don't resist, be
assimilated, fire the IDE and write setup() and loop(). ;-)

Once you have something working, the next step is to get rid of the IDE,
which is admittedly not very nice. A couple of ways to do that:

Use Arduino Builder, the command-line tool for building
Arduino sketches. The internals of this are the same as for the
Arduino IDE, but it works on the command line.
Use a Makefile, like Sudar Muthu's Arduino-Makefile. This
is a generic Makefile for building Arduino programs. It is not 100%
compatible with the IDE or Aduino builder, as it does not add function
declarations for you, but it may suit you better if you are used to a
more standard toolchain (it's just make + avr-gcc + avrdude).


Why is my TMP35 giving me weird values? A TMP35/36/37 is giving very high voltage readings, which results in high temperature readings. The serial monitor looks like this:

As you can see, the sensor value is in the 900s, voltage is almost 5, and temp is in the 400s. The circuit is very simple, just a TMP connected to 5V and ground and pin A0. Here is my code:

const int sensorPin = A0;
const float baselineTemp = 20.0;

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

}

void loop() {
  int sensorVal = analogRead(sensorPin);
  Serial.print("Sensor value: ");
  Serial.print(sensorVal);

  float voltage = (sensorVal / 1024.0) * 5.0;
  Serial.print(", volts: ");
  Serial.print(voltage);

  Serial.print(", degrees C: ");
  float temperature = (voltage - .5) * 100;
  Serial.println(temperature);
  delay(1000);
}

This is a very simple program and a very simple circuit, so I'm not sure what is going on. Maybe the problem is the sensor itself. I have also tried this sensor with multiple other circuits and programs and the same thing happens.

If anyone knows anything about this, help would be great.

I use voltage dividers a lot and have seen this before.

In each and every case where ALL my readings are high, yet they vary predictably (like on my solar panels - they go up during day and down at night), there has always been proven to be a very simple, single cause.

Resistance in the ground lead.

Such as if it is plugged into a breadboard hole that is not holding it well, or if I have extended it and have connections along the way.

So that would be the first thing I would look for.

Having said that, if the readings are very high and do NOT vary predictably, then I would look for a disconnected ground lead.

If all the connections are good but it still misbehaves then I would swap it out with another one to make sure the part itself isn't the problem.


Verifying the timing between relay activations I would like to verify timings of a relay controlled by an arduino (uno R3). There is a lot going on in the sketch and it does not use the delay function but one which is based on counting milliseconds. The arduino then transmits to another arduino using a radio module (nRF24L01). I'd like to confirm the intervals between the relay, so for instance if the relay is acivated 10 times and there are 5 seconds between each actvation.

So what I was wondering was whether anyone had any reccomendations on methods to verify timings using an external source.

Two ideas I came up with were: have another arduino with a very simple script that measures the timings or try and find/write a verilog script to upload to a mojo fpga and measures the timings.

An ideal situation would be where I have a seperate device that hooks up to the relay and then measures and displays the timings between the relay switches and is extremely precise.

I hope that makes sense, if not please let me know and I'll explain further. Thank you for reading and any help is greatly appriciated.

You could use sigrok with one of the many supported devices.
For example, you can find on ebay an 8 channell 24MHz probe for less than $10.

It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.


Arduino UNO Rx/Tx speaks to itself I'm trying to make my chinese arduino (which use a chinese CH340G chip) speaks to itself via serial.
I have wired rx/tx together.

Then, I run the arduino IDE and go to the serial monitor.

When I write a message, the arduino should respond with the exact same message, right ? Actually, when I write a message, the arduino doesn't respond anything...

As Mikael Patel pointed out in his answer, you have set up a voltage divider. Mikael has thoughtfully provided a schematic of the clone Uno, where the relevant part is here:

Equivalent circuit

If you jumper together pins D0 and D1 (Rx and Tx) on the Uno effectively you have made this circuit:

Testing

If I set up this with a function generator, I get this result:

You can see that for a square-wave input of 0 to 5V, we only get an output of 2.16 to 5V.

What is LOW?

Now looking at the datasheet for the DC characteristics we see:

For an input to register as LOW it has to be no higher than 0.3 * Vcc = 0.3 * 5. Thus the voltage cannot be higher than 1.5V. Since we are measuring 2.16V, that will not count as a LOW.

Now admittedly that is for the Atmega328P and not the CH340G, but it will probably have similar characteristics.

I found a datasheet for the CH340G, and that shows even stricter requirements for a LOW signal:

Official Uno

Comparing to the official Uno circuit:

You will note there that the indicator LEDs are on a different circuit, and thus do not form a voltage divider.

The Maths

The clone Uno circuit above can be re-arranged like this:

Given that the LEDs have a voltage drop of 1.86V (measured in practice, and about right for the red LEDs I am using) then effectively we have the resistors R1 and R2 connected to 3.14V.

Since they are in parallel they are effectively 500 ohms.

Now using the formula for voltage dividers:

1000 / (1000 + 500) * (5 - 1.86) = 2.09V

This is close enough to the observed result. I didn't check each resistor to make sure it was exactly in spec.

I don't think R4 affects the results because it is effectively "floating".


RF24 Network and Payload i struggle to figure out the max payload for the RF24 Network library without payload fragmentation.
It uses a NetworkHeader with the Attributes from_node, to_node, id, type and reserved.
This must be send to and lowers the amount of Bytes of the payload.

Can any one tell me how many Bytes I can write without sending two packages?

According to the source code:

const static unsigned int max_frame_payload_size = MAX_FRAME_SIZE-sizeof(RF24NetworkHeader);

that would be 24 bytes. Maximum lenght of payload for NRF24L01+ is 32 bytes and the RF24NetworkHeader seem to be 8 bytes long. So you can send up to 24 bytes in one package.

EDIT:
Here is the stripped RF24NetworkHeader declaration code from which can be seen sizeof(RF24NetworkHeader) is 8 bytes.

struct RF24NetworkHeader {
  uint16_t from_node;           // 2 bytes
  uint16_t to_node;             // 2 bytes
  uint16_t id;                  // 2 bytes
  unsigned char type;           // 1 byte
  unsigned char reserved;       // 1 byte
  static uint16_t next_id;      // static member doesn't count for sizeof()
  RF24NetworkHeader() {}
  RF24NetworkHeader(uint16_t _to, unsigned char _type = 0): to_node(_to), id(next_id++), type(_type) {}
  const char* toString(void) const;
};


Use large variables without using much memory I've wired up a dot matrix, and I display characters on the screen by using something like the example code below.

The Char_B variable is a global variable in a library used by the Arduino, and displayPixels() is called from inside the library.

bool Char_B[8][8] = {
{0,1,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,0,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,0,0,0,1,0,0},
{0,1,1,1,1,0,0,0}
};

displayPixels(1000, Char_B);

However, each time I declare a new character like the array above, I use a relatively massive amount of memory. Is there any way to reduce memory usage? Keep in mind I am willing to change the structure of the array if necessary, since I'll need well over 100 characters loaded onto the Arduino to write text.

The data structure will take 64 bytes as sizeof bool is 1 byte not a bit. The first option is to pack each line (or column) in a byte (or bytes). The prefix 0b is for binary constant value (in gcc).

uint8_t Char_B[8] = {
0b01111000,
...
0b01111000
};

The second option is to move the data structure to program memory.

const uint8_t Char_B[8] PROGMEM = { ... };

This will require reading each line with a special function.

for (int line = 0; line < sizeof(Char_B); line++) {
  uint8_t pixels = (uint8_t) pgm_read_byte(Char_B + line);
  ...
}


Measuring the capacitance of 2 capacitors at a time I need help with my project. In my project, I have two homemade capacitors made from 2 aluminum foil strips separated by a water bottle. I need to detect which bottle is going to become empty as people drink from it. So I plan to use the change in capacitance to detect the empty bottle. I know how to measure capacitance of 1 bottle and detect the change, but I don't know how to do it to 2 bottles at a time. Any ideas how to do this?
Here is the following code, I have been working on.

// Initialize Pins
int analogPin = 0;
int analogPin1=1;
int chargePin = 13;
int chargePin1=12;
int dischargePin = 11;
int dischargePin1 = 10;

// Initialize Resistor
int resistorValue = 10000;

// Initialize Timer
unsigned long startTime;
unsigned long elapsedTime;

// Initialize Capacitance Variables
float microFarads;
float microFaradr;
float nanoFarads;
float nanoFaradr;

void setup()
{
  pinMode(chargePin, OUTPUT);
  pinMode(chargePin1,OUTPUT);
  digitalWrite(chargePin1,LOW);
  digitalWrite(chargePin, LOW);
  Serial.begin(9600); // Necessary to print data to serial monitor over USB
}

void loop()
{
  digitalWrite(chargePin, HIGH); // Begins charging the capacitor
  digitalWrite(chargePin1,HIGH);
  startTime = millis(); // Begins the timer

  If(analogRead(analogPin)>648){
    elapsedTime= millis() - startTime;
    microFarads = ((float)elapsedTime / resistorValue) * 1000;

    if (microFarads == X) // X is an arbitrary capacitance when the bottle is empty and X is not a variable
    {
      Serial.println(" Bottle A is empty");
    }

    digitalWrite(chargePin, LOW); // Stops charging capacitor
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW); // Allows capacitor to discharge
    while(analogRead(analogPin) > 0)
    {
      // Do nothing until capacitor is discharged
    }
    pinMode(dischargePin, INPUT); // Prevents capacitor from discharging
  }

  If(analogRead(analogPin1)>648){
    elapsedTime= millis() - startTime;
    microFaradr = ((float)elapsedTime / resistorValue) * 1000;

    if (microFaradr == Y) // Y is an arbitrary capacitance when the bottle is empty and Y is not a variable
    {
      Serial.println(" Bottle B is empty");
    }

    digitalWrite(chargePin1, LOW); // Stops charging capacitor
    pinMode(dischargePin1, OUTPUT);
    digitalWrite(dischargePin1, LOW); // Allows capacitor to discharge
    while(analogRead(analogPin1) > 0)
    {
      // Do nothing until capacitor is discharged
    }
    pinMode(dischargePin1, INPUT); // Prevents capacitor from discharging
  }
}

Before we get started, there are a few problems with your code.

First, I wouldn't check for ==648 or ==0: what if you miss it by a moment and it jumps to 649, or it doesn't quite discharge to 0v?  I'd use >=648 and <=2 (or some other similarly low number - experimentation required).

How is your circuit connected?  I can't quite get my head around the charge and discharge pins, but I'll stick with what you have, assuming it works.

You say you want measurements every 30s, but don't say how long they take. (I have no idea of the capacitance of your bottle.)  My code assumes it takes much less than 30s to measure one bottle.  If it takes near to 30s to do one, this won't work.

I'll also assume your code works.  This is a bad assumption, since it won't even compile (capital I in if) but regardless, that's what I'll assume.

All that being said, here's the code:

// Pins connections
int analogPinA = 0;
int analogPinB = 1;
int chargePinA = 13;
int chargePinB = 12;
int dischargePinA = 11;
int dischargePinB = 10;

// Resistor being used
int resistorValue = 10000;

void setup()
{
  pinMode(chargePinA, OUTPUT);
  pinMode(chargePinB, OUTPUT);
  digitalWrite(chargePinA, LOW);
  digitalWrite(chargePinB, LOW);
  pinMode(dischargePinA, OUTPUT);
  pinMode(dischargePinB, OUTPUT);
  digitalWrite(dischargePinA, LOW);
  digitalWrite(dischargePinB, LOW);
  Serial.begin(9600);
}

// Measure the capacitance of specified capacitor
float measureCapacitance(int analogPin, int chargePin, int dischargePin)
{
    // Ensure the capacitor is discharged
    digitalWrite(dischargePin, LOW);
    while (analogRead(analogPin)>2) { /* Do nothing */ }
    pinMode(dischargePin, INPUT);

    // Start charging
    unsigned long startTime = millis();
    digitalWrite(chargePin, HIGH);

    // Wait for the capacitor to charge
    while (analogRead(analogPin)<=648) { /* Do nothing */ }
    unsigned long endTime = millis();

    // Start it discharging again, ready for next time
    pinMode(dischargePin, OUTPUT);
    digitalWrite(dischargePin, LOW);

    // Calculate measured capacitance
    unsigned long elapsedTime = endTime - startTime;
    float microFarads = ((float)elapsedTime / resistorValue) * 1000;
    return microFarads;
}

void loop()
{
    // Measure capacitance of first bottle
    float microFarads = measureCapacitance(analogPinA, chargePinA, dischargePinA);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle A is empty");
    }

    // Measure capacitance of second bottle
    float microFarads = measureCapacitance(analogPinB, chargePinB, dischargePinB);
    if (microFarads <= X) // X is an arbitrary capacitance when the bottle is empty
    {
      Serial.println("Bottle B is empty");
    }
}


Using timer2's ISR instead of timer1's in Arduino wiring.c breaks Serial object I want to change timer0 frequency because I need to use 4 PWM pins at a frequency lower than 500Hz and the SPI on an ATmega328. So I changed timer2 to Fast PWM with 64 divisor, enabled the overflow interrupt for timer2 and disabled the overflow interrupt for timer0:

  TCCR2A = _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS22);
  TIMSK2 |= (1 << TOIE2); // enable overflow interrupt for timer2
  TIMSK0 &= ~(1 << TOIE0); // disable overflow interrupt for timer0

and changed the ISR vector in wiring.c from ISR(TIMER0_OVF_vect) to ISR(TIMER2_OVF_vect).

But delay doesn't work. What can be the problem?

Now everything works except for delay()

delay() uses micros() and micros() reads the hardware registers, like this:

unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t = TCNT0;
#elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t < 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.


Arduino vs Old Computers How does an arduino microprocessor compare to some of the older computers in RAM, and computational speed? Like how does it compare to the Intel 400 or the original IBM PC. I'm interested in both the Atmega328 and the 2560. Just how much better/worse is the arduino compared to an old computer?

Similar capability in turns of processing power if you compare back 10 -20 years.

arduino is a micrcontroller not a microprocessor.

A good example is the pdp11 minicomputer and the ti msp430 micro controllers. They share the same instruction set (approx 90%) . Both can (or could) do realtime event handling but pdp11 was more for data processing. Though pdp11 didn't have integrated peripherals

see bottom of this page http://www.cpushack.com/CPU/cpu4.html


Why does this code execute? After experiencing failures of my Arduino projects due to low memory, I decided to do some research into it so I could understand better where the problems were. I eventually came to this code:

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

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));
}

void loop() {
  int timing = 1000;
  delay(timing);
  digitalWrite(13, HIGH);
  delay(timing);
  digitalWrite(13, LOW);
}

I expected that since my Arduino Uno does not have enough RAM to hold an array of 5000 bytes (Atmel's information on the Atmega328P shows us it only has 2KB of SRAM), the code in void loop() would not be able to run due to lack of memory. As far as my understanding goes, once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes), there would physically not be enough space left in memory for the variable timing and the LED I attached on pin 13 would not flash on and off at intervals of 1 second.

However, my LED toggles at perfect intervals of 1 second. Why would this occur? Isn't memory allocated by malloc unavailable for use by anything else until free is called on it?

If you add a debugging print you will see what is happening:

void setup() {
  Serial.begin (115200);
  Serial.println ();

  pinMode(13, OUTPUT);

  int len = 5000;
  byte *data = (byte *)malloc(len * sizeof(*data));

  Serial.print ("data = ");
  Serial.println ((int) data);
}

Output:

data = 0

The malloc failed, it returned NULL, the rest of the program proceeded normally.

  once malloc has allocated 5000 bytes (or as many as it could of the 5000 bytes)

malloc does not return with a partial allocation. It either allocates the amount you requested or none at all.


Is it any way to connect ESP8266 to wifi faster? I'm uploading this sketch to try connecting ESP to internet. However, most of the times I've ran it it takes a very long time to connect, a lot of times I've had to break the process because it seems it goes to nowhere. Few times it has connected in less than a minute. Is it any alternative to boost the connection?

Also, when I reset the module, it writes to the terminal 3 strange characters, and freezes without even starting to execute its sketch. Do you mind me asking how to solve that?

Regards!

#include <ESP8266WiFi.h>

const char red[] = "CDT10";
const char pass[] = "G7ZSY74Cs";
unsigned long muestra = 0;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(red,pass);
  while (WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address: "); Serial.println(WiFi.localIP());
  Serial.print("Chip ID: "); Serial.println(ESP.getChipId());
}

void loop() {
  delay(5000);
  muestra = millis();
  Serial.println(muestra);
}

I have also experienced the inability to connect sometimes. I wait a certain amount of time for it to connect then do a ESP.reset() if it fails.

As for the boot problem it sounds like you are keeping GPIO0 low so it goes back into programming mode. Hold it high and it will run your program instead.


Comparing 2 char converted from a array I wrote this little program to test converting and comparing 2 char with each other. With some help from here i have learned that you have to NULL-terminate c stings. But when i try to compare them i still get that they are not equal to each other. this is my program:

char code[4] = {'1','2','3','4'};
char strcode[5];
char pass[4] = {'1','2','3','4'};
char strpass[5];

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

void loop()
{
    memcpy(strcode, code, 5);
    strcode[4] = '\0';
    Serial.println(strcode);
    Serial.println("done");
    delay(1000);
    memcpy(strpass, pass, 5);
    strpass[4] = '\0';
    Serial.println(strpass);
    Serial.println("donepass");
    if (strpass == strcode)
    {
        Serial.println("yes");
    }
    else
    {
        Serial.println("no");
    }
}

I get this in my serial monitor:

1234
done
1234
donepass
no

Why is this not equal to each other?

You cannot compare char arrays with ==. A char array, as far as your program is concerned, is just a block of memory. That memory has an address where it starts. It is that address that is stored in your array variable.

C string library functions take that address and read the block of memory starting there. However it doesn't know how big the memory block is, only where it starts. So they operate on the content up until they find the NULL character (which is why it is vitally important to NULL terminate your strings).

Comparing two char array variables with == is just comparing the addresses stored in those variables. Instead you need to compare, byte by byte, the contents of the memory starting at the specified memory addresses up until the NULL characters.

There's various functions for doing that depending on how you want to compare.

strcmp(a, b)
strncmp(a, b, n)
strcasecmp(a, b)
strncasecmp(a, b, n)

All return 0 for a == b, a negative number for a < b and a positive for a > b.

The "n" variants (e.g., strncmp) take the extra parameter giving a maximum number of characters to compare. Useful for looking at just the first few characters of a string (also useful for stopping buffer overruns).

The "case" variants are case insensitive comparisons - that is "foo" matches with "Foo" and "foO".


Get servo to travel full length Recently we purchased servos for use in an Arduino and began testing with servos. It turned out that the uSec for the servos differed from the online documentation and we had to find the min and maxes of the uSecs manually:

while (Serial.available()) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the string readString
    delay(2);  //slow looping to allow buffer to fill with next character
}

if (readString.length() >0) {
    Serial.println(readString);  //so you can see the captured string
    int n = readString.toInt();  //convert readString into a number
    Serial.print("writing Microseconds: ");
    Serial.println(n);
    myServo.writeMicroseconds(n);
    readString = ""; //empty for next input
}

The issue is that the servos don't travel the full 180 degree advertised price (more like 135-160) and that lack of angular distance is affecting performance of one of our products. The servos can even mechanically travel a noticeable distance farther than 180, but not "programmatically" farther even when given a larger PWM uSec value that the observed "max" PWM value

What I've found

I looked around and apparently there are "Servo Programmers" to calibrate endpoints and midpoints, but cost an arm and a leg. I find it strange that I would have to "program" my servos. I was part of an First (FTC) robotics team using tetrix/nxt electronic control systems, and never noticed a problem with uSec values or not getting the full range of motion using the same brand of servos I currently am now.

  How can I perform a low cost, easy way to simply get the full range
  of motion I paid for?

This is an analog servo, so there is no endpoint calibration on the servo side. This type of calibration is for digital servos (which can be tuned) and controllers.
On the servo description page, they talk about a stretcher. This is a translation tool to help with old controllers:  usually servos have a narrower band: 1000us to 2000us for 0° to 180°. Therefore old controllers can only do 1000us to 2000us, and would fail to achieve full range with this servo, which requires 600us to 2400us

Also, note that RC servo input signal isn't really a PWM: duty cycle doesn't matter, only lengh of the pulse does.

Your servo doc says: 600us to 2400us for -90° to +90°, which correspond to what the Servo lib does by default according to its documentation. You should be fine. What are the results of a super simple sweep-like code? eg:

loop() {
  myServo.writeMicroseconds(600);
  delay(2000);
  myServo.writeMicroseconds(2400);
  delay(2000);
}


Run program from SRAM on SAMD21? I am looking for an example of how to load a program from sd card to SRAM and execute it from there on the SAMD21.

I understand that the given MCU use the Von Neumann architecture and all code is privileged.

There's two aspects to what you want to do - one (relatively) easy, and one (comparatively) hard.

The first thing you will need is some way of getting your program into RAM. That would mean some software running on the chip that will accept the program and place it into RAM then execute it. You will have to write your own bootloader-like program that runs in Flash that will perform the task.

The second, harder, thing is to compile your program in such a way that it will execute from RAM. And that's no easy task.

Ideally you want to compile the code as position independent code (with the command line flag -fPIC), but that depends on the compiler being able to do that for this chip. If not, you will have to compile it so that the code expects to reside in RAM with all addresses used for jumps, etc, going to the right location. And that brings me to the second aspect of compiling, the linker script.

If you have your code in RAM you can't also have your variables in the same place in RAM. You will have to subdivide the RAM into two sections - the code execution section and the variable storage section. This is done through the construction of a custom linker script which is used during the linking phase of compilation. It tells the compiler where in memory to place everything - code, variables, etc. You will need to craft your own linker script to divide the RAM up in a suitable manner to give you enough room for your code while at the same time not starving it of variable storage space. This will also make sure all jumps, etc, in your code use the right addresses in case you can't (or don't want to) use -fPIC.

So, given all that, do you still really want to execute code from RAM?


Using TX/RX serial pins to communicate over USB I'm using an Arduino Nano with an Atmega 328p.
I would like to attach and use a different USB port instead of the builtin one for supplying power, serial debugging and uploading code.
Currently my board is recieving power from the USB port using vin, but I would like to know how I can get the Arduino to use serial communication with the TX/RX pins and the data+ and data- pins on the USB. I'm especially interested in knowing if I can upload new code to the board through TX/RX.
The official page for the Nano says that the serial communication is handled by an FTDI FT232RL chip, which as I understand, translates the signal from the builtin USB to serial. Is there any way that I can use this chip to communicate over the TX/RX pins instead of builtin USB?
Online documentation about this subject is really lacking, and of the few opinions that I've found, many are conflicting. I would really appreciate any help with this, thanks.

There is no "built-in USB" on the Nano. There is only the FT232RL chip which talks USB. That chip is connected directly to the TX/RX pins inside the board.
You are already communicating over the TX/RX pins through the FT232RL to the USB.
Yes, you could use your own FT232RL (or FT232-like) board to communicate between USB and the TX/RX pins, but that will be exactly the same as using the one built in to the board - but without the convenience, and with the addition of more wires and expense.  So pointless, unless the current USB connection is damaged in some way.


Arduino with stepper motor I'm trying to control a stepper motor for my FYP with an Arduino Mega. I tried code form examples, stepper one revolution. It worked when I uploaded it but if i turn the power off during the half position of a revolution, then next time I turn on the supply it first moves that portion backwards then it works according to the program. I want that when I turn on the power supply it should move according to the code and forget the last movement. Can anybody help me on this issue?

A stepper motor doesn't have any mechanical "steps" as such. When powered off, a stepper is free-wheeling. When you power it up - energize a set of set of coils - the rotor will move to the nearest of several positions corresponding to whichever coils are energized. Thus, it doesn't retain its position across a power-down; your code has to "find it" each time. Usually that involves driving it until the attached mechanism trips an optical or mechanical switch, giving the software a reference-point. Your other option is to apply a holding current (less than the stepping current) to the presently energized coils and not completely power down the motor's power supply when the rest of the system powers down. The software would have to save the motor position before the power down in a non-volatile memory, such as EEPROM, where it can retrieve it again at the next power-up.


How to extract the last byte out of an IP adress Newbie question:

I need to pass the last byte of a local IP as a parameter.
Eg.: when Ethernet.localIP() returns 192.168.0.100,
I need to extract the 100 and put it in a char array or string.

Anyone any ideas? Thx!

localIP() returns an IPAddress object.  That object has an operator for [] allowing you to access the individual parts of it.

IPAddress ip = Ethernet.localIP();
Serial.println(ip[3]);


Problems recycling c++ lib with templated class for Arduino I have a header & cpp file located in Arduino\libraries\Parentfolder\Header&Cpp. Arduino IDE recognizes my lib (the class is color coded & Sketch->include library->MyLibrary shows in the dropdown menu and #includes properly).

Problem: Arduino IDE gives undefined reference to MyClass . . . error in my sketch for every reference of the class including function calls. The function fully in other IDEs as header/cpps so I don't think pasting the cody is necessary -- what could I be missing? I've read a million Stack Exchange posts with similar error/watched a million YouTube guides on writing Arduino libs and I can't seem to find the differentiating factors that would make my code not work for Arduino IDE.

tl;dr what are the reasons that a working c++ library (self-made) would not work with Arduino IDE?

/e

Queue.h
#ifndef Queue_h
#define Queue_h

#include "Arduino.h"

template <typename T>
class Queue
{
  public:
    typedef struct node
    {
      T data;
      node * next = nullptr;
    } * nodePtr;

    nodePtr head; // = nullptr;
    nodePtr tail; // = nullptr;
    nodePtr curr; // = nullptr;
    nodePtr temp; // = nullptr;

    unsigned int counter;

    Queue();
    void push(T);
    T& peek();
    T pop();
    int size();
    bool isEmpty();
    void clear();
};

#endif

Queue.cpp

#include "Arduino.h"
#include "Queue.h"

template <typename T>
Queue<T>::Queue()
{
    nodePtr head = nullptr;
    nodePtr tail = nullptr;
    nodePtr curr = nullptr;
    nodePtr temp = nullptr;

    counter = 0;
}

template <typename T>
void Queue<T>::push(T data)
{
  if (head == nullptr)
  {
    head = new node;
    head->data = data;
    tail = head;
  }
  else
  {
    temp = head;
    head = new node;
    head->data = data;
    head->next = temp;
  }
  counter ++;
}

template <typename T>
T& Queue<T>::peek()
{
  if (head == nullptr)
  {
    return 0;
  }
  return head->data;

}

template <typename T>
T Queue<T>::pop()
{
  // Empty
  if (head == nullptr)
  {
    return 0;
  }

  // Head = tail
  if (head == tail)
  {
    T data = head->data;
    delete head;
    return data;
  }

  // Size > 1
  curr = head;
  while (curr->next != tail)
  {
    curr = curr->next;
  }
  T data = curr->next->data;
  tail = curr;
  curr = curr->next;
  delete curr;
  counter --;
  return data;
}

template <typename T>
int Queue<T>::size()
{
  return counter;
}

template <typename T>
bool Queue<T>::isEmpty()
{
  if (counter ==0)
  {
    return true;
  }
  return false;
}

template <typename T>
void Queue<T>::clear()
{
  while (head->data != nullptr)
  {
    temp = head->next;
    delete head;
    head = temp;
  }
  if (head == nullptr)
  {
    return;
  }
  delete head;
  return;
}

.ino

. . .
Queue<float> avgQueue;
. . .

error

. . . In function `__static_initialization_and_destruction_0':
. . . undefined reference to `Queue<float>::Queue()'

SOLVED:

Combining the .cpp contents in the .h and removing the .cpp worked.

SOLVED:

Putting the .cpp contents in the .h and removing the .cpp from the lib folder entirely worked.


Arduino Video player? I want to play video from SD card   by using arduino mega 2560 and TFT 3.2" touch screen is it possible ?

if yes please tell me.

thanks in adavance

An ATMEGA2560 has no enough computational power to perform on-the-fly decoding, even at resolutions as low as 160x128 pixels and low frame rates.

The best you can hope for is a 20 fps, 16 bpp, 160x128 pixel video, directly streamed from the SD card, uncompressed (800kB/s), if the MCU runs at 16MHz. Even with such low specs, you'll have to use a trick, to implement a direct peripheral to peripheral transfer.

We made a guide here for the Arduino Uno (i.e. ATMEGA328P), but it should work also for ATMEGA2560 with little modifications: https://next-hack.com/index.php/2017/08/14/how-to-play-a-video-on-arduino-uno-46-playing-a-20-fps-animation-from-sd-card/

On the same link you'll find also the youtube links for a video guide.


How avoid TCP packet fragmentation? I'm using an Arduino Uno with an Ethernet Shield and the arduino.cc Ethernet library for a custom TCP-based message-exchanging chat-like protocol. Specifically I'm using the Client class with its print()
and println() methods. It works.

But on each single print() or println() call a whole TCP packet is sent. Also if just one byte is printed, a whole TCP packet is sent over the IP layer. I mean there's a lot of TCP packets with very few data inside. In other words there's a big overhead.

For example take this message that my Arduino successfully sends and my server successfully receives:

i-am EEEEEEEE-EEEEEEEE-EEEEEEEE-EEEEEEEE\r\n

The code is the following:

stream.print("i-am");
stream.print(' ');
for (byte i = 0 ; i < SERIAL_CODE_LENGTH ; i++){
  if (  i % 4 == 0 && i != 0 ){
    stream.print('-');
  }
  if (serialCode[i] < 16){
    stream.print('0');
  }
  stream.print(serialCode[i], HEX);
}
stream.println();

All that EE are hexadecimal byte values from an array and they are fine. But I can see from Wireshark that those 42 bytes (that could be fit in a single packet) are sent in 22 TCP packets (one for each print call in my code)!

How can I avoid this fragmentation? Is there a way to use an hardware or software buffer to group data before to send (Nagle's algorithm)?

With other SDKs the data are buffered by default and they're sent when the buffer is full or when an explicit "push" or "flush" call occurs. I checked Client flush method and it looks to be a different beast...

I suspect its stream.print() that is causing the problem.  Write the data into a string and then use a SINGLE call to stream.print() to send the data.  It looks like it is trying to send it as soon as possible to prevent delays and this is what is causing fragmentation..