Convert the Serial.Println to string I'm working with VirtualWire and I'm trying to get a string value out of the Serial.println in the loop. I've tried create a string and add the message[i] , but surprisingly message[i] becomes an int when added. Serial.println outputs the string correctly, but the string that I get from message[i] is just numbers...

#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
String sensorname;
void setup(){
  Serial.begin(9600);
  Serial.println("Device is ready");
  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  }
void loop(){

  if (vw_get_message(message, &messageLength)){
    Serial.print("Received: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      sensorname += message[i];
      }
      Serial.println();
      Serial.pintln("Name of sensor: " + sensorname);
      sensorname="";  //Reestart the string
      }
}

I'm quite new with VirtualWire so I don't know if there is command to get the message and pass it directly to string...Any help will be appreciated!

EDIT
I think I dind't express myself well. In my original question I didn't add the String sensor name

The Response I get in the Serial is the following:

Device is ready
SensorA
Name of sensor: 8310111011511111465

My aim is to instead of having as sensorname=8310111011511111465, have sensorname=SensorA

Those numbers are the numerical ASCII representation of the characters.

83 = S
101 = e
110 = n
... etc ...

(Find the whole list here: http://www.asciitable.com/)

The reason you are ending up with numbers is because of the type of variable you are receiving the data into - a byte.

A byte stores a number between 0 and 255.  When you add that byte to a String the compiler assumes you want to append a number, since it is a numerical type that you are using.

If you instead tell it to use a char type then the compiler should realise "Ah, this is the numeric representation of a character - I will add the character instead".

You can either change the whole array type:

char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages

Or cast the variable to be the right type when you append it:

  sensorname += (char)message[i];

Or better still, don't use the String class since it is really too heavyweight and prone to memory issues for use on a little microcontroller.  Stick to C strings. They take a little more getting used to, but are so much more microcontroller friendly.


Converting from Float to Int yielding weird results. What am I doing wrong? So I am trying to take GPS data with a Neo 6M gpsmodule (that is what is covered up by the square for privacy sake) and process it by adding/multiplying to get large integers representing the GPS data. This is using Arduino nano. When I try and convert the float numbers to integers, it gives me totally different numbers. 1242895 turns into -2289, and 611194 turns into 21370. I have tried so many things, but am stumped as to what is going on. Is it related to pointing? It's been awhile since I learned about pointers in my C++ class. X and Y are initialized as int global variables.

On an Arduino board with the 328 processor, an INT is stored as a 2 byte value, so the max number is 32,767.
You want to use a LONG which is a 4 byte number which has a max of 2,147,483,647.
When the variable you are using is not big enough, the number rolls over, which is why you end up getting a negative number.


How to make an Arduino USB programming circuit? I am designing a PCB in which I am using the MCU used in Arduino UNO which is Atmega328P and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using USB B Type just like we do it in Arduino UNO. My friend suggests me to purchase an Arduino UNO device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the schematic design but its very confusing. Can anyone help me out with this.?

Looking at the schematic design, you need atmega8 to make a usb programming connection. Design your circuit exactly like in the schematic.You will also need bootloader for it, so use any programmer like usbasp, connect its pins to mosi, miso sck, rst,vcc,gnd and click on burn boot loader in arduino ide


(Neopixels) How to keep the pixels of the same colour despite increasing brightness? I've been doing a fade function for the NeoPixels. However, the moment I have maximum brightness for the pixels, I noticed there 2 colours even though in my function I have only specified one colour.

Some strips are one colour and the others are another colour. I
specified the colour to be blue for the strips however many strips are blue and the strips nearer the end are green (but closer to a blue-green colour).

Is there any way to keep the colour even when the brightness changes? I've read somewhere online a different colour is seen with different brightness levels i.e. setPixelColor(brightness, r,g,b).

I've also tried FastLED library and followed documentation. However, the lights are not doing what it has said in the codes, I've tried leds[i].fadeLightBy(200) and it has given me no result.

My code for the fade function (edited from http://moving-rainbow.readthedocs.io/en/latest/guide/fade-in-and-out/):

void fade(uint32_t color) {
  for (int i = 0; i < 255; i++) {
    for (int q = 0; q < strip.numPixels(); q++) {
      strip.setPixelColor(q, Wheel((color) & 255));
    }
    strip.setBrightness(i);
    strip.show();
  }

  //decreasing brightness
  for (int l = 255; l > 255; l--) {
    for (int p = 0; p < strip.numPixels(); p++) {
      strip.setPixelColor(p, Wheel((color) & 255));
    }
    strip.setBrightness(l);
    strip.show();
  }
}

The method "Wheel" is from the Arduino Neopixel strandtest example.

uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if (WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if (WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

Any advice on how I should go about doing it?

I have some simple NeoPixel fading going on in this example sketch:

/*
 *
 * NeoPixels demo - fades colours (in array) up and down
 *
 */

#include <SPI.h>
#include <NeoPixels_SPI.h>

const unsigned int PIXELS = 8; // Number of pixels in the string

void setup()
  {
  ledsetup();
  } // end of setup

float patterns [] [3] = {
  { 1, 0, 0 },  // red
  { 0, 1, 0 },  // green
  { 0, 0, 1 },  // blue
  { 1, 1, 0 },  // yellow
  { 1, 0, 1 },  // magenta
  { 0, 1, 1 },  // cyan
  { 1, 1, 1 },  // white
  { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
  { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

};

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

void loop()
  {

  for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
    {
    // fade up
    for (byte m = 0; m < 100; m++)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for

    // fade down
    for (byte m = 100; m > 0; m--)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for
    } // end of for each array item

  } // end of loop

This is using the simple NeoPixel library that I wrote using the SPI hardware. The library with the exact code above is available here.

Basically the fading is done by multiplying the floating-point values for the R/G/B values by a constant from 0 to 100 (you could make it 0 to 255).

Since the colours themselves are expressed in the range 0 .. 1 then the result of the multiplication would be 0 to 255. To my naked eye the colours seem true at all brightnesses.

To use the library on your Uno just connect +5V, Gnd, and the data pin is MOSI (D11 on the Uno).


Arduino program using i2c stops working after printing to OLED a few times A NOTE ON THE PROJECT AND PROGRAM STRUCTURE

I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.

So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.

The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.

WHAT I AM TRYING TO DO ?

Read RTC into State class's static variables
Display once
Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
set to 1 minute) Service interrupt in loop by:

Read RTC into State class's static variables
Reset alarm for RTC
Update display

WHAT IS THE PROBLEM ?

The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.

WHAT HAVE I TRIED TO SOLVE IT ?

With Serial.println() in many areas such as before and after OLED::writeString is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.

Removing OLED::writeString statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.

This is wrong in many ways:

String input = Serial.readString();
serialInputBuffer = new char[input.length()];
input.toCharArray(serialInputBuffer, input.length());

What's fatal is that you later don't free the memory allocated with new. Don't use String and new. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a delete, but they still cause the fragmentation problem.

Use a global buffer like char serialInputBuffer[64]; and use:

int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
serialInputBuffer[l] = 0;

In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.

Again, dynamic allocations will cause fragmentation even if the memory is released properly.


How to exit out of a timer interrupt (ISR(TIMER1_COMPA_vect)) I have a code here where I collect an array of data and do some data analysis with the data. The only thing I'm struggle with is how to exit the ISR after I am done running my code. I am using a pre-scalar of 256 and running the ISR once (1Hz)
const signed int numReadings = 21;
volatile int gauge0[numReadings];
volatile int gauge1[numReadings];
volatile int add[numReadings];
volatile int deltaGAUGE;
volatile int slopeADD;
volatile int mean;

const int A0_pin = PC0;
const int A1_pin = PC1;

const uint16_t t1_load = 0;
const uint16_t t1_comp = 62500;

void setup() {

  //Set A0 and A1 pins as inputs
  DDRC &= ~(1 << A0_pin);
  DDRC &= ~(1 << A1_pin);

  //Reset Timer1 Control Reg A
  TCCR1A = 0;

  //Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  //Set to prescaler of 1024
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  //Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  //Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  //Enable global interrupt
  sei();

       Serial.begin(9600);
       Serial.println(" ");
       Serial.println("START");
        Serial.println(" ");

}

ISR(TIMER1_COMPA_vect){

       Serial.println(" ");
        for (unsigned int i=0; i<numReadings; i++)
            {
                        gauge0[i] = (analogRead(A0_pin))*(100.00/1024.0);
                        gauge1[i] = (analogRead(A1_pin))*(100.00/1024.0);
                        add[i] = ((gauge0[i]+gauge1[i]));

                        deltaGAUGE = abs(add[20] - add[0]);
                        slopeADD = abs((add[20]-add[0])/(20-0));
                        mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+

                     add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;

                        if(i == 20)
                {
                      Serial.print("This of the delta AVG reading: ");
                      Serial.println(deltaGAUGE);
                      Serial.println(" ");
                      Serial.print("This of the slope reading: ");
                      Serial.println(slopeADD);
                      Serial.println(" ");
                      Serial.print("This of the mean reading: ");
                      Serial.println(mean);
                      Serial.println(" ");
                      Serial.println("END");
              }

                        delay(50); //wait .05 sec

          }

}

void loop()
{

}

When I run the circuit, the interrupt keep executing every seconds for an infinite amount of time, while I just want it to run once and exit.
I have tried the exit(0) command but I get an output that looks like this
START

This of the delta AVG reading: 0

This of t

As you can see, The program does not execute completely. Anyone have any idea how I can fix this, or anyhow I can better my code? thank you.

As some of the comments have suggested, I would either get rid of the ISR or reduce the size significantly. When using ISRs, it is recommended that you keep the code as small as possible. Use it to set variables, for example
//these two variables are global
ISR(TIMER1_COMPA_vect){
    someValue = true;
    numberOfValues++;
}

you should also never use any Serial functions inside an ISR as these use interrupts themselves which can cause all kinds of problems
After using the ISR to update global variables, you can then use if() or while() statements within the loop() function to execute your serial print functions and such
P.S. on a side note, I would recommend changing your code where you calculated mean from
    mean = (add[1]+add[2]+add[3]+add[4]+add[5]+add[6]+add[7]+add[8]+add[9]+add[10]+
add[11]+add[12]+add[13]+add[14]+add[15]+add[16]+add[17]+add[18]+add[19]+add[20])/20;

to
for(uint8_t i = 1;i<=20;i++){
    mean += add[i];
}
mean /= 20;


Building Custom Bootloaders Recently I was checking out the Atmel's AVR series and I found the Atmega328PB. I am really familiar with Arduino's environment. So I thought if somehow we could bootloader it with Arduino bootloader. My doubt is how can I make a Arduino bootloader for it.

Here are a couple sources of ATmega328PB bootloaders based on optiboot:

https://github.com/watterott/ATmega328PB-Testing
https://github.com/ElektorLabs/Arduino

I haven't used either.
If you are set on making your own at least they can provide you with a reference.


Arduino IDE compiles, UECIDE not I'm rewriting a personal project and it doesn't compile under UECIDE 0.9.1, but it does with Arduino IDE 1.8.5.

Target is NodeMCU 0.9 with default options.

Arduino IDE 1.8.5

Archiving built core (caching) in: /tmp/arduino_cache_347503/core/core_esp8266_esp8266_nodemcu_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_4a642491bde0820b9be0f8ad42686d29.a
Sketch uses 299199 bytes (28%) of program storage space. Maximum is 1044464 bytes.
Global variables use 37372 bytes (45%) of dynamic memory, leaving 44548 bytes for local variables. Maximum is 81920 bytes.

UECIDE 0.9.1

• Error at line 231 in file Monitor.ino:
‣ expected '{' before ';' token

• Error at line 231 in file Monitor.ino:
‣ expected ')' before ';' token

• Error at line 190 in file Monitor.ino:
‣ redefinition of 'CronEntry cronBlink'

• Error at line 231 in file Monitor.ino:
‣ 'CronEntry cronBlink' previously declared here

Project is too large to post here, so I zipped it and uploaded to Google Drive, where anyone can download it with this link

https://drive.google.com/file/d/1BGvqtPx0547fPfX1Nucwhd_a-MO__vWX/view?usp=sharing

EDIT
(After lambda comment by Majenko)

I was using a struct to hold cron entries, using lambdas:

struct CRON_ENTRY {
  boolean active;       // Task is active.
  unsigned long start;  // Start time (ms uptime).
  unsigned long repeat; // Repeat every (ms).
  fcncron fcn;          // task.
};

CRON_ENTRY cronBlink = {false, 0,   500, [](CRON_ENTRY * c)
{
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();
}

and then replace CRON_ENTRY struct with CronEntry class:

CronEntry cronBlink(false, 0,   500, []() {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    display.countdownPanel();});

I really like lambas because they made code shorter.

This is a bug in UECIDE. It doesn't like lambda functions in constructors.

A complete rewrite of the sketch parser to use Exuberant Ctags is under way.


Endless loop on boot after reflashing ESP-12E with AT firmware I flashed the ESP-12E from AT firmware 2.0 (running ok) to NodeMCU (running ok). When I reflashed it back to the AT 2.0 it is stuck in endless loop on boot:

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2408, room 16
tail 8
chksum 0xe5
load 0x3ffe8000, len 776, room 0
tail 8
chksum 0x84
load 0x3ffe8310, len 632, room 0
tail 8
chksum 0xd8
csum 0xd8

2nd boot version : 1.6
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
no GPIO select!
jump to run user1 @ 1000

rf_cal[0] !=0x05,is 0xFF

I am sure I flashed it correctly, it was not my first flashing of AT firmware. Just to be sure:

esp_init_data_default.bin -> 0x3fc000
blank.bin -> 0x3fe000
boot_v1.6.bin -> 0x0000
user1.1024.new.2.bin -> 0x1000
blank.bin -> 0x7e000

I can even reflash it to the NodeMCU firmware and it works, but reflashing to the AT firmware ends in the same endless loop again.

I suspect the problem is in initialization data, but I'm at my wit's end with it.

Full answer and writeup to the comments:

The error message is due to the bootloader trying to read the contents of its radio-frontend calibration data (hence the name rf_cal). It compares it with a magic number, 0x05, but fails because it reads 0xFF at that point. 0xff is an indication that you read data from flash which was erased. After erasing a flash-sector, the data in it becomes 0xff 0xff 0xff... Hence it seems as if the bootloader is trying to access the data from the wrong address, thus only reading erased flash data. The RF-calibration data is stored in the file esp_init_data_default.bin and must be flashed to the correct address in order for the bootloader to be able to read it.

The NodeMCU documentation  tells us the needed address for esp_init_data_default.bin given the size of the flash of our ESP module:

The bootloader messages

2nd boot version : 1.6
SPI Speed      : 40MHz
SPI Mode       : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)

indicate that the flashed firmware (or that what is overriden by esptool.py) uses the 8 MBit flash size. There should be two ways to fix this:

Put esp_init_data_default.bin to the address the 8Mbit (1 MByte) bootloader expects, which is 0xfc000
Force the usage of the 32 MBit (4 MByte) Flash map by giving esptool.py the parameter --flash_size 32m. This makes esptool.py overwrite a few bytes in the firmware (at 0x000000) to adapt the firmware.

By your comments, method one worked. If there are problems however with the flash or the firmware, consider also trying method 2.


Arduino PRO Mini - The pads [was "jumpers"] on the back and Low Power Consumption I've noticed that on the back of an Arduino PRO mini are two Jumpers next to the A4 and A5 pins, marked with red in the following :

Looking at the leads one seems to be a bypass for the POWER Led and the other a bypass for the regulator, but not sure.

Further, the schematic reveals just one Jumper SJ1 :

https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf

So, my questions are :

Why are there two physical Jumpers on the board ?
Are these two jumpers actually just one : SJ1 ?
And if so how to connect them in order to enable Power isolation ?

Both responses are correct but be mindful that this is a SparkFun feature.  An Arduino Pro Mini from China won't necessarily have the SJ1 pad.

1) Like Gerben said, the pads on the underside of the board are for I2C pull-up resistors.

2) Like David said, SJ1 is on the top of the board next to the GND and RST pins.  (It looks like a small solder blob.)

3) To isolate the regulator from VCC, remove the solder blob on the top of the board with a sucker or solder wick.

The Sparkfun schematic shows all of these elements:
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/Arduino-Pro-Mini-v14.pdf


Arduino Uno + 12 relays I'm using a basic relay and I want to use 12 like this. Each one needs 50 milliamps, but the Arduino can supply only 300 milliamps. What can I do?

You should never drive relays direct from an Arduino.  You always need a driver circuit since each OP pin can only reliably provide up to 25mA.

Every relay needs (at least) an NPN transistor and a flyback diode.  Follow the myriad of examples for controlling one relay on an Arduino and multiply it by 12.

You might like to make things smaller and more manageable by using a paur of ULN2303 chips with 6 darlington drivers in each instead of using 12 discrete transistors.


Serial communication PC to Arduino using C and send via NRF I'm trying to communicate my PC with an Arduino Mega via serial and after send the message via NRF to another Arduino.

But I don't know if the message is send correctly or if it even send the message. Because I can't debug using Serial Monitor. If it is opened the serial port appear as busy.

When I execute the code the TX led on the Arduino blinks, but nothing is send via NRF.

I made some tests using only the NRF between the Arduinos and it's working, but when I try using the PC - Arduino serial communication, nothing happens.

C Code

#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};
  int error = 10;
  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  if(!usb_port) {
    perror(arduinoPort);
    return 1;
  }

  //memcpy(buffer, &error, sizeof(error));
  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

Arduino Code

#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(7, 8); // CE, CSN

uint64_t address = 0xF0F0F0F0E1LL;

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

  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  radio.printDetails();

}

void loop() {

  if(Serial.available() > 0) {

    char byteLido = Serial.read();

    radio.write(&byteLido, sizeof(byteLido));
    delay(1000);
  }
}

Working with serial in C on Linux is not as simple as opening a file and reading from it (though in some circumstances that can work).

You should open the file using open() not fopen(), then use tcgetattr() and tcsetattr() etc to configure the port.

For example:

#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>

struct termios oldsettings, newsettings;
int fd;

// This signal handler will close the port cleanly leaving
// it in the same state it started in
void sighandler(int sig) {
    if (sig == SIGINT) {
        if (fd >= 0) {
            // Restore the settings to original
            tcsetattr(fd, TCSANOW, &oldsettings);

            // Close the port
            close(fd);

            printf("Program teminated. Thank you for playing.\n");
            // Exit the program
            exit(0);
        }
    }
}

int main(int argc, char *argv) {

    // Trap CTRL-C to close the port properly
    signal(SIGINT, &sighandler);

    fd = open("/dev/ttyACM0", O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "Error opening serial port: %s\n", strerror(errno));
        return 10;
    }

    // Save the settings
    tcgetattr(fd, &oldsettings);
    // Grab the current settings again to modify
    tcgetattr(fd, &newsettings);

    // Set the baud rate
    cfsetispeed(&newsettings, B9600);
    cfsetospeed(&newsettings, B9600);

    // Make it a raw port
    cfmakeraw(&newsettings);

    // Apply the settings
    tcsetattr(fd, TCSANOW, &newsettings);

    char c;
    printf("Press CTRL-C to terminate\n");

    while (read(fd, &c, 1) == 1) {
        printf("Got character 0x%02x\n", c);
    }

    fprintf(stderr, "Reception terminated: %s\n", strerror(errno));

    return 0;
}

No one ever said programming C was easy. It makes you appreciate just how much work the Arduino API does behind the scenes for you...

Also you need to be aware that the Arduino resets (if you use an Uno, Mega, or other board with a separate USB interface chip) when you open the serial port. You need to wait about 2 seconds after opening the port before you ever send anything, or whatever you send will be completely ignored.  You can do that with:

sleep(2);

after you have opened and configured the port.


Removing Element From Array While Keeping Order I'm building a wireless mechanical keyboard. There is an array of 6 elements that stores the keys pressed by the user (since 6 is the max number of keys you can send at once over Bluetooth). An example would be 02-05-03-00-00-00. Notice the "00" at the end, these are just "placeholders" and don't have a meaning other than to indicate that there are no more keys pressed. When the user releases key 05 for example, the array should become this 02-03-00-00-00-00. I don't know how to do this however, since you can't just remove and item from an array and there doesn't seem to be a polished option for lists in Arduino.

Does anyone have any idea for an algorithm that finds the 0's in an array, places them at the end of the array and keeps the order of the other elements?

You need to compact the vector: First search for the first non-zero element and then move all non-zero elements. It could look something like below:

void setup()
{
  Serial.begin(57600);
  while (!Serial);

  char vec[] = { 2, 5, 3, 0, 0, 1 };
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));

  vec[1] = 0;
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));
}

void loop()
{
}

void compact(char* vec, size_t len)
{
  int i = 0;
  for (; i < len && vec[i] != 0; i++);
  if (i == len) return;
  int j = i;
  for (; i < len; i++) {
    char c = vec[i];
    if (c != 0) {
      vec[j++] = c;
      vec[i] = 0;
    }
  }
}

void print(char* vec, size_t len)
{
  for (int i = 0; i < len; i++) {
    unsigned c = vec[i];
    if (c < 16) Serial.print(0);
    Serial.print(c, HEX);
    if (i + 1 < len) Serial.print('-');
  }
  Serial.println();
}

This give the following output:

02-05-03-00-00-01
02-05-03-01-00-00
02-00-03-01-00-00
02-03-01-00-00-00

Cheers!


Pause in the program for some time I have a variable timeInSec which records the time as loop begins. It is defined as timeInSec = millis();. I have two conditions. If (timeInSec - lastRun)< 5 (that is 5 sec) , the first condition is executed(the if statement).Otherwise if (timeInSec - lastRun)>5 the second condition is executed(else statement). Here is the code:

void loop(){
  timeInSec = millis();  // Records time in seconds
  // if(lastRun > 0) {   // if i run this, only else statement is executed
  // delay(10000);
  // }
  if((timeInSec - lastRun) < 5000){  // Treshold time (if condition which runs when timeInSec is less than 5 seconds)
    // Some code
  }
  else{ // If treshold time exceeds (executes when timeInSec is > 5seconds)
   delay(10000);  // if i run this, only else statement is executed
   lastRun = timeInSec;
  }
}

Here the else statement executes once and control goes back if statement again. I want to pause the control at else statement for 10 seconds and then go back to if statement for further execution. Everytime  the control should pause at else statement for 10 seconds. I have used delay in the else statement and in this case only else statement is being executed. The same happens if I use delay at the start of loop (as in code). I have tried without using delay but didn't succeed.

Thanks for the help!

Do not try to change millis(). Instead, record the last time the
second code (else statement) ran, and check whether that was more than
five seconds ago:

void loop() {
    static uint32_t lastRun;
    uint32_t now = millis();
    if (now - lastRun < 5000) {
        // Some code
    }
    else {
        // Some code
        lastRun = now;  // record the time
    }
}

This is essentially the same technique used in the Blink without
delay Arduino
tutorial.


Getting a fixed sampling rate Ultimately I will move to a generic smart phone for this project.
I'm trying to read 4 analog inputs from my arduino with a fixed 1kHz sampling frequency. I managed to set it to read at 1kHz as you can see from this link. The issue is that after running several times, I kept testing the frequency by logging the time vector (produced by arduino to the serial terminal) into Excel and calculating the frequency using the equation:
f=1/(t2-t1)

I did this to the entire column and I noticed that I got a changing frequency. The difference is very big as it ranges from 780 to 1kHz. I need a fixed sampling rate because we will be applying some digital signal processing on the obtained results which obviously requires a sampling frequency. My code to send the data is the following:

#define INTERVAL_LENGTH_US 1000UL

unsigned long previousMicros;
#define FASTADC 1
int recValue;
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
double t = 0;

void setup() {
  int start ;
  int i ;

#if FASTADC
  // set prescale to 16
  sbi(ADCSRA, ADPS2) ;
  cbi(ADCSRA, ADPS1) ;
  cbi(ADCSRA, ADPS0) ;
#endif

  Serial.begin(115200) ;
}

void loop()
{
  unsigned long currentMicros = micros();

  if ((currentMicros - previousMicros) >= INTERVAL_LENGTH_US)
  {
    previousMicros += INTERVAL_LENGTH_US;

    int val_a0 = analogRead(A0);
    int val_a1 = analogRead(A1);
    int val_a2 = analogRead(A2);
    int val_a3 = analogRead(A3);

    Serial.print(((double)currentMicros) / 1000000UL, 5 ); // 1 is the number of decimals to print
    Serial.print('\t');

    Serial.print(val_a0);
    Serial.print(',');

    Serial.print(val_a1);
    Serial.print(',');

    Serial.print(val_a2);
    Serial.print(',');

    Serial.println(val_a3);

  }
}

Ps. I'm using Arduino Leonardo,
What's the right way to achieve this?

EDIT: Thank you all for responding, As you wanted to see my data, here is a screenshot of the results after I applied Jwpat7's suggestion:

The yello shaded column is the frequency calculated, the first and 2nd columns represent T1 and T1 (T2 is just T1 shifted upward for easier calculation). You may notice the Matlab section, this is because I'm trying to plot the data in Matlab and use it to do the digital signal processing after transmission. The plotting will be real time (I'll the data in txt files for later processing). the bottom potion of the figure shows the frequency after a while....as you can see it's decreasing!

Thanks

Expanding on my previous comments...

The only reliable way to get jitter-free ADC readings is to trigger the
ADC from a timer event. I wrote the following program to demonstrate the
approach on an Arduino Uno, as I don't have a Leonardo. The program
configures the Timer 1 to set it's overflow flag every 250 µs, and
the ADC to start a conversion on every rising edge of that flag. When
the conversion is done (104 µs after it started), the ADC ISR
fires. It's job is to retrieve the conversion result and set the analog
multiplexer for the next channel, switching round-robin through channels
0 – 3.

volatile int adc_readings[4];
volatile bool fresh_readings;

// Used only to clear the interrupt flag.
EMPTY_INTERRUPT(TIMER1_OVF_vect);

ISR(ADC_vect)
{
    static int buffered_readings[3];
    static uint8_t channel;

    if (channel == 3) {

        // "Export" the 4 readings at once.
        adc_readings[0] = buffered_readings[0];
        adc_readings[1] = buffered_readings[1];
        adc_readings[2] = buffered_readings[2];
        adc_readings[3] = ADC;
        fresh_readings = true;
    } else {

        // Buffer the current reading.
        buffered_readings[channel] = ADC;
    }

    // Move to next channel.
    channel = (channel + 1) % 4;
    ADMUX = _BV(REFS0)  // reference = Vcc
          | channel;
}

void setup()
{
    Serial.begin(115200);
    Serial.write("================");

    // Configure the ADC.
    ADMUX  = _BV(REFS0)   // reference = Vcc
           | 0;           // channel = ADC0
    ADCSRA = _BV(ADEN)    // enable
           | _BV(ADSC)    // start first conversion
           | _BV(ADPS0)   // prescaler = 128
           | _BV(ADPS1)   // ...ditto
           | _BV(ADPS2);  // ...ditto
    ADCSRB = _BV(ADTS1)   // trigger source = Timer 1 overflow
           | _BV(ADTS2);  // ...ditto

    // Wait for and discard the first conversion.
    loop_until_bit_is_set(ADCSRA, ADIF);

    // Configure Timer 1 to overflow every 250 us.
    TCCR1A = _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ...ditto
           | _BV(WGM13)   // ...ditto
           | _BV(CS11);   // clock at F_CPU/8
    TIMSK1 = _BV(TOIE1);  // enable overflow interrupt
    ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles

    // Set the ADC to auto-trigger mode.
    ADCSRA |= _BV(ADATE)  // enable auto-trigger
            | _BV(ADIF)   // clear interrupt flag
            | _BV(ADIE);  // enable interrupt
}

void loop()
{
    if (fresh_readings) {
        Serial.write((uint8_t *) adc_readings, sizeof adc_readings);
        fresh_readings = false;
    }
}

A few comments:

The Timer 1 overflow interrupt is used only to clear the timer
interrupt flag. The flag has to be cleared because the ADC is
triggered only on it's rising edges. Alternatively, that flag could be
cleared inside the ADC ISR.
I choose to deliver the readings by batches of 4 (one reading per
channel), thus the buffering inside the ADC ISR. The choice is
arbitrary: you can, if you wish, transmit the readings as they come,
as suggested in jwpat's answer.
The very first ADC reading is manually started and discarded. The only
reason for this is that it takes longer (200 µs instead of 104).
The readings are transmitted in binary form at 115.2 kb/s. The
effective data rate is 80 kb/s. ASCII would not be possible at
this sampling rate.
The loop() function must never take more than 1 ms to execute,
otherwise there is a risk of it reading the adc_readings array while
the ADC ISR is updating it, which would lead to corrupt data.
Protecting the access to adc_readings inside a cli()/sei() pair
would not significantly ease the timing constraint, as a long loop()
execution would still carry the risk of loosing data points.

From a cursory look at the ATmega32u4
datasheet
it would seem it's Timer 1 is identical to the one of the ATmega328P
powering the Uno, save for an extra PWM channel. The ADC, however, is
slightly different, but similar enough to make porting fairly
straightforward. At least the setting of ADMUX would be different.


Adafruit Circuit Playground Express fails to upload When uploading code to the Adafruit Circuit Playground Express, I have found that most of the time it fails to upload saying that the port is busy. There seems to be no logical reason behind this, as it uploads perfectly to an Arduino Uno (Yes, I did switch the board types). What am I doing wrong?
Here is the error:

processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2075)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM1'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

Operating system: kubuntu linux 64 bit

EDIT: Never mind. In the end I used chmod a-x /usr/sbin/ModemManager to remove execute permissions from every user, and that worked without any noticeable repercussions to my system. For anyone who wants to do the same, make note of the original permissions, so you can change it back if you have to.

The actual error part of that stack trace is:

Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Port busy.

You have something else using /dev/ttyACM1.  If you don't yourself have something open, such as a serial terminal or the Arduino serial monitor, then the most likely culpret is modemmanager.

https://majenko.co.uk/blog/diagnosing-arduino-problems-linux


Why is observed clock rate < 3MHz on Arduino Uno? I wrote a simple loop to test the processor speed on my Arduino Uno. The numbers I'm getting are much worse than the 16MHz advertised, by a factor of ~5. Trying to figure out what I'm missing.

long counter = 0;
int sum = 0;
uint32_t t = 0;

void setup() {
  Serial.begin(9600);
  t = micros();
}

void loop() {
  sum += counter;

  if (counter == 10000) {
    float usecsPerIteration = (micros() - t) / (counter * 1.0);
    Serial.print(usecsPerIteration);
    Serial.println(" microseconds per iteration");

    // Print result to avoid loop getting optimized away
    Serial.println(sum);
  }

  ++counter;
}

The output is:

3.77 microseconds per iteration

Here's how I'm estimating clock rate from this. The body of the loop involves two additions and an equality check. Even if we assume that these simple operations take 10 clock cycles, the implied clock rate is still just (1 iter / 3.77 us) * (1e6 us / sec) * (10 cycles / iter) = 2.65 MHz.

What am I missing?

As Michael says there is a lot more going on than you think.

Firstly there are interrupts triggering which can slow things down (used to calculate milllis()).

Secondly you vastly under estimate the number of instructions that are being called.  For a start the loop is being called from a for(;;) loop in main():

    for (;;) {
        loop();
4   572:    0e 94 73 00     call    0xe6    ; 0xe6 <loop>
        if (serialEventRun) serialEventRun();
2   576:    20 97           sbiw    r28, 0x00   ; 0
2   578:    e1 f3           breq    .-8         ; 0x572 <main+0x10>
-   57a:    0e 94 1d 01     call    0x23a   ; 0x23a <_Z14serialEventRunv>
2   57e:    f9 cf           rjmp    .-14        ; 0x572 <main+0x10>
10 total

Then for the call to loop() the registers used get pushed to the stack, then your code executed, and the registers popped off again before returning.  This is the code for loop when disassembled:

000000e6 <loop>:
    // Save the registers to the stack
2   e6:     cf 92           push    r12
2   e8:     df 92           push    r13
2   ea:     ef 92           push    r14
2   ec:     ff 92           push    r15
8 total

    // Add to the sum
2   ee:     40 91 44 01     lds r20, 0x0144 ; 0x800144 <counter>
2   f2:     50 91 45 01     lds r21, 0x0145 ; 0x800145 <counter+0x1>
2   f6:     60 91 46 01     lds r22, 0x0146 ; 0x800146 <counter+0x2>
2   fa:     70 91 47 01     lds r23, 0x0147 ; 0x800147 <counter+0x3>
2   fe:     80 91 42 01     lds r24, 0x0142 ; 0x800142 <sum>
2   102:    90 91 43 01     lds r25, 0x0143 ; 0x800143 <sum+0x1>
1   106:    84 0f           add r24, r20
1   108:    95 1f           adc r25, r21
2   10a:    90 93 43 01     sts 0x0143, r25 ; 0x800143 <sum+0x1>
2   10e:    80 93 42 01     sts 0x0142, r24 ; 0x800142 <sum>
18 total

    // Check the value to see if it's time to print
1   112:    40 31           cpi r20, 0x10   ; 16
1   114:    57 42           sbci    r21, 0x27   ; 39
1   116:    61 05           cpc r22, r1
1   118:    71 05           cpc r23, r1
2   11a:    d1 f5           brne    .+116       ; 0x190 <loop+0xaa>
6 total

    // From here on is the "IF" section - skipped by the BRNE above
-   11c:    0e 94 f5 04     call    0x9ea   ; 0x9ea <micros>
-   120:    c0 90 3e 01     lds r12, 0x013E ; 0x80013e <__data_end>
-   124:    d0 90 3f 01     lds r13, 0x013F ; 0x80013f <__data_end+0x1>
-   128:    e0 90 40 01     lds r14, 0x0140 ; 0x800140 <__data_end+0x2>
-   12c:    f0 90 41 01     lds r15, 0x0141 ; 0x800141 <__data_end+0x3>
-   130:    6c 19           sub r22, r12
-   132:    7d 09           sbc r23, r13
-   134:    8e 09           sbc r24, r14
-   136:    9f 09           sbc r25, r15
-   138:    0e 94 68 06     call    0xcd0   ; 0xcd0 <__floatunsisf>
-   13c:    6b 01           movw    r12, r22
-   13e:    7c 01           movw    r14, r24
-   140:    60 91 44 01     lds r22, 0x0144 ; 0x800144 <counter>
-   144:    70 91 45 01     lds r23, 0x0145 ; 0x800145 <counter+0x1>
-   148:    80 91 46 01     lds r24, 0x0146 ; 0x800146 <counter+0x2>
-   14c:    90 91 47 01     lds r25, 0x0147 ; 0x800147 <counter+0x3>
-   150:    0e 94 6a 06     call    0xcd4   ; 0xcd4 <__floatsisf>
-   154:    9b 01           movw    r18, r22
-   156:    ac 01           movw    r20, r24
-   158:    c7 01           movw    r24, r14
-   15a:    b6 01           movw    r22, r12
-   15c:    0e 94 c7 05     call    0xb8e   ; 0xb8e <__divsf3>
-   160:    ab 01           movw    r20, r22
-   162:    bc 01           movw    r22, r24
-   164:    22 e0           ldi r18, 0x02   ; 2
-   166:    30 e0           ldi r19, 0x00   ; 0
-   168:    88 e4           ldi r24, 0x48   ; 72
-   16a:    91 e0           ldi r25, 0x01   ; 1
-   16c:    0e 94 a9 04     call    0x952   ; 0x952 <_ZN5Print5printEdi>
-   170:    60 e0           ldi r22, 0x00   ; 0
-   172:    71 e0           ldi r23, 0x01   ; 1
-   174:    88 e4           ldi r24, 0x48   ; 72
-   176:    91 e0           ldi r25, 0x01   ; 1
-   178:    0e 94 0b 03     call    0x616   ; 0x616 <_ZN5Print7printlnEPKc>
-   17c:    60 91 42 01     lds r22, 0x0142 ; 0x800142 <sum>
-   180:    70 91 43 01     lds r23, 0x0143 ; 0x800143 <sum+0x1>
-   184:    4a e0           ldi r20, 0x0A   ; 10
-   186:    50 e0           ldi r21, 0x00   ; 0
-   188:    88 e4           ldi r24, 0x48   ; 72
-   18a:    91 e0           ldi r25, 0x01   ; 1
-   18c:    0e 94 b0 03     call    0x760   ; 0x760 <_ZN5Print7printlnEii>

 // All this is just counter++
2   190:    80 91 44 01     lds r24, 0x0144 ; 0x800144 <counter>
2   194:    90 91 45 01     lds r25, 0x0145 ; 0x800145 <counter+0x1>
2   198:    a0 91 46 01     lds r26, 0x0146 ; 0x800146 <counter+0x2>
2   19c:    b0 91 47 01     lds r27, 0x0147 ; 0x800147 <counter+0x3>
2   1a0:    01 96           adiw    r24, 0x01   ; 1
1   1a2:    a1 1d           adc r26, r1
1   1a4:    b1 1d           adc r27, r1
2   1a6:    80 93 44 01     sts 0x0144, r24 ; 0x800144 <counter>
2   1aa:    90 93 45 01     sts 0x0145, r25 ; 0x800145 <counter+0x1>
2   1ae:    a0 93 46 01     sts 0x0146, r26 ; 0x800146 <counter+0x2>
2   1b2:    b0 93 47 01     sts 0x0147, r27 ; 0x800147 <counter+0x3>
20 total

 // Get the registers back and return
2   1b6:    ff 90           pop r15
2   1b8:    ef 90           pop r14
2   1ba:    df 90           pop r13
2   1bc:    cf 90           pop r12
4   1be:    08 95           ret
12 total

That's more than 10 instructions.  I make it 74 clocks to run one full iteration. (counter++ alone is 20 clock cycles - double your estimation for the total...)

You have to remember two important things:

AVR is a RISC CPU - that means that seemingly simple operations can take multiple instructions to perform.
AVR is an 8-bit CPU - that means that working with any variables bigger than 8 bits in size require far more complex code, and you work with 32-bit variables (and floats, but that's outside the timing loop section of your code).


DS18B20 sending variable via Enthernet shield I am trying to send temperature read from DS18B20 to a web server. I know two things: to read a temperature, and to send something to web server. What I don't know is how to convert float that temperature reading function is giving to me to string that I need to send to the server.

I am reading temperature with OneWire and DallasTemperature libraries (just a standard sketch ending with:

sensors.requestTemperatures();
Serial.println(sensors.getTempCByIndex(0));//sensors.getTempCBy... returns float, from my understanding

I am sending data via ethernet shield, and important part is:

 client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + String(sensors.getTempCByIndex(0)) + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret=111 HTTP/1.1");

I know that the problem is that String(sensors.getTempCByIndex(0)) is not converting to right value. Arduino just stops working there, if that makes sense. At least serial communication stops working, since I don't see any more output...

Basically, TL:DR, I think that the question is how to convert float to string in Arduino? I have read a million topics on this but still cant figure it out, especially sicne it works for temp2 and humidity in example above.

Having re-read the question just before posting this answer, I find it odd that the DHT temp and humidity (also floats) work for you - how odd

Use dtostrf

char tStr[9] = { 0 }; // buffer to store the string - length 9, because at most you need 8 chars "-23.5678" , plus null terminator
dtostrf(sensors.getTempCByIndex(0), 7, 3, tStr)

Note: dtostrf returns char pointer to tStr

The 7, 3 is ... 7 = total length of string, 3 = number of decimal digits - So depending on your resolution, you can change those values

Resolution     Arguments to dtostrf
 9             5, 1                  -nn.n
10             6, 2                  -nn.nn
11             7, 3                  -nn.nnn
12             8, 4                  -nn.nnnn

Of course, you can use any arguments for any resolution, the table just shows what you would need if you wanted to show the exact data coming in

For example, I use resolution 12, but I'm not really interested in displaying more than tenths of a degree - so I use 5,1 for the format


I want to begin with arduino programming I want to start programming with the Arduino Uno, but I don't know where to start or what a good start is. I can program a bit in c#, but I red that you have to program in c++.

Any idea's where to start?

Thanks!

You can purchase some great starter kits too:

They're easy to search for, here's a few that popped up right away:

http://www.arduino.cc/en/Main/ArduinoStarterKit

http://www.amazon.com/Kuman-Project-Complete-Starter-breadboard/dp/B016D5KUHS/

And here's one that I own, and I've recommended to other people:

http://www.microcenter.com/product/458578/Arduino_Compatible_Maker_Kit_with_LCD_Display

If you have a microcenter or radio shack or Fry's in your area, they all stock a variety of different starter kits.


Set EEPROM from PC before program I have been working on an arduino program, which has gotten rather large. I am close to hitting the 32k limit on Flash for my ATmega328p. I would like lower my program size by saving some of my many string literals into EEPROM.

All of the example programs on the EEPROM page suggest loading them in at runtime, in which case they would take up flash memory anyways! What I am wondering, is if there is a way to write to EEPROM from my PC, THEN load the arduino program which will access those values. Do I need some external hardware to do this?

Thanks for your help!

-sam

The simplest way would be to have two sketches.

One that will store all the strings into EEPROM.

After that you can upload the second actual sketch that uses the values stored in EEPROM.

You only need to upload the first sketch if any of the strings change.

There is a way to upload a hex directly to the EEPROM using avrdude, but you'd have to use the commandline, and also have some way of generating this hex file containing all these strings.


5V power supply negative terminal connection I am currently developing some basic led board using Arduino Uno R3. Basically,
the LEDs are connected in parallel so that 5V DC supply can light up about 3 LED. Each LED has its resistor and its connected to 3 Arduino digital pin where I ground it by using digitalWrite(pins, LOW). Each ground on the schematic is the Arduino digitalWrite(LOW). My question is where should the negative of the 5V should be connected?

Also, if I wanted to measure the voltage of the LED, where should I connect my probe so that analogRead() can read the voltage?

Thanks and sorry if my explanation is not correct since it's my first time using this site.

simulate this circuit – Schematic created using CircuitLab

The Arduino common, normally referred to as ground, although it is usually only accidentally grounded through external connection. In general ALL connections should have a common "ground".

You can not measure voltage across the LED given the circuit you have listed. (You could read the voltage at both ends and subtract.)

If you swap the LED and resistor you can get an approximation of the LED voltage (actually LED + Arduino pin) from the junction of LED and resistor.


millis() not working properly I'm doing a little project that, on a press of a button, will light up three LEDs and then will turn off the LEDs in different times. I'm using the millis() function to control the time that each LED will be on.

On the first time that I press the button, everything works fine. But the problem starts when I press the button for the second time.

If I press the button soon after the loop ends, something goes wrong and the behavior of the LED become a mess (just one or two LEDs light up in weird times). But, if I wait about 2 seconds before pressing the button for the second time, everything goes right.

Here's my code:

const int ledPin1 =  11;
  const int ledPin2 =  12;
  const int ledPin3 =  13;
  const int buttonPin = 2;

  int buttonState = 0;
  long previousMillis1 = 0;
  long previousMillis2 = 0;
  long previousMillis3 = 0;

  int state = 0;

  void setup()
  {
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(buttonPin, INPUT);

    Serial.begin(9600);
  }

  void loop()
  {

       buttonState = digitalRead(buttonPin);

       if (buttonState == HIGH) {
        state = 1;
       }

       if (state == 1)
       {
        taskExecute(3000, 2000, 4000);
       }
  }

  void taskExecute(int tMotor1, int tMotor2, int tMotor3)
  {

    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;

    digitalWrite(ledPin1, ledState1);
    digitalWrite(ledPin2, ledState2);
    digitalWrite(ledPin3, ledState3);

    do
    {
      unsigned long currentMillis = millis();

      if(currentMillis - previousMillis1 > tMotor1)
      {
        previousMillis1 = currentMillis;

        if (ledState1 == HIGH)
          ledState1 = LOW;

        digitalWrite(ledPin1, ledState1);
      }

      if(currentMillis - previousMillis2 > tMotor2)
      {
        previousMillis2 = currentMillis;

        if (ledState2 == HIGH)
          ledState2 = LOW;

        digitalWrite(ledPin2, ledState2);
      }

      if(currentMillis - previousMillis3 > tMotor3)
      {
        previousMillis3 = currentMillis;

        if (ledState3 == HIGH)
          ledState3 = LOW;

        digitalWrite(ledPin3, ledState3);
      }
    } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
    state = 0;
  }

Other strange thing that happens is that sometimes the time that i've been set in millis for the led get on become a little different. Example: when I press the button, the LED 1 needs to light up for 3 seconds, but he lights up just 2.5 seconds.

What i'm doing wrong? Thanks!!

The variables previousMillis (1-3) are not properly initialised.  So if you wait a while before pressing the button, that delay time becomes part of the time that the LED is illuminated for.

If your taskExecute() function sets them before the loop, this will fix that:

void taskExecute(int tMotor1, int tMotor2, int tMotor3)
{
    int ledState1 = HIGH;
    int ledState2 = HIGH;
    int ledState3 = HIGH;

    digitalWrite(ledPin1, ledState1);
    digitalWrite(ledPin2, ledState2);
    digitalWrite(ledPin3, ledState3);

    unsigned long time_now = millis();
    previousMillis1 = time_now;
    previousMillis2 = time_now;
    previousMillis3 = time_now;

    do
    {
        ...
    } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
    state = 0;
}

On a coding-style note - I did not initially see the resetting of the global variable state=0 at the end of the taskExecute() function.  It might be better to move this up to underneath the initial call to taskExecute() so all the state handling is in one place.


Checking size in flash memory Esp32 I recently purchased an Esp32 and am doing some tests using Arduino IDE.
In one of the tests, I am recording a lot of .txt files with some text inside them in the flash memory, however, I would like to know how I can check the remaining space in the flash memory. I'm checking the flash memory space with Serial.println(ESP.getFlashChipSize());, however, the returned value is always the same.

Is this the right command to check? Why is it always with the same value?

Is this the right command to check? Why is it always with the same value?

The only way that size can change is if you desolder the can from the top of the ESP32 module, then desolder the flash chip, and replace it with one that has a different capacity.

The free space is not a function of the flash chip. It is a function of the filesystem you are using to store your data - be that SPIFFS or FAT.

You should check the manual for the filesystem you are using to find what functions there are pertaining to space usage.


Problems using an arduino with vex motors and motor controller 29 I am using a VEX 2-wire motor with the Motor Controller 29 to use it like a three-wire motor.

I was told that I am able to program it like a servo using the Arduino Servo class. When I use the write() function to set the power, it works from values around 50-85 in one direction, slowing down the power as I increase the value, but when the value exceeds around 90 then the motor stops working and makes strange clicking sounds. It is not a hardware problem, because the motor works fine in either direction when I plug it straight into a power source.

Does anyone know what my problem is?

VEX motors with Servo library have the following functionality:

0 one direction (full speed)

90 stop

180 opposite direction (full speed)

So at 90, it is trying to remain motionless and hence creating that sound.

btw. You should provide power to motors separately from the Arduino. You might fry your Arduino if you run VEX motors from it. Best solution is to power using 7.2V 3000mAh Flat NiMH High Power Battery Packs.


Why doesn't pin 3 blink? It blinks in another program I used toneMelody example code (sketch sample 02.Digital->toneMelody) on an Arduino UNO. Then I wanted to blink an LED with the melody.

Here's the code:

#include "pitches.h"
#define BLUE 3 // pin 3 does not blink. but, pin 9 ok.
#define GREEN 5
#define RED 6

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    analogWrite(RED, 0);
    analogWrite(GREEN, 0);
    analogWrite(BLUE, 0);
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    int color = melody[thisNote] % 5;
    if(color == 0) {
      analogWrite(RED, 200);
    } else if(color == 1) {
      analogWrite(GREEN, 200);
    } else {
      analogWrite(BLUE, 200);
    }
    delay(pauseBetweenNotes);
    noTone(8);
  }
  analogWrite(RED, 0);
  analogWrite(GREEN, 0);
  analogWrite(BLUE, 0);
}

void loop() {
  // no need to repeat the melody.
}

Unfortunately, pin 3 did not blink.
But it worked when I changed pin 3 to pin 9.

To check whether pin 3 or Blue LED is broken,
I checked with the following code.

#define BLUE 3

void setup() {
  analogWrite(BLUE, 0);
}

void loop() {
  for(int i = 0 ; i < 255 ; i ++) {
    analogWrite(BLUE, i);
    delay(10);
  }
  analogWrite(BLUE, 0);
}

This code worked. Blue LED blinked.
Why couldn't pin 3 blink with toneMelody?

Thanks.

In the tone function reference you can read:

  Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

analogWrite() is PWM


Is using malloc() and free() a really bad idea on Arduino? The use of malloc() and free() seems pretty rare in the Arduino world. It is used in pure AVR C much more often, but still with caution.

Is it a really bad idea to use malloc() and free() with Arduino?

My general rule for embedded systems is to only malloc() large buffers and only once, at the start of the program, e.g., in setup(). The trouble comes when you allocate and de-allocate memory. Over a long run session, memory becomes fragmented and eventually an allocation fails due to lack of a sufficiently large free area, even though the total free memory is more than adequate for the request.

(Historical perspective, skip if not interested): Depending on the loader implementation, the only advantage of run-time allocation vs. compile-time allocation (intialized globals) is the size of the hex file. When embedded systems were built with off the shelf computers having all volatile memory, the program was often uploaded to the embedded system from a network or an instrumentation computer and the upload time was sometimes an issue. Leaving out buffers full of zeros from the image could shorten the time considerably.)

If I need dynamic memory allocation in an embedded system, I generally malloc(), or preferably, statically allocate, a large pool and divide it into fixed-size buffers (or one pool each of small and large buffers, respectively) and do my own allocation/de-allocation from that pool. Then every request for any amount of memory up to the fixed buffer size is honored with one of those buffers. The calling function doesn't need to know whether it's larger than requested, and by avoiding splitting and re-combining blocks we solve fragmentation. Of course memory leaks can still occur if the program has allocate/de-allocate bugs.


Using Arduino Yún to send data through Ethernet I'm still new to Arduino Yún and I can't find any tutorials or examples on making the Yún send data through Ethernet, which will then be showed on a web server.

I've seen other tutorials but they use Uno with an Ethernet shield.  Is it the same with the Yún too?

How can I send data through Ethernet using Yún?

There are three bits of information you need to know:

The Ethernet port is connected to a tiny Linux computer
On Linux you can do HTTP POST and HTTP GET using a program called cURL
The AVR chip can tell the Linux computer what to do using the Process library.

Putting all those together: You need to use the Process library to tell Linux to run curl with the right parameters.

Just like the tutorials show you:

https://www.arduino.cc/en/Tutorial/Process


MIDI and DMX together I am fully new to Arduino (even don't have one ... yet), however, I'm looking into possibilities to use both MIDI in/out and DMX together. If I understand correctly the MIDI library (re)uses the UART/COM while the DMX does the same.

I am wondering if it can be used together (e.g. use MIDI in to control MIDI out and/or DMX out).

(Also still checking if I would need some simple MIDI/DMX components or 'full' MIDI or DMX shields/boards.)

Yes you can use multiple UART/Serial devices with a single Arduino.

However, there are some things to consider:

The Arduino Uno supports a single hardware serial connection (which is used for programming and debugging with the Serial Monitor). The Arduino Mega supports 4 hardware serial connections.

The arduino environment has a software Serial library that allows for additional Serial connections. However it is worth noting that software serial is slower than its hardware counterpart.

Also, if you want to use software serial, be sure to verify that any shields you want to use will support using a software serial connection.


How to use an Arduino Uno + Keyboard Firmware to make a "N Key Rollover" Game Pad Hello I have flashed my Arduino Uno with USB keyboard firmware from this tutorial http://mitchtech.net/arduino-usb-hid-keyboard/#comment-6786, and I have been successful sending individual key presses but, not when trying to press an hold a key. I am attempting to use this firmware to create a custom Game Pad to USB adapter, the only issue is sending simultaneous keystrokes (not sending them one at a time). If you know how to accomplish this task I would be very happy. The technical term for this is "Key Rollover"

You don't want to send random keys do you?

Well consider using the code below as your base.
It's using Port Manipulation to read the buttons (Digital 0 to 7).

void setup()
{
  Serial.begin(9600);//Start serial connection.
  DDRD = 0b00000000; //Set Data Direction Register of port D to inputs (attach keys to digital pins 0to7;
  delay(200); //Misc delay.
}

void loop()
{
  Serial.write(PIND, 8);    // Send states of PORTD (digital 0 to 7)
}

I strongly suggest you use pull-down/up resistors on the buttons also.
Adjust your code to the amount of keys you're using, or pull the pins low if not used. To avoid receiving random/floating pin values.


Understanding datasheet of a HCHO gas sensor I have a gas sensor whose datasheet is attached:
DS-HCHO

Now it says that UART communication is needed (P2P) where it (module) waits for Data Frame before tx the data frame to host which I need.

All i know is that I can send start bit in I2C but how shall I proceed.
Also if I have multiple sensors how shall I connect them to ESP-32?

First, you need to be communicating by UART, not I2C.  That means using Serial or some similar object (On ESP32 you can define your own on whatever pins you want).  However, the datasheet omits one vital piece of information: the baud rate it communicates at - so you will have to guess that and try various different standard baud rates until you find the one that works.

Then you have to send the "Give me the data" instruction.  The module then responds with the data.

For example (untested):

HardwareSerial mySerial(1);

#define PIN_RX 21
#define PIN_TX 22

void setup() {
    Serial.begin(115200);
    mySerial.begin(9600, SERIAL_8N1, PIN_RX, PIN_TX); // This is the one you need to guess since the DS omits it...
}

void setup() {

    // Once a second send the request to get the data

    static uint32_t ts = millis();
    if (millis() - ts > 1000) { // Once a second
        ts = millis();
        // "Give me the data"
        mySerial.print("\x42\x4d\x01\x00\x00\x00\x90");
    }

    // When 10 or more bytes have arrived then assume that they are correctly
    // framed and print them.  Really it should read one byte at a time and
    // look for the correct start sequence of 0x42 0x4d 0x08 and read only
    // from there, but this will server for demonstration purposes.

    if (mySerial.available() >= 10) { // We expect 10 bytes returned
        uint8_t packet[10];
        mySerial.readBytes(packet, 10);
        Serial.print("ID:   ");
        Serial.println(packet[3]);
        Serial.print("UNIT: ");
        Serial.println(packet[4]);
        Serial.print("VH:   ");
        Serial.println(packet[5]);
        Serial.print("DHH:  ");
        Serial.println(packet[6]);
        Serial.print("DLL:  ");
        Serial.println(packet[7]);
        Serial.print("LRCH: ");
        Serial.println(packet[8]);
        Serial.print("LRCL:   ");
        Serial.println(packet[9]);
    }
}


Arduino interrupt not called using PinChangeInterrupt I am new to Arduino and I was trying to figure out how to use an interrupt. When I ran this it would read my magnet but the interrupt would never be called and I couldn't figure out if anyone can help me that would be great.

Thanks.

Here is the code

#include <PinChangeInterrupt.h>

//#define INTERRUPT_PIN 12
#include <Math.h>

#define RADIUS 3
const int hallPin = 7; // the number of the hall effect sensor pin
const int ledPin =  13; // the number of the LED pin
// variables will change:
int hallState = 0; // variable for reading the hall sensor status
double inital_val = 0.0;
double distance = inital_val;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  pinMode(hallPin, INPUT);
  //attachInterrupt(hallPin, calc_distance, HIGH);
  // initialize the hall effect sensor pin as an input:
  attachInterrupt(digitalPinToInterrupt(hallPin), calc_distance , HIGH);
  Serial.begin(9600);
}

void loop() {
  //read the state of the hall effect sensor:
  hallState = digitalRead(hallPin);
  if (hallState == LOW) {
    // turn LED on:
    Serial.print("Main Loop: HallState LOW\n");
    digitalWrite(ledPin, HIGH);
    Serial.print(distance, 2);
    Serial.print("\n");
  } else {
    Serial.print("Main Loop: HallState HIGH\n");
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

void calc_distance() {
  Serial.print("INTERRUPT! \n");
  if (digitalRead(hallPin) == HIGH) {
    Serial.print("YES!\n");
    distance += PI * 2 * RADIUS;
  } else {
    Serial.print("NO!\n");
  }
}

The attachInterrupt function is only for normal interrupts. Read the reference: attachInterrupt

When you need the Pin Change Interrupts, there is a library for that: EnableInterrupt

Try to keep the interrupt routine as short as possible. Do not use the Serial functions in calc_distance because the Serial functions themself use also interrupts.

The Arduino Mega does not have 'double' floating point variables, the compiler changes it into 32-bit 'float' variables. You are reading the interrupt pin for a test ? I don't understand why you do that. Please make "distance" a volatile variable. In the loop function, the interrupts should be turned off when reading "distance". Because "distance" is a 4 bytes 'float' variable and the Arduino Mega is a 8-bits microcontroller. An interrupt could occur when the "distance" is only read for a part from memory.


Controlling multiple 24V solenoids with Arduino I'm building a pump for which I need 4 medium strength solenoids (20-50N). 24V is probably the minimum I will need to put through them, but this is something I need to test, once I've got them working. At 24V they draw 400mA.

I've found various posts with very useful info, especially https://playground.arduino.cc/Learning/SolenoidTutorial and https://forum.arduino.cc/index.php?topic=417030.0

Will the attached sketch below work for one? If so what resistance should R1 be?
And if so can you see any problems with hooking up 4 working at different intervals?

The power supply is an LRS-350-24RS, and the Mosfet has a max gate source voltage of 35V. The 5v-24v optocoupler is off ebay -  https://www.ebay.co.uk/itm/152904980799

Many thanks for your help!!

No, it won't:

The diode D1 is backwards.
The opto-coupler is wired completely wrong.

You don't actually need the opto-coupler as long as the threshold voltage of the MOSFET is low enough for the Arduino to switch.  However if you do want (or need) to use it you should wire it like this:

simulate this circuit – Schematic created using CircuitLab

R1 is a pull-down that keeps the MOSFET off when not being turned on (just like with a button). The value doesn't matter much.  R2 is a resistor just like you use for any LED with an Arduino.  D1 must be connected reverse biased or it will just short out your solenoid. The opto-coupler must be connected with the transistor the right way around or it will not work (or melt, or create a black hole...)

To ditch the opto-coupler you can just treat it like any other load on the Arduino (as long as the MOSFET's threshold voltage VGS is below 4V):

simulate this circuit


Trying to make a wattmeter I've been trying to make a wattmeter using arduino but cannot find the shield I need to buy to put onto my arduino to make it. There are no such parts in the Arduino Store and online the best I could find is this. This measures the arduino's energy consumption, however, not other things. I am really new at this and thoroughly lost. I would be really glad if someone could help me with this problem :)

You will need an Ampere meter and a Voltmeter. Watts is Volt * Ampere.

There are logic level compatible units out there for ampere meters ranging from a few mA to at least dozens of Amperes.

Also for voltmeters there are several logic level compatible units available, to plug in your project.

The rest is math. (Watts = A * V )


ir sender detecting receiver and display I am in a pickle and want to know if you can help me. I have an IR sensor and receiver and want a program that makes a light bulb flash or detect whenever the IR receiver is in range.
So whenever the IR sender detects the receiver, it should print "detect". This will be done using the Arduino program. And it is an Arduino Nano I am using.

These are the things I use:

http://www.dx.com/p/keyestudio-digital-ir-receiver-module-for-arduino-black-429206#.V5gcpzYko-U

http://www.dx.com/p/38khz-ir-infrared-transmitter-module-for-arduino-135040#.V5gcpjYko-U

How should this program look like? Anyone have the code for this?

Never mind the LED blinking, I just want the program to know whenever the receiver is detected and probably display it somehow. My plan is to send the number of times the transmitter detects the receiver to an Android app in the end.

You can't.

IR is a one-way protocol. The transmitter has no way of knowing whether a receiver is in range; it's literally just an LED that emits infrared instead of visible light.


In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor? I would like to know if there are always the latest features in Arduino Desktop IDE if I update it every day.

I mean if there is a new feature in Arduino Web Editor, can I get it on Arduino Desktop IDE?

You will always get the same API features in both, because the API is separate to both of them - it's a plugin that's developed separately.

Would you get the same GUI facilities? No idea. Maybe - maybe not. It depends how useful they would be. You may get features added to the GUI that don't appear on the web. Or you may get the other way around. If they are essential to the operation of the system, though, you will get them added to both.


Parent class callback from child class I want the Parent class to pass a pointer to a callback function to the child class when the child class is created. I got this working when the parent was the sketch thanks to this post:
In this example, the parent was the .ino file, i.e. not a class but a collection of functions. This code worked fine.
However, I need to be able to make the call to the child constructor from a within a class as shown in the code below. I get I get an "invalid use of non-static member function on the line child = new Child ( handlerDispatcher );

Here is the complete code:

class Child {
public:
    typedef void ( *callback_t ) ( uint8_t, uint8_t );

    callback_t callback;

    //  Constructor
    Child ( callback_t _callback ): callback ( _callback ) {}

    void doCallback ( uint8_t id, uint8_t index ) {
        callback ( id, index );
    }

    void makeCallbacks () {
        doCallback ( 1, 0 );
        doCallback ( 2, 1 );
        doCallback ( 3, 2 );
    }
};

class Parent {
public:
    Child *child;

    Parent () {}

    void handlerDispatcher ( uint8_t id, uint8_t index ) {
        ( this->*callbackHandlers [ index ] ) ( id );
    }

    typedef void ( Parent:: *handlerPointer ) ( uint8_t );
    handlerPointer callbackHandlers [ 3 ] = {
        &Parent::handler1,
        &Parent::handler2,
        &Parent::handler3,
    };

    void handler1 ( uint8_t index ) { echo ( index ); }
    void handler2 ( uint8_t index ) { echo ( index ); }
    void handler3 ( uint8_t index ) { echo ( index ); }
    void echo ( uint8_t value ) {
        Serial.print ( "Got: " );
        Serial.println ( value );
    }

    void configure () {
        child = new Child ( handlerDispatcher );

    }
    void test () {
        child->makeCallbacks ();
    }
};

Parent parent;
void setup () {
    Serial.begin ( 115200 );
    parent.configure ();
    parent.test ();
}

void loop() {}

Use virtual functions. On object of type Child, fnc2 defined in Parent will call fnc1 of class Child:

class Parent {
public:

  virtual void fnc1() {
  }

  void fnc2 {
    ...
    fnc1();
    ...
  }
}

class Child : public Parent {
public:
  virtual void fnc1() {
    ...
  }
}


Use Mac for memory & processing I understand that each model of Arduino has limited cpu, ram, etc.

However, I have this very powerful Mac that it’s hooked up to.

Am i able to use my Mac for expensive computation and just pass results to my arduino in real-time?

Basically arduino takes in sensor data - passes it to Mac. Mac computes and returns an output to arduino.

This blog describes the author's open-source, cross-platform library in C to talk to an Arduino via serial. The library is available on GitHub. A C project on your Mac can use it to communicate with your Arduino. You'll probably want to create a simple command protocol to keep the two in sync, as serial is pretty "barefoot" by itself, being just a stream of bytes with no markers, packets, or check-sums unless you impose such structures on your data, yourself. It probably doesn't need to be very complex, depending what your application needs.

I have found similar projects in Python and in Java for the Mac/Windows/Linux/<whatever> side; there's plenty of work already done for you.


I have four servos connected to an arduiono uno and I cannot control them I am making a simple bipedal robot. I have four 9g servos connected to my uno. Whenever I try to even do the simplest command, like move right foot 45 degrees it does not work properly. I have tried on my second Uno and i have the same result.

My program for testing the servos:

#include <Servo.h>

Servo myservo;

void setup(){
myservo.attach(6);
}

void loop(){
 myservo.write(45);
}

Each servo wire is attached to a breadboard where they all share power and ground from the arduino. Each servo wire then has another wire going to pins 3,5,6 and 9.

Does anyone know what the problem is and what I can do? Thanks

As others have said, the Arduino cannot drive 4 servos - my experience is that it can have problems powering one if you try to move it too often due to the voltage drop caused by the high current consumption.  When you move a servo the power consumption rises considerably.  A large (220uF or more) capacitor near he servo can help, but even so, by far the best option is to supply the servos from a separate supply.

If the Uno resets when you try to move the servos (especially multiple times per second) then the power supply is most likely your culprit.


Whats the best way to keep an Arduino in a waterproof junction box and prevent overheating? I am trying to make an automatic garden gate unlock that runs on a timer. I plan on running an arduino uno 24/7 with a software timer that activates a motor to release a bolt lock. I am going to fit all the electronics and extension cord into a waterproof junction box. Will this cause over heating? Is there a need for some kind of waterproof cooling system? Has anyone ever built outdoor electronics and ran into this problem?

The linear regulator on an Arduino works by converting excess voltage to heat. If you power it with 12V and draw a full amp from it it will turn (12-5)*1a or 7 watts of power to heat, and quickly overheat even if it's not in a box.
If you power it from 6.5V and only draw 300mA from it, it will turn (6.5-5)*.3, or a little under half-a-watt. While the Arduino is idling it will probably only draw 50mA, so less than 1/10th of a watt of heat.
For infrequent, short bursts of a few seconds you can probably get away with drawing 500mA of power without overheating.
Or skip the internal regulator and use a buck style voltage regulator. Those generate a LOT less heat.
Edit:
For a project I did recently, I used an external 5V regulated supply for everything. I cut a USB cable and soldered the red and black (+5V and ground) to the 5V supply, and plugged that into the Arudino's USB connector. That feeds 5V into the Arduino.


How do I convert a float into char*? Asked this question on Electrical Engineering Stack Exchange and was directed here:

Pretty self explanatory; how would I go about converting a float into a char*? I have code in which the float 'resistance' is constantly being updated. I would like to be able to update the variable 'result' to take the value of 'resistance'. Here is some of the code, in case it helps:

const char * result = "";
float resistance = 2.5;

result = resistance; //This bit (obviously) doesn't work

Thanks for your help!

There is a function in the standard Arduino library called dtostrf(). I think of it as "Decimal to String Float". You pass in the float, how wide you want the whole number to be (if it will fit), the number of decimals of precision - and the buffer you want it to fill.

Note that! You need to provide the buffer, and you need to be careful to provide more than enough! Don't forget to add 1, too (to store the NUL character at the end):

char result[8]; // Buffer big enough for 7-character float
dtostrf(resistance, 6, 2, result); // Leave room for too large numbers!

This will give result values like "  1.23" and " -1.23" and "123456789" (without the quotes). Note the last example - it won't truncate the number if it's too large, and that 10- character result (don't forget the final NUL) just overflowed your buffer...

Incidentally, if you specify a negative width, it won't right-justify the answer, it'll left-justify it (put any spaces on the end instead of the beginning).


What is the best way to get more RAM for a sound buffer? The problem:

How to extend the memory for a sound buffer (intensively used) if:

SD card library supports only one file open at a time (and I have one open already)
EEPROM chips are able to stand about 100,000 write cycles only (see the datasheets!)
I can't find anything else to buy! (a standard and durable RAM chip that loses its content when switched off would be the best).

About the 2nd point. Let's assume that the chip is 64KB and I want to use half of it for a circular sound buffer (it's small, I know). Let's also assume that a standard MP3 song is 160kbps and it's 3.5 min long. Given that, the EEPROM chip (with 100k write cycles limit) in this condirions will reach its limit after 3.2GB of played sound, which is about 762 songs, 44 hours. That can be reached in a single week! Replacing a chip every week is not an option. I'm not a fan of planned obsolescence...

Do you know any chip that will be right for the job? (and can be bought on eBay and it's affordable?)

Background:

I have built a WWW-controlled MP3 and online radio player (using ESP8266 and VS1003) and it's working really great, we're using it whole days, but ESP is not fast enough to handle WWW requests and play MP3 at the same time (especially from SD card), so the sound is paused for about 0.5 - 1 sec every time a www page is served (a really small page! Just basic HTML with a title and a list of file links!). SD card content cannot be cached for generating the pages on the fly (not enough heap memory) and two files cannot be opened at the same time by the SD library (one is open for the currently playing file - if not playing an online stream - and I'm currently closing it during reading and sending of requested html page). So I've got two memory problems: 1. serving the www pages and 2. buffering the online stream (usually not needed, most streams can play on my 4KB buffer without a glitch whole day but some of them are jamming very often - depends on the server). I'm thinking about both caching the pages (so I don't have to read them from SD and my music won't be interrupted) and creating a circular buffer (for live streams) in external memory chip. It does not need to keep the data after cutting the power. I've got about 24KB of heap left in my sketch (max) and it can fall even to about 6KB when a single folder's content is loaded to memory. It's not far away from heap overflow... I need to load at least the current folder (with long filenames).

A simple SPI SRAM chip. Available up to 128KB, such as the 23LC1024: http://www.microchip.com/wwwproducts/en/23LC1024


Arduino due + mcp2551 I am currently using an atmega328 along with the mcp 2515 and the 2551 for CAN communication in my systems.

However, I've now decided to upgrade to the arduino due for my operations. Can anybody tell me if the arduino due along with it's inbuilt CAN controller be used with the mcp2551 transciever to operate CAN successfully.

If not, can somebody also tell me if there are other alternatives I should look into. Thanks :)

The biggest trouble you are going to find is the voltage levels. The MCP2551 works at 5V and your MCU is 3.3V. I personally don't have experience with this MCUs, but some STM32 MCUs are 5V tolerant on some pins, including the CAN_TX and Can_RX and it's fine to use a 5V Transceiver like the MCP2551.

Anyway, you still can replace the CAN Transceiver with one that has a built in level shifter,  like one of the following:

MCP2562
ATA6561
SN65HVD256
NCV7351D13

I've used all the above, except the TI one, and they all talk nicely between each other. Some have different features, like silence or advanced sleeping modes.

Cheers


Value appears to change sign suddenly When slot == SLOT_1 is true, speed_value is positive but when slot == SLOT_2 is true, speed_value becomes negative.

I printed the value of speed_value immediately after the statement speed_value = -speed_value and it shows a positive number. How did speed_value changed sign when it enters the slot == SLOT_2 argument?

case ENCODER_BOARD:
  if(port == 0)
  {
    uint8_t slot = readBuffer(7);
    int16_t speed_value = readShort(8);
    speed_value = -speed_value;

    if(slot == SLOT_1)
    {
      Encoder_1.setTarPWM(speed_value);
    }
    else if(slot == SLOT_2)
    {
      Encoder_2.setTarPWM(speed_value);
    }
    else if(slot == SLOT_3)
    {
      Encoder_3.setTarPWM(speed_value);
    }
    else if(slot == SLOT_4)
    {
      Encoder_4.setTarPWM(speed_value);
    }
  }

int16_t readShort(int16_t idx)
{
  valShort.byteVal[0] = readBuffer(idx);
  valShort.byteVal[1] = readBuffer(idx+1);
  return valShort.shortVal;
}

uint8_t readBuffer(int16_t index)
{
  if(BluetoothSource == DATA_SERIAL)
  {
    return buffer[index];
  }
  else if(BluetoothSource == DATA_SERIAL2)
  {
    return bufferBt1[index];
  }
  else if(BluetoothSource == DATA_SERIAL3)
  {
    return bufferBt2[index];
  }
}

All the code are taken from here and I am not the owner. I myself still studying how these whole code works. I am hoping someone out there who have experience with these kind of implementations be able to help me out.

I think I understand what's going on from here. That's why speed_value appears to change sign suddenly when entering the if...else... statement. But why speed_value == -speed_value is necessary is yet to be answered.


Leonardo Serial1 enable internal pull-up for removable Bluetooth module I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.

My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins.

I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors.

I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?

Yes, what you have done is good.

It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs.  When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.

As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.

UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter.  By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.

The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART.  If that happens then you want to add an external stronger (lower resistance) pull up.

Another thing to think about with your disconnected pins is to protect them from ESD.  You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions.


ESP 8266 reverse digitalWrite behaviour on which pins? I am using a device with an ESP 8266 microcontroller. I have discovered that setting LED_BUILTIN to HIGH turns the built-in LED off and  setting LED_BUILTIN to LOW turns the built-in LED on. This seems to be because the microcontroller can sink more current than it can source.

Before I start using this microcontroller, I would like to know which other pins have this reverse behaviour. I've looked up datasheets for the ESP 8266 but I don't see how to discern this information. I would simply write a sketch to test, but I'm not sure what I might damage, and I'm not sure how to determine when an output pin is in the high-impedance state anyway.

On the ESP 8266, how to know which pins are HIGH -> 0v and which pins are HIGH -> 5v? Are the HIGH -> 0v pins necessarily LOW -> 5v? Where is this documented?

The esp8266 must have a pull-up on io 2 for boot configuration. The Wemos D1 boards put the LED in series with the pull-up resistor on io 2. This creates the 'reversed' LED behavior.

The large D1s are retired and it is hard to find a good and readable schematics. The cut out is from D1 mini schematics.


2 stepper cnc inaccurate I'm building a simple cnc machine that just writes letters. It uses 2 steppers for x and y axis.
Here is how it works

generate letters in c# and convert them to list of lines
send to arduino mov_xy line.x line.y as string for each line
on arduino convert to int, multiply by steps per mm and run with speedy stepper

It eventually builds up to accuracy problems.
If it's writing "ZWX", letter "X" would be slightly to the side.
Things i tried:

500000 baud rate
accumulate remainder of float number of steps
different usb cables
different cnc machines

It is serial communication error?
Do i need to implement CRC?
Can UNO handle this?
Does SERIAL_8E1 do parity check automatically or do i need do something?
I went trough everything many times.
What am i missing here?

This image is generated directly from letter lines in c#, so i doubt the problem is on c# side.

I forgot to take care of negative steps in remainder accumulation.
This solved it.
// x accum
float resX = mmX * (float)X_STEPS_PER_MM;
float lresX = (long)resX;
_x_acum += resX - lresX;

long extraStepsX = 0;
while(_x_acum > 1.0f){
     _x_acum -= 1.0f;
     ++extraStepsX;
}

while(_x_acum < -1.0f){
     _x_acum += 1.0f;
    --extraStepsX;
}
// move stepper for lresX + extraSteps


State change in Arduino Using Adafruit display if(menustate == 1310){menustate ++;Serial.println("Execution:");Serial.println(menustate);}
             if(menustate == 1311){menustate ++;if (hr==0) menustate ++;else{aCount++;gpArray[aCount]=hr;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1312){menustate ++;if (minu==0) menustate ++;else{aCount++;gpArray[aCount]=minu;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1313){menustate ++;if (seco==0) menustate ++;else{aCount++;gpArray[aCount]=seco;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1314){menustate ++;if (dates==0) menustate ++;else{aCount++;gpArray[aCount]=dates;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1315){menustate ++;if (months==0) menustate ++;else{aCount++;gpArray[aCount]=years;}Serial.println("Execution GP:");Serial.println(menustate);}
             if(menustate == 1316){menustate ++;if (years==0) menustate ++;else{aCount++;gpArray[aCount]=years;}}
             if(menustate == 1320){menustate ++;}

I am trying to get different time inputs from users by using the menustate value , but here in this code the menustate starts from 1311 and without pressing anything the state goes directly to 1320 .and i cant get to the inbetween states

You should use a switch statement ... than after the switch statement you get the in between states:

// conditional loop
{

    // prepare for switch (if something is needed)

    switch (menustate)
    {
        case 1310:
            menustate ++;
            Serial.println("Execution:");Serial.println(menustate);
            break;
        case 1311:
            menustate ++;
            if (hr==0)
                 menustate ++;
            else
            {
                aCount++;
                gpArray[aCount]=hr;
            }
            Serial.println("Execution GP:");Serial.println(menustate);
        break;

        case 1312:
            // ...

        default:
            // You can do here things with all other values
    }

    // Here you have the in between states available
}

You should put this switch statement in some conditional loop (like until an end state is reached.


MPU6050 safe to use with glue? My current project involves embedding an MPU6050 accelerometer into straps, one of which goes below the knee, the other above the knee.

I need to fit the sensor into the strap and currently i have 6-core multi-threaded wire soldered directly into the board. This doesn't facilitate the greatest of long term stability, as too much strain and the wires will just pull out and break.

What I am wondering is if it is OK to:

cover the wire side of the board in glue from a hot glue gun?
                 Would this have any possible conductivity issues or risk damaging the wires or board itself?
If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance. This would leave me with a really solid sensor for embedding if so!

Any answers to the above questions would be greatly appreciated and I would be extremely grateful for any alternative options as well. I would like to keep the wires soldered into the board as it is extremely tidy and makes for easier embedding than if I were to use another connector.

Would this have any possible conductivity issues

Nope.

  or risk damaging the wires or board itself?

Nope.

  If it is OK to use the hot glue, would it be possible to cover the entire MPU6050 in the glue without compromising performance.

Sure.

This is known as "potting". You can get special potting compounds, but hot glue is just as good.


Wifi module for arduino shield Recently I bought a B006RATC2E wireless shield for my Arduino One, but didn't notice that I had to buy a wifi module as well to let it work (bad surprise as the shield already cost me $30 + travel expenses to CR). Could someone be so kind to suggest me some compatible wifi modules for the shield?

I'm kind of newbie in this and when I search specs for Adafruit and XBee modules, the documentation is not explicit about the compatibility with Arduino shields, so I'm stuck.

I don't want to buy components that would't work together (my budget is limited). Is XBee XB24 a good module for the shield? Any other alternative?

Thanks in advance for any help!

Wireless doesn't necessarily mean it's WiFi.
You should get an XBee module that explicitly states that it's a WiFi module.

For a cheaper alternative you can check ESP8266 WiFi modules, which you can get for $5.


Storing in a global variable using inline assembly What I'm trying to do is pretty basic: I have a global variable and I'm trying to store some value in it (specifically, the SP_H and SP_L values).

The variable is an array of structs and I'm trying to access one of those structs.

This is what I am doing:

typedef struct_t { uint8_t sp_h, sp_l; } struct_t;

struct_t arr[MAX_STRUCTS];

void some_inline_assembly_function()
{
  volatile asm(

  // Determine where to store the new SP_H and SP_L register

  "lds r26, ???                \n\t" // <-- How do I store the address
                                            of arr[0].sp_h or arr[0].sp_l
                                            in the X registers (r26,27)
  "lds r27, ???                \n\t"

  // This part stores the stack pointer low and high byte indirectly
     using the X registers (r26,27), which is what I want.

  "in    r0, __SP_L__          \n\t"
  "st    x+, r0                \n\t"
  "in    r0, __SP_H__          \n\t"
  "st    x+, r0                \n\t"
  ::);
}

If this looks familiar, it is because it probably is. I'm trying to implement simple context switching (pushing the entire task context into the stack and retrieving another one). What I'm trying to accomplish is storing the current PC_H and PC_L to a global variable so that the "shceduler" knows where to start popping the registers and restore the context.

Yes, I know FreeRTOS does this. I need to know how to do this myself.

Thanks a bunch.

The address you are looking for is a symbol known by the linker. Then
you can have the linker put the value of the symbol straight into your
code: no need to load from memory. In other words, you use the ldi
instruction to load the required address as an immediate value. You
should also reverse the order of the struct definition, since you are
storing SPL at the lowest address.

typedef struct { uint8_t sp_l, sp_h; } struct_t;

struct_t arr[MAX_STRUCTS];

void some_inline_assembly_function()
{
  asm volatile(
    // Determine where to store the new SP_H and SP_L register
    "ldi r26, lo8(arr)     \n\t"  // X is loaded with the symbol arr
    "ldi r27, hi8(arr)     \n\t"  // which is the address of arr[0].sp_l
    // Here you may want to add 2 * an array index.

    // This part stores the stack pointer low and high byte indirectly
    // using the X registers (r26,27), which is what I want.
    "in    r0, __SP_L__    \n\t"
    "st    x+, r0          \n\t"
    "in    r0, __SP_H__    \n\t"
    "st    x+, r0          \n\t"
  ::);
}

Notice the lo8() and hi8() assembler macros: they split the address
into low and high bytes. Actually the assembler translates them into
R_AVR_LO8_LDI and R_AVR_HI8_LDI relocations records, and the
linker does the real job.

Edit: I think I just realized why you were thinking of using lds
in the first place...

Instead of using array indices, you may want to access the array through
a pointer (declared struct_t *pointer). When programming in C or C++,
a pointer identifier behaves, for most purposes, just like an array
identifier. However, at the assembly level, using a pointer involves an
extra indirection, as you have to read the contents of the pointer from
RAM. In this case you would indeed be using lds instructions:

; Copy the global 'pointer' into the X pointer register.
lds r26, pointer    ; low byte
lds r27, pointer+1  ; high byte

As a side note, if you are programming in C++, then you have to declare
extern "C" any identifier that you want to use both in C++ and in
assembly. Otherwise the C++ compiler will
mangle its name and you
would need to use the mangled name in the assembly source.