text:
ArduinoJson buffer gets overwritten
I have not that much experience with native languages like c/c++ and I'm facing a strange issue, which drives me crazy. So I'm using an Wemos D1 mini (ESP8266) which uses a class calles ConfigManager to read a configuration file from eeprom. The config file is formatted as json, so I'm using ArduinoJson to parse the content. I have declared a StaticJsonBuffer and pointer to a JsonObject in the header, like you can see in the code example:
//FILE: ConfigManager.h
#ifndef ConfigManager_H
#define ConfigManager_H

#include <Arduino.h>
#include <ArduinoJson.h>
#include <FS.h>
#include "Logger.h"

class ConfigManager {
public:

    Settings *settings;

    ConfigManager();

    void read_from_eeprom();

private:

    File configFile;
    JsonObject *json;
    StaticJsonBuffer<200> jsonBuffer;

    void open_file(const char *permission);

    void read_json();

    void recreate_file();

    void create_json();

    void check_success();

    void populate_settings();

    void clean_up();
};

#endif

When the function read_from_eeprom is invoked, it opens the file and invokes the functionread_json:
void ConfigManager::read_json() {
    size_t size = configFile.size();
    Log.verbose("[ConfigManager] Config file size: %d", size);

    std::unique_ptr<char[]> buf(new char[size]);
    configFile.readBytes(buf.get(), size);
    Log.verbose("[ConfigManager] File content: %s", buf.get());

    Log.verbose("[ConfigManager] Parsing json");
    json = &jsonBuffer.parseObject(buf.get());

    Log.notice("[ConfigManager] Json is:");
    json->printTo(Serial);
    Serial.println();
}

Which is followed by a call to check_success()
void ConfigManager::check_success() {
    Log.notice("[ConfigManager] Json is:");
    json->printTo(Serial);
    Serial.println();

    bool should_recreate = true;
    if (json->success()) {
        Log.notice("[ConfigManager] Parsed json successfully");

        auto version = json->get<const char*>("version");
        if (version) {
            if (strcmp(version, Settings::current_version) == 0) {
                Log.notice("[ConfigManager] Config version is up2date");
                should_recreate = false;
            } else {
                Log.warning("[ConfigManager] Config version outdated");
            }
        } else {
            Log.warning("[ConfigManager] Invalid config file");
        }
    } else {
        Log.warning("[ConfigManager] Config file is not valid json");
    }

    if (should_recreate) {
        Log.notice("[ConfigManager] Recreating config file");
        recreate_file();
        create_json();
    }

    Log.notice("JSON IS: ");
    json->prettyPrintTo(Serial);

    Log.notice("[ConfigManager] Sucessfully read json");
}

So what I noticed is that the file content is fine. E.g. {"version":"0.2","led_count":"64"}.
Then the json is parsed, which succeeds and logs the json object, which is again {"version":"0.2","led_count":"64"}.
Afterwards the function returns, and calls check_success, which again prints the content of the json object to the log, but this time it seems that something has overwritten the JsonBuffer, which causes the json object to be corrupted. This time the logged content is {"v␂":"0.2","led_count":"64"} (with some strange unicorn characters that change as the source code changes). I'm trying to figure out whats going on for many hours now, but I'm stuck. Can someone please point me in the right direction to solve this problem? Thank you!

I give +1 for the care you put debugging your code and a well stated question (which led to a timely answer).

the ArduinoJson library doesn't copy the strings, it only stores pointers and writes terminating zeros into input buffer. And your buffer buf is disposed by std::unique_ptr at the end of read_json() function

That's exactly what I needed. I'm now creating the unique_ptr dynamically and dispose it at the end. It now works flawless. Thank you so much!

@Simon Could you show an example of how you did that ?

@AnumSheraz The 3rd line in the read_json function (where I create the unique_ptr) was the issue. A quick fix would be to move the variable to class level rather than defining it in the function itself. This will keep the buffer available until the class instance is disposed.


text:
Can I change this code to use a potentiometer instead of a push button
The following code is for a pyrograph power supply that uses an ATtiny85. I want to change it, so instead of a push button I have a potentiometer being the control of the temperature. Can anyone guide me on how to accomplish this with this code?
//Written by Tyler Gerritsen
//2017-10-21
//Pyrography Pen Power Supply Controller
//Written for ATTiny85 w/ Internal 1MHZ Clock

const byte btn = 2;
const byte led = 1;
const byte pwr = 0;
byte rate = 0;
unsigned long nextChange = 0;
boolean onOff = false;
unsigned long blinkyCount = 2000000000;
unsigned long nextBlink = 0;
unsigned long debounceTimer = 2000000000;
const unsigned int debounceDelay = 400;
const unsigned int onDelay[5] = {6800, 6300, 5800, 6300, 4800};
const unsigned int offDelay = 5000;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  digitalWrite(btn, HIGH);
  pinMode(led, OUTPUT);
  pinMode(pwr, OUTPUT);
  digitalWrite(pwr, LOW);
  debounceTimer = 60000000;
  while (digitalRead(btn)) {
    checkButton();
  }
  analogWrite(led, 0);
  nextChange = micros();
  debounceTimer = millis() + debounceDelay;
  blinkyCount = 1;

}

void loop() {
  runBurner();
  checkButton();
}

void runBurner() {
  if (micros() > nextChange) {
    if (onOff) {
      digitalWrite(pwr, LOW);
      onOff = false;
      nextChange += onDelay[rate];
    } else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

void checkButton() {
  if (!digitalRead(btn) && millis() > debounceTimer) {
    debounceTimer = millis() + debounceDelay;
    rate++;
    rate %= 5;
    blinkyCount = (rate) * 2 + 5;
    nextBlink = millis();
  }
  if (blinkyCount > 1 && millis() > nextBlink) {
    if (blinkyCount % 2) {
      digitalWrite(led, LOW);
      blinkyCount--;
      nextBlink += 150;
    } else {
      analogWrite(led, 10);
      nextBlink += 150;
      blinkyCount--;
    }
  } else if (blinkyCount == 1) {
    analogWrite(led, 10);
    blinkyCount = 0;
  }
}

This is a simple sketch that shows how to read a potentiometer and do something with the value, namely, adjust the delay of the blinking led.
[Source: https://www.arduino.cc/en/tutorial/potentiometer]
/* Analog Read to LED
 * ------------------
 *
 * turns on and off a light emitting diode(LED) connected to digital
 * pin 13. The amount of time the LED will be on and off depends on
 * the value obtained by analogRead(). In the easiest case we connect
 * a potentiometer to analog pin 2.
 *
 * Created 1 December 2005
 * copyleft 2005 DojoDave <http://www.0j0.org>
 * http://arduino.berlios.de
 *
 */

int potPin = 2;    // select the input pin for the potentiometer
int ledPin = 13;   // select the pin for the LED
int val = 0;       // variable to store the value coming from the sensor

void setup() {
  pinMode(ledPin, OUTPUT);  // declare the ledPin as an OUTPUT
}

void loop() {
  val = analogRead(potPin);    // read the value from the sensor
  digitalWrite(ledPin, HIGH);  // turn the ledPin on
  delay(val);                  // stop the program for some time
  digitalWrite(ledPin, LOW);   // turn the ledPin off
  delay(val);                  // stop the program for some time
}

So, in every loop iteration you read the potPin and using that value for delay.
AnalogRead gives you a value between 0-1023, which you have to adjust to give the desired value for temperature control. That is all you need.
Use map function to adjust the value. Look at https://www.arduino.cc/reference/en/language/functions/math/map/

thank you for the help. I will try this, I am new to programming this type of things I will keep you guys updated

This bit of code from you is the key part:
if (!digitalRead(btn) && millis() > debounceTimer) {
  debounceTimer = millis() + debounceDelay;
  rate++;
  rate %= 5;
  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

Specifically, the rate++ and rate %= 5 lines.
You have a 5-step temp setting. The analogRead() function returns a value from 0 to 1023, which you have to map to 0 to 4 (5 steps). Also, you can read the Potentiometer without worry about debouncing; thus:
if (true) {
  rate = map(analogRead(A0), 0, 1023, 0, 4);
  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

If you desire to have more than 5 "settings" for temperature, you could get a continuous range by eliminating the table onDelay[] and mapping the analog value between the high and low range of the acceptable onDelay values, so you get a finer control of the "on" delay time.
// No longer needs to be an array or a const
unsigned int onDelay = 6800;

Within checkButton():
if (true) {

  // Key Change here
  onDelay = map(analogRead(A0), 0, 1023, 6800, 4800);

  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

Update to runBurner():
void runBurner(){
  if (micros() > nextChange){
    if (onOff){
      digitalWrite(pwr, LOW);
      onOff = false;

      // Key Change here:
      nextChange += onDelay;

    }
    else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

thank you so much this really helps clear some things, and will try this code to give it a test, I really appreciate your time helping me with this

You forgot the rollover issue.

Correct - I only addressed the value-from-pot question and did not further debug the code.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
ATtiny84 vs ATtiny85 consumption
I'm doing a comparative study between ATtiny84 and ATtiny85, and I found from the datasheet that ATtiny84 consumes less current, is that normal even if it is bigger in terms of size and number of pins? Am i wrong?

There are wide differences in power usage in AVR parts. Typically the "P" variants (for "picopower") are more optimized for low power usage, but there are also differences between different revs of the same part (for example the ATMEGA168PB uses slightly more power than the ATMEGA168PA during sleep) presumably becuase of different processes used to make the chips.
If you are looking for the lowest power possible, it will depend on how your application.  Do you spend most time running at full speed? Power down? Do you need a realtime-clock?
Don't forget about the ATXMEGA parts- they have some that have very low power when running a real-time clock from the internal "ultra-low power" oscillator.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
ATtiny85 serial communication, bootloader and setting up fuses
I have been reading some articles about ATtiny and how to burn the bootloader. And I have two questions which I can't figure out.

Do I need to manually setup fuses to run 8 MHz on my ATtiny when I'm using my Arduino board as my ISP (there we can select the internal clock and that confuses me)?
For the SoftwareSerial.h library, do I need to setup my ATtiny to 8 Mhz in order to work?

If you load this into the IDE
https://github.com/SpenceKonde/ATTinyCore
the fuses will be set correctly for the different selectable clock speeds.

If you search the internet, you mostly find statements, that the fuses will be set right, if you burn the bootloader from the IDE. However I had to set the fuses in an extra call to avr-dude, because the clock divider was still active, setting the clock effectivly to 1MHz, instead of the intended 8MHz. With a command like
avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v

you can read the current fuses. Note that you have to set the parameters according to your setup (I used an ArduinoAsISP on the serial port ttyUSB1). You can write the fuses with a command like this:
avrdude -P /dev/ttyUSB1 -b 19200 -c avrisp -p attiny85 -v -U lfuse:w:0xE2:m

depending on which fuse you want to set, you have to replace lfuse with hfuse or efuse.

SoftwareSerial should also work with other clock frequencies, but I don't know the limitations. Keep in mind, that lower clock frequency means you can only reach lower baudrates. It is crucial, that the fuses are set correctly for the intended speed, because the library takes the speed defined in the IDE. In my case this was 8MHz, but the ATTiny still run at 1MHz, which confused the serial communication.


text:
concurrent display of BMP file and text on Arduino TFT LCD screen
I am using an Arduino TFT LCD screen (1.7'') on Arduino Due for displaying .bmp file of 80X60 pixels. Is it possible to display a .bmp image on the lcd screen and also display text/draw an object such as a rectangle, simultaneously in the extra free space available on the screen?
The code I'm using is from the examples section in arduino IDE. File->Examples->TFT->Arduino->TFTBitmapLogo

Yes, after drawing the BMP, draw pixelwise over the TFTs framebuffer (without deleting any other pixels) or compute the whole framebuffer locally and transfer it one go. What library and display exactly are you using?

Thank you for your quick response. I'm using the TFT LCD display 160X128 size by Arduino and TFT.h library. The .bmp file has to be retreived from the SD card. Could you please help me with an example of computing the framebuffer for text/object display?

I looked at the library and it already does direct writes to the TFT's framebuffer over SPI. So you should be able to just call TFTScreen.text() and draw over your bitmap after you called the TFTScreen.image(). function. Can you edit your question to include the current code you're running?


text:
Sending over a number from Arduino to Attiny85
I recently started my first arduino project, displaying a number on a 4x 7 segment display. I want to keep this code and use the display in other projects to display 4 digit numbers (creating a library and using segmentdisplay.write(number) maybe?).
Just displaying the number went really well, but I wanted to drive it with less I/O pins. Then I discovered shift registers, which reduced the number of necessary I/O pins to 3. But, the code needs to execute constantly to keep the 4 digits on the display via multiplexing. My solution to this was to run the sketch on attiny85, on which I programmed the code below. The only thing left to do is to change the value of 'getal' to a value that I read or calculate on the arduino. But I have no idea on how to achieve this, can I shift out data from the arduino to attiny85, which then updates 'getal's value? Any help is appreciated!
const int dataPin = 0;
const int latchPin = 1;
const int clockPin = 2;

const int Db = B00001111;
const int D1 = B00000111;
const int D2 = B00001011;
const int D3 = B00001101;
const int D4 = B00001110;
const int num0 = B11111100;
const int num1 = B01100000;
const int num2 = B11011010;
const int num3 = B11110010;
const int num4 = B01100110;
const int num5 = B10110110;
const int num6 = B10111110;
const int num7 = B11100000;
const int num8 = B11111110;
const int num9 = B11110110;

int D_4[4] = {D1, D2, D3, D4};
int D_3[4] = {Db, D2, D3, D4};
int D_2[4] = {Db, Db, D3, D4};
int D_1[4] = {Db, Db, Db, D4};
const int num[10] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};

const int tallen[4] = {1000, 100, 10, 1};

int getal = 185;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  int lengte = findn(getal);
  switch (lengte) {
    case 1:
      displaynum(D_1);
      break;
    case 2:
      displaynum(D_2);
      break;
    case 3:
      displaynum(D_3);
      break;
    case 4:
      displaynum(D_4);
      break;
  }
}

int findn(int num) {
  int n = 0;
  while (num) {
    num /= 10;
    n++;
  }
  return n;
}

void displaynum(int *D_x) {
  for (int i = 0; i <= 3; i++) {

    digitalWrite(clockPin, LOW);
    digitalWrite(latchPin, LOW);

    shiftOut(dataPin, clockPin, LSBFIRST, D_x[i]);
    shiftOut(dataPin, clockPin, LSBFIRST, num[(getal / tallen[i]) % 10]);
    digitalWrite(latchPin, HIGH);
    delay(1);
  }
}

If you setup the display to run on a timer-driven interrupt, you can still do many other things and the display will update via the timer(say every 5ms)

Hardware i cheaper that your time; buy a LCD or OLED display.

I obviously know that buying a screen is cheaper, I just want to learn this.

While the tiny85 does not have a complete hardware I2C, I believe you can do a hardware-"assisted" I2C interface which may be more suitable for transferring a multi-byte value than asynchronous serial.  Beware though that debugging multiprocessor systems can rapidly become complicated; doing background operations on the main ATmega may ultimtely prove simpler.

As Look Alterno stated it would be easier to directly use an LCD display. But if you really want to use the 7 segment display and the ATTiny85 you can use I2C to send the number to the ATTiny. There are libraries, that can use the USI hardware ot emulate a (nearly) full I2C bus. For example my TinyWire library, that I composed from the previous TinyWireM and TinyWireS libraries. I2C needs only 2 pins (pin 0 as SDA and pin 2 as SCL I think), so you still have your 3 pins left for the display.
Then you would make the Arduino master and the ATTiny slave. Use the examples, that come with the library to learn it's usage. Note, that currently you can use the write() function only with one byte, so if you need bigger datatypes you need to split them to byte-level on your own.

Could also use a chip with better resources, such as Attiny2313. 20 Pins, so a little larger than the '85, but you get a real serial port and SPI port.


text:
Is it possible to add an additional board on Arduino Web Editor (create.arduino.cc)?
I'm using a board that can be programmed via Arduino IDE (a NodeMCU with ESP8266) and I've configured the Windows client successfully. I've added an additional board through "Preferences" menu by specifying its configuration url, following manufacturer's directions.
Now, I'm quite happy with the web editor, the one at create.arduino.cc, and I'd like to use it with this board too. Is there any way to configure additional boards?

No, there isn't.
The web editor is completely closed. It's a service run by Arduino, and as such it will only support Arduino's own boards.
Two reasons:

Why should they spend the time, effort and money adding support for other people's products?
It adds value to their products to encourage you to use real Ardiuno hardware.

Business is business, after all.

Got it, makes sense. The border is a bit blurred to me, sorry: seeing that feature on the client IDE made me wonder if the same was available on the web counterpart.

Here's a statement from an Arduino employee to the contrary: http://forum.arduino.cc/index.php?topic=361376.msg2741262#msg2741262 "we will support 3rd party HW in the future". On the other hand that statement was made over 1.5 years ago. I think there are security challenges to this since they will need to allow 3rd party applications to run on their server. I also wouldn't say "completely closed" since there are open source components but certainly a lot of it is closed. Interestingly there is another comment in that thread indicating there was a consideration of making it open.


text:
Two-wire Conductivity Sensor and Arduino Hook-up?
For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.
I am trying to figure out the best method for measuring the output of the sensor using an Arduino.
I am told from the supplier that there is no polarity.  I was planning to connect one of the leads through a 10k resistor to an analog input (A0) on my Arduino; and the other lead to 5V?
Without much other information on the sensor, is a 10k resistor a good place to start?

what does "non-NPN" mean? ... the picture shows what looks like two metal prods ...there may be a component inside the long tube ... do you have a link to the spec sheet for the sensor? ... if it is just two metal prods, then connect +5V -> 10k -> prod#1 -> A0  and  prod#2 -> GND (0V)  ... if the long tube has a resistor, then connect +5V to long prod without using a 10k resistor

I think the npn dictates the type of output (logarithmic vs. linear).  I am using a 10k resistor.  What would the effect of adding a higher resistance or lower resistance be?  Would it change the resolution of the sensor output?  It looks like, for example when I use a 10k resistor, my numbers are much higher and change quicker than when I use a 1k resistor.  It appears that there is higher resolution?

It depends on the conductivity of the liquid which it is going to be placed/submerged to. For example if the liquid is highly conductive(ex. saltwater), then a 10k Ohms resistor should be fine. But if the liquid conductivity is low(ex. tap water), then its best to measure the output voltage of one lead with respect to the Arduino's ground to be sure what value of resistor to apply to or if there is no resistor needed at all.
But generally if you are going to supply it with 5 Volts, it should be fine to connect it with the Arduino's Analog inputs directly as the operating voltage of the Arduino itself is also 5 Volts.
Cheers!

Thanks for your comment!  Could you just elaborate on what the resistor is doing in this case?  For example, if I am using a 10k versus a 1k, does the conductivity sensor with the 10k keep it from getting too saturated from the high conductivity of the salt water?

See photo that I posted in the original post.  I have a probe in tap water, and used different resistor values between GND and A0, as per my Fritzing schematic also shown.  My question is; why does the non-resistor value have a higher value than the 300k resistor value?

I see, from the picture you posted that is a pull-down resistor. Why pull-down, because it is connected between the input(A0) and ground(GND), so when a positive signal comes in, the resistor acts as a "pull-down" voltage.
For additional info: On the contrary there is "pull-up" resistor when the resistor is connected between the positive supply(5V) and the input pin(A0). this type of setup is used when the output of a sensor for example is going from high to low, so to determine there is a change the default state is "pulled-up" by the resistor to 5V so the sensor's output can be read.

By the way, I think why they used a 10k ohms value of resistor is because probably the output of the sensor is 12Volts, so that it won't damage the Arduino, there is a 10k value of pull-down resistor.
But if the output of the sensor is 5V, there should be no resistor needed at all.


text:
Enroll more than one finger on Unique Id in R305 FingerPrint Module Working With Arduino
I am working on a project when I have to enroll and Submit the attendance of the fingerprints.
What I have : I am able to enroll single fingerprint on a different unique ID. Using AdaFruit FingerPrint Sensor Library.
I have :

R305 FingerPrint Sensor having 1000 fingerPrint storage and
  Arduino Uno

What I want : I want to enroll more than one finger Prints on same Unique Id.
How to do it, Please anyone Help me with  this.
Help will be appreciated. Thanks

your project seems to have a lot of issues with privacy  ... why are you capturing people's fingerprints?

No, You are getting me wrong, it is just a college project but i want to enroll more than one finger on same unique id

i do not think that you can ... the reader outputs a unique ID for each fingerprint ... the controller has to keep track of all the ID numbers belonging to an individual

Each fingerprint must have a unique ID that refers to that fingerprint.
What you need next is a table to associate multiple fingerprint IDs with "persons" so that you can find out which person belongs to a particular print scan.
You didn't say if you were holding fingerprint and person data within the Arduino or on some network-based storage system, but if we assume that this is entirely self-contained in the Arduino you would need to write the association table to some kind of storage that won't reset when the Arduino loses power, such as an EEPROM. The Uno has a "built in" EEPROM on the ATMega328p chip, but it only holds 1024 bytes. There are external EEPROMs that communicate via SPI or I2C that can hold more data.
As to the actual data structure -- it can be as simple as a 2-dimensional array, with one dimension holding the fingerprint ID, and the other holding a person ID. For multiple fingerprints of the same person, the table would have multiple rows with the same person ID, but different fingerprint IDs.
You could also make an array of struct datatypes, or create class, etc. But the point is that the "Unique ID" matching only ONE print from the fingerprint sensor is a limitation you have to work with.


text:
Why my ISR is giving impossible values?
I have a very simple ISR:
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;
volatile uint32_t count = 0;
volatile uint32_t toggle = PATTERN_A;

// My ISR
void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

The idea is that the toggle variable takes values 0xFF00FF00 or 0xFF00FF00 depending on the evenness of the count variable. This is the only place where toggle is changed, but it's used (read-only) in the sketch.
I don't know why, but toggle gets all sort of random values during execution.
What is happening here?

The problem is a combination of several causes.
Assignments are not atomic
An atomic operation is something that is completely done or not. The opposite is some operation that can be disrupted while executing, leaving thing in a inconsistent state.
This is how the count++ works at machine level in Arduino:
void callback()
{
    count++;
  fa:   80 91 0a 02     lds r24, 0x020A
  fe:   90 91 0b 02     lds r25, 0x020B
 102:   a0 91 0c 02     lds r26, 0x020C
 106:   b0 91 0d 02     lds r27, 0x020D
 10a:   01 96           adiw    r24, 0x01   ; 1
 10c:   a1 1d           adc r26, r1
 10e:   b1 1d           adc r27, r1
 110:   80 93 0a 02     sts 0x020A, r24
 114:   90 93 0b 02     sts 0x020B, r25
 118:   a0 93 0c 02     sts 0x020C, r26
 11c:   b0 93 0d 02     sts 0x020D, r27

The first four instruction loads the four count bytes into four separate register, the laboriously increment it by one and then store it back in RAM.
Now, toggle is a variable of interest and you want to use it inside loop, like this:
void loop()
{
    uint32_t x = toggle;
    ...
}

And at machine level you get
    uint32_t x = toggle;
 414:   60 91 04 01     lds r22, 0x0104
 418:   70 91 05 01     lds r23, 0x0105
 41c:   80 91 06 01     lds r24, 0x0106
 420:   90 91 07 01     lds r25, 0x0107

Here we are simply copying the toggle variable into our x variable. As you can see, the copy takes four machine instructions to get completed.
Now, what happens if an interrupt comes while you are copying (or using) toggle?
An interrupt suspend the assignment, go to the ISR (callback in this case and change toggle value. Upon return, copying continues, mixing bytes from the old and new value.
You must use volatile
Any global variable used inside an ISR must be declared volatile. This is an hint to the compiler that the variable could change unexpectedly. Therefore, the volatile variable must be always read afresh, discarding any cached value.
Critical section
The rule for using values changed by ISR is simple:

Always copy the ISR's global variables to your own temporary variable.
Before coping, disable interrupts and reenable it after the copy is done. This prevent the ISR from executing while your are copy the values.

Demo
This little demo shows you all of this in action.
The sketch collect all the values from toggle (not disabling interrupts) during one minute and after that print a table showing what it got.
/*
 * This sketch show how to deal with variables shared between ISR and main thread.
 *
 * By Look Alterno 2018
 */

#include "TimerOne.h"

volatile uint32_t count = 0;
const uint32_t PATTERN_A = 0xFF00FF00;
const uint32_t PATTERN_B = 0x00FF00FF;

volatile uint32_t toggle = PATTERN_A;

#define MAX_CASES 16
struct {
    unsigned long value;
    int count;
} found[MAX_CASES];
int freeFound = 0;

#define PRINT_INTERVAL 60000L

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

    while(!Serial);

    Serial.println("");
    Serial.println("Test assignment under interrupts");
    Serial.println("");

    Serial.print("Value A=");
    Serial.println(PATTERN_A, HEX);
    Serial.print("Value B=");
    Serial.println(PATTERN_B, HEX);

    Timer1.initialize(500);
    Timer1.pwm(9, 512);
    Timer1.attachInterrupt(callback);

    pinMode(A0, INPUT);
    randomSeed(analogRead(A0));
}

void callback()
{
    count++;
    toggle = (count % 2) ? PATTERN_A : PATTERN_B;
}

void loop()
{
  static unsigned long prev = 0;

  //  A random delay to simulate some real, variable work being done.
    delayMicroseconds(random(250));

  // This is the critical section.
//  noInterrupts();
    uint32_t x = toggle;
//  interrupts();

  // Now, let's see what value we got.
    if(x != PATTERN_A && x != PATTERN_B) {
        insert(x);
    }

  // Print values found
  unsigned long now = millis();
  if (now - prev > PRINT_INTERVAL) {
    printFound();
    prev = now;
  }
}

/*
 * Add a value to a table for counting.
 */
void insert(unsigned long x)
{
    int index = 0;

    while(index < freeFound && found[index].value != x) {
        index++;
    }

    if(index < MAX_CASES) {
        if(index == freeFound) {
            found[index].value = x;
            found[index].count = 1;
            freeFound++;
      Serial.print(freeFound);
      Serial.print(". Add=");
      Serial.println(x, HEX);
        } else {
            found[index].count++;
        }
    } else {
        Serial.print("*** Table overflow. value=");
        Serial.print(x, HEX);
        Serial.println(" ***");
    }
}

/*
 * Print the table of found values so far.
 */
void printFound() {
  Serial.println("");
  Serial.println("Values found");
  Serial.println("");
  Serial.println("Value - Count");
  for (int i=0; i < freeFound; i++) {
    Serial.print(found[i].value, HEX); Serial.print(" - "); Serial.println(found[i].count);
  }
}

If you uncomment noInterrupts and interrupts, every thing works just fine.
Other CPU
More powerful CPUs have atomic assignments, but following this practices makes your code portable across platforms, no matter what. Think of defensive programming

you can do it branch-less by defining an array with both states
const uint32_t PATTERN[2] = { 0x00FF00FF, 0xFF00FF00 }; and evaluating it via PATTERN[count & 1];.

@Kwasmich. Your proposal is more compact, but I'm trying to keep it simple and focused on the central issue. As a personal matter, I prefer the "?:" pattern. You can explore this issue comparing the standard "?:" vs your proposal, from performance, convenience and clarity. I'm waiting for your post.

@Kwasmich: Note that branchless is not necessarily better. Especially on the AVR which, owing to its very shallow pipeline, has very cheap branching.

Moderator's note: Due to the dispute about this answer we have reverted the community wiki flag, and rolled back the answer to the (almost) original one. Anyone who believes they can post a better answer is free to do so.

@User42 You are right. There is no point in making the code more compact, if it does not save time or flash space.

@Edgar Bonet True. Not all optimizations from x86 apply to AVR. Here one has to trade between precious flash space and execution time. For example it takes less flash space for swapping A and B the naive way using a temporary variable than having the BitTwiddling tripple XOR solution.


text:
Ubuntu class string has no member remove
I am running some code that works fine on my windows system using the .remove method.  On Ubuntu 16.04 I get the following errror:
error: ‘class String’ has no member named ‘remove’

To see if it was installation, I uninstalled arduino with
sudo apt-get purge arduino arduino-core

then
sudo apt-get update
sudo apt-get upgrade

sudo apt-get install arduino arduino-core

and the issue remains.  I have seen some people say opening arduino through the terminal (from this), although that does not fix it.
Arduino version
2:1.0.5+dfsg2-4
Any help is appreciated.

Why are you running 1.0.5?

@IgnacioVazquez-Abrams I didn't realize that, for some reason I thought it was 2.  Ubuntu is installing 1.0.5 even after the updated package list, is arduino not maintained on the repo? Or am I missing something obvious?

You'll probably have to download the tarball from the Arduino site, but don't quote me on that.

The remove method was added to the String class in 1.0.6.
Installing Arduino IDE from the Ubuntu repository gets you a really old package (1.0.5).
You should download and install the newest version from the official Arduino page.

Yep, that's what I always do. Download the newest version and bang it into some place like your home directory.


text:
Arduino Leonardo RX TX mystery
I'm at the tail end of a project using a Leonardo, a HC-06 bluetooth module and a few cell phone vibration motors.  Everything is working fine except the serial communication between the Leonardo and the HC-06.  I've done some tests to rule out common mistakes

TX is connected to RX, and vice versa.
Using a multimeter I checked for continuity with the RX TX, no problem there
I can upload the script
I uploaded the exact same script to an Uno, using the same HC-06.  I was able to connect to the HC-06 with my phone and execute the script.  So I know it's not the script and I know it's not the HC-06.
The Leonardo is working properly because I can upload the script and execute it using the Arduino Serial Monitor.

The only clue I have is that I can upload the script with the RX/TX connected and that's not supposed to work.  However, I checked the connections and there is continuity.  So I'm stumped.  The only thing I can think of is that I damaged the RX/TX while I was soldering, but I'm hoping it's not that.  Is there a way to test for that.  Any suggestions?
/*
 * created by Rui Santos, http://randomnerdtutorials.com
 * Bluetooth App - Turn On and Off LED
*/

#include <SoftwareSerial.h>
SoftwareSerial mySerial(1, 0); // RX, TX

int led = 3;
int state;

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0){
      state = Serial.read();}

  if (state == '1') {
      digitalWrite(led, HIGH);}   // turn the LED on (HIGH is the voltage level)

  else if (state == '2') {
      digitalWrite(led, LOW);}    // turn the LED off by making the voltage LOW

  delay(100);               // wait for 100ms

  //For debugging purpose
  //Serial.println(state);
}

You should read the Leonardo manual. All will be explained. It's very different from an Uno.

Why are you using software serial on pins 0 and 1?

On the Leo the RX and TX are labeled RX1 and TX0, so I assumed they were pins 0 and 1.  But I also deleted that line of code and tested it and still it didn't work

An Arduino Leonardo has native USB support. Which means that it has separate serial interfaces to the PC and to the hardware pins.
Serial is only used for the communication with the PC and is unrelated to the hardware serial pins 0 and 1. Those are exposed trough Serial1.
So, if you are using the exact same Uno sketch, that uses the hardware serial pins, it can't work on a Leonardo, because data is just sent-to/read-from the PC and not to the connected Bluetooth module connected on pins 0 an 1.

Thanks.  Any suggestions on how to change the script to reflect that difference?

You need to replace Serial with Serial1.

You're a genius gre_gor, it worked!!  Thanks for the help, I needlessly banged my head against the wall for 3 days.  Have a good one!


text:
Sending Float values from Python to Arduino via serial communication
I want to Control the current flowing through a circuit using an Arduino. I have trained a PID controller for this purpose. I am using a current sensor to determine the error. It runs successful on my Arduino.
In my next step I want build a system where I can send the Current setpoint (deter mined by my python code) value to the Arduino through serial communication. I am able to send integer values to Arduino. But I am unable to send and receive float values from Python to Arduino. I want to know the necessary code to be written in both sender and receiver.
I tried of converting float to string and then send it to Arduino. But I failed. Please help.
Arduino Code(edit- Sorry previous code was an old file. Here is the correct one):
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
//pinMode(13,OUTPUT);
}
float f;

void loop() {
 if(Serial.available())
      {f=Serial.parseFloat();
        Serial.println(f);
      }
    delay(1000);
   }
//count=count+1;
      //delay(1);
//}

Python Code (edit- Sorry, the previous code was from an old file. Here is the correct one):
import serial
import time
import struct

ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1) # ttyACM1 for Arduino board
data=5.7

while True:
        ser.write(str(data))
        time.sleep(1)
        ser.flush()

When I run this code I get the following output on the Arduino Serial Monitor. As shown in the figure below.

Thank you.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets. Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem. Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant. Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem

Problems: 1) Data doesn't arrive in all at once, but in chunks. 2) You don't  filter out control chars like LF, CR and others. 3) You never look for a delimiter to sync things between Arduino and Python. 4) Never convert the string to float.  Google "Arduino parse string" and study that

Start by removing the "delay(1000);" in loop(). Why would you want that? And change the order of "time.sleep(1)" and "ser.flush()". Last but not least add a space character between writing numbers.

@Mikael Patel... Thank you for the response. It works. Thanks again.

You are sending 5.75.75.75.75.75.75.75.75.75.7.

It would seem you managed to solve your problem with
Serial.parseFloat(). This is probably the easiest solution, but it has
one serious drawback: it is a blocking function. Which means, during
all the time needed by the serial port to transfer the number, your
Arduino does nothing but wait for the incoming characters. This is an
issue if your program has other task to do like, e.g., manage a PID
regulation.
I suggest you consider reading the serial port in a non blocking
fashion instead. This should make your PID happier, as it won't feel
neglected while you read the incoming data. Look Alterno's answer is a
good example of a non-blocking function that combines reading and
parsing. However, I would like to point out that you do not need to
implement your own number parser if you don't want to. A very common
pattern is to instead store the incoming characters in a buffer and,
when you see the character chosen as a terminator (e.g. ASCII LF), you
parse the buffer at once using either strtod() or atof(). For
example:
void setup() {
    Serial.begin(9600);
}

void loop() {
    static char buffer[32];
    static size_t pos;
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') {  // on end of line, parse the number
            buffer[pos] = '\0';
            float value = atof(buffer);
            Serial.print("received: ");
            Serial.println(value);
            pos = 0;
        } else if (pos < sizeof buffer - 1) {  // otherwise, buffer it
            buffer[pos++] = c;
        }
    }
}

Well sir, even this code has the same outcome as that of Alterno's code. The serial monitor is just empty. Again my python code is still the same.

@CR7: Your Python code is buggy: it fails to send a line terminator. You should ser.write(str(data) + "\n").

Thank you sir, it works. Takes less time too. Thanks once again.

Problem with Serial.parseFloat() is that it blocks until it read the value.
Try this code, which implement a minimal float parse routine (no error checking), and it's not blocking, so you can do other things while waiting for float to come
void setup()
{
    Serial.begin(9600);

    while(!Serial);

    Serial.println("Start");
}

float result = 0;
bool dec = false;
int decDiv = 10;

void loop()
{
   // Float are positive, with format 999.99 (no sign, variable length integer/dec
   // We read only one char in each execution.

    if(Serial.available()) {
        // Read a single char from serial input.
        char c = Serial.read();

        if(isDigit(c)) {
            int val = (c - '0');  // Convert ASCII to binary.

            if(dec) {
                // We just read a decimal digit.
                result += (float) val / decDiv;
                decDiv *= 10;
            } else {
                // We just read a integer digit.
                result = result * 10 + val;
            }
        } else if(c == '.') {
            // Decimal part start now.
            dec = true;
        } else {
            // Any other thing is the end of the float value.
            Serial.println(result);
            // And reset everything for another float value.
            result = 0;
            dec = false;
            decDiv = 10;
        }
    }
}

Well, sorry to say Sir but this didn't work. The serial monitor just shows "start". I didn't change the python code at all. Just implemented your Arduino code.

Did you type a float value in the Serial Monitor?

No Sir, I just uploaded the code. Started my python script and opened the serial monitor.

@CR7 Forget Python for a while. Just connect your Arduino to Arduino IDE's Serial Monitor and type a float value. Test the code until it perform as you require and then conect it with Python. Divide and Conquer.

Yeah sir, I entered a float value in serial monitor. Still the same result. Only start.

@CR7 Did you press Enter after the value?

Yeas obviously...


text:
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


text:
Run two steppers one by one
I want to run two stepper motors one after the other. Stepper 1 has to move 5 rotations, and stepper 2 has to move 1 rotation. Here is the code.
Stepper 1 is nema 34
And stepper 2 is nema 24
#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper1 (1, 3, 2); // Defaults to 4 pins on 2, 3, 4, 5 mortor (A)
AccelStepper stepper2 (1, 5, 4); // Defaults to 4 pins on 2, 3, 4, 5 motor (B)

long Steps_For_Distance1 = 3; // 3cm
long Steps_For_Distance2 = 5; // 5cm
long currentPos = 0;
long targetPos = 200;
long targetPos_Reverse = -200;
long Motor_Speed1 = 50;
long Motor_Speed2 = 400;
long Motor_Speed3 = 800;
int Op_Sw = 0;
const int buttonPin = 2;     // the number of the pushbutton pin

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

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

void setup()
{
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);

  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void checkStepper1_For_DT(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations
    astepper.setCurrentPosition(currentPos);
    astepper.moveTo(targetPos);
    astepper.setSpeed(Motor_Speed1);
    astepper.setAcceleration(100);
  }
}
void checkStepper2_For_360(AccelStepper &astepper)
{
  if (astepper.distanceToGo() == 0)
  {
    // Random change to speed, position and acceleration
    // Make sure we dont get 0 speed or accelerations

    astepper.moveTo(targetPos);
    astepper.setMaxSpeed(Motor_Speed2);
    astepper.setAcceleration(100);
  }
}
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;

  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  stepper2.runSpeedToPosition();
}
void loop() {
    PatternToBeLooped_For_Cycle1();
  }

I ran the code, but it didn't work. Both motors are running at the same time.
Please help me. Where did I make a mistake?
Thank you in advance.

I tried with delay(1000);, but
But still both steppers are moving  at the same time and get delay at the same time.

please show the wiring diagram

May it be that they are not moving at the same time but moving one after another very fast, so that you cannot see the difference? Try putting a delay inbetween of the two stepper run statements in your looped function and see what happens

-Dir pin  to arduino gnd

-Dir pin , - pulse pin  to arduino gnd.     And + dir to arduino 3 pin  ,5pin.    And +pulse to pin 2,4

I looked into the source of the AccelStepper library here, which may be your library or one similar to it. The function runSpeedToPosition() does not block until the desired position is reached. Instead inside the function you see code that executes a step, when the right time (according to millis()), calculated through the speed, is reached, else it will return false. You are supposed to call this function very often while the motor moves. This enables you to drive more than one motor simultaneously with different speeds.
Since you don't want to drive both motors at the same time, you have to loop, until the first motor have reached the desired position; then doing the same with the second motor. Try something like this:
void PatternToBeLooped_For_Cycle1()
{
  int count = 0;
  for (count == 0; count <= 5; count ++)
  {
    checkStepper1_For_DT(stepper1);
    while(stepper1.currentPosition() != stepper1.targetPosition()) stepper1.runSpeedToPosition();
  }

  checkStepper2_For_360(stepper2);
  while(stepper2.currentPosition() != stepper2.targetPosition()) stepper2.runSpeedToPosition();
}

Note: With this change the function PatternToBeLooped_For_Cycle1() blocks the execution of the loop function, until the motors have done their movement. To avoid this you can use an if-statement, which executes the code for stepper1 or stepper2 depending on the millis() function. This works the same way as the BlinkWithoutDelay example in the Arduino IDE.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
EDB char array problem. New input word overlaps the previous words saved
I have been searching everywhere now and nothing seems to work out for me. When I try to input a new word, it overlaps the previously entered words.
Here is my struct definition:
struct LogEvent{
  char fullname[30];
} logEvent;

Here is how I assign a value to fullname:
strcpy(logEvent.fullname, testName);

Here is how I print the output:
for(int i = 0; i <= db.count(); i++)
{
  EDB_Status result = db.readRec(i, EDB_REC logEvent);
  if(result == EDB_OK)
  {
     Serial.print(logEvent.fullname);
     Serial.print(" ");
  }
}

Here is the sample output:
Input 1 - Lebron James
Output 1- Lebron James

Input 2 - Kobe Bryant
Output 2 - Kobe Bryant Kobe Bryant  (The output should be - Lebron James Kobe Bryant)

Input 3 - LeGoat
Output 3 - LeGoat LeGoat LeGoat (The output should be - Lebron James Kobe Bryant LeGoat)

How to fix this?
EDIT. Here is my code:
#include "Arduino.h"
#include <EDB.h>

// Use the external SPI SD card as storage
#include <SPI.h>
#include <SD.h>

int recnumber = 1;
//Arbitrary definition
struct LogEvent {
    int id;
    int temperature;
    char fullname[30];
}
logEvent;

inline void writer (unsigned long address, const byte* data, unsigned int  recsize) {
    digitalWrite(13, HIGH);
    dbFile.seek(address);
    dbFile.write(data,recsize);
    dbFile.flush();
    digitalWrite(13, LOW);
}

inline void reader (unsigned long address, byte* data, unsigned int recsize) {
   digitalWrite(13, HIGH);
   dbFile.seek(address);
   dbFile.read(data,recsize);
   digitalWrite(13, LOW);
}
  EDB db(&writer, &reader);

// Run the demo
void setup()
{
    pinMode(13, OUTPUT);
    digitalWrite(13, LOW);

    Serial.begin(9600);
    Serial.println(" Extended Database Library + External SD CARD storage demo");
    Serial.println();

    randomSeed(analogRead(0));

    if (!SD.begin(SD_PIN)) {
        Serial.println("No SD-card.");
        return;
    }

    // Check dir for db files
    if (!SD.exists("/db")) {
        Serial.println("Dir for Db files does not exist, creating...");
        SD.mkdir("/db");
    }

    if (SD.exists(db_name)) {

        dbFile = SD.open(db_name, FILE_WRITE);

      // Sometimes it wont open at first attempt, espessialy after cold start
      // Let's try one more time
        if (!dbFile) {
            dbFile = SD.open(db_name, FILE_WRITE);
        }

        if (dbFile) {
            Serial.print("Openning current table... ");
            EDB_Status result = db.open(0);
            if (result == EDB_OK) {
                Serial.println("DONE");
            } else {
                Serial.println("ERROR");
                Serial.println("Did not find database in the file " + String(db_name));
                Serial.print("Creating new table... ");
                db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
                Serial.println("DONE");
                return;
            }
        } else {
            Serial.println("Could not open file " + String(db_name));
            return;
        }
    } else {
        Serial.print("Creating table... ");
        // create table at with starting address 0
        dbFile = SD.open(db_name, FILE_WRITE);
        db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
        Serial.println("DONE");
    }
    deleteAll();
    recordLimit();
    countRecords();
}
char testName[30];

void loop()
{
  if(Serial.available())
  {
    Serial.println("Waiting for name...");
    index = 0;
    for(int i = 0; i < sizeof(testName); ++i)
    {
      testName[i] = (char)0;
    }
    while(Serial.available())
    {
      char character = Serial.read();
      testName[index] = character;
      index++;
    }
    createRecords(testName);
    selectAll();
    delay(1000);
  }
  delay(1000);
 }

void createRecords(char *testName)
{
  Serial.print("Creating Record... ");
  logEvent.id = recnumber;
  logEvent.temperature = random(1, 125);
  strcpy(logEvent.fullname, testName);
  recnumber++;
  EDB_Status result = db.appendRec(EDB_REC logEvent);
}

void selectAll()
{
   for (int recno = 1; recno <= db.count(); recno++)
   {
      EDB_Status result = db.readRec(recno, EDB_REC logEvent);
      if (result == EDB_OK)
      {
        Serial.print("Recno: ");
        Serial.print(recno);
        Serial.print(" ID: ");
        Serial.print(logEvent.id);
        Serial.print(" Temp: ");
        Serial.print(logEvent.temperature);
        Serial.print(" Fullname: ");
        Serial.print(logEvent.fullname);
        Serial.print(" Length: ");
        Serial.println(strlen(logEvent.fullname));
      }
    }
 }

Here is the output:
Extended Database Library + External SD CARD storage demo

Openning current table... DONE
Truncating table... DONE
Record Limit: 2045
Record Count: 0
Record Count: 0
Waiting for name...
Name received: Kobe Bryant
LogEvent Fullname:
The sentence entered is 11 characters long
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
Waiting for name...
Name received: Lebron James
LogEvent Fullname: Kobe Bryant
The sentence entered is 12 characters long
Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
Waiting for name...
Name received: Michael Jordan
LogEvent Fullname: Lebron James
The sentence entered is 14 characters long
Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Michael Jordan Length: 14
Recno: 2 ID: 2 Temp: 78 Fullname: Michael Jordan Length: 14
Recno: 3 ID: 3 Temp: 29 Fullname: Michael Jordan Length: 14

Update: I tried to use memset but the result is still the same as above.

The sample output doesn't correspond with the your code. Publish a complete, mininal code that show the result you posted.

@LookAlterno Sure

memset fill a block of memory with a given value. See it http://www.cplusplus.com/reference/cstring/memset/

Okay, I'll try to work on that.

Your code looks clean and well structured, and you have a good debugging approach, but code and output doesn't match (and setup is missing). Your question is valuable; please edit it so code and output match. And complete, so others can test it easily.

Okay. Working on it.

Can you upload the arrangement you made here I have the same problem

I managed to solve the problem. The problem is with the SD card library of Arduino. I downloaded this library sdFat library, included it in the sketch #include "SdFat.h", and defined SdFat SD. I also removed the #include <SD.h>.

I've just tried to extend one of the examples (with internal EEPROM), and it's working as expected:
/*
 EDB_Simple.pde
 Extended Database Library + Internal Arduino EEPROM Demo Sketch

 The Extended Database library project page is here:
 http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

 */
#include "Arduino.h"
#include <EDB.h>

// Use the Internal Arduino EEPROM as storage
#include <EEPROM.h>

// Uncomment the line appropriate for your platform
#define TABLE_SIZE 512 // Arduino 168 or greater

// The number of demo records that should be created.  This should be less
// than (TABLE_SIZE - sizeof(EDB_Header)) / sizeof(LogEvent).  If it is higher,
// operations will return EDB_OUT_OF_RANGE for all records outside the usable range.
#define RECORDS_TO_CREATE 10

// Arbitrary record definition for this table.
// This should be modified to reflect your record needs.
struct LogEvent {
  int id;
  int temperature;
  char test[20] = {};
}
logEvent;

// The read and write handlers for using the EEPROM Library
void writer(unsigned long address, byte data)
{
  EEPROM.write(address, data);
}

byte reader(unsigned long address)
{
  return EEPROM.read(address);
}

// Create an EDB object with the appropriate write and read handlers
EDB db(&writer, &reader);

void setup()
{
  Serial.begin(115200);
  Serial.println("Extended Database Library + Arduino Internal EEPROM Demo");
  Serial.println();

  db.create(0, TABLE_SIZE, sizeof(logEvent));

  Serial.print("Record Count: "); Serial.println(db.count());

  Serial.println("Creating Records...");
  int recno;
  for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
  {
    logEvent.id = recno;
    logEvent.temperature = recno * 2;
    strcpy(logEvent.test, (String{recno*3} + " whatever " + recno).c_str());
    db.appendRec(EDB_REC logEvent);
  }

  Serial.print("Record Count: "); Serial.println(db.count());
  // Thanks to katts0...@gmail.com for the next line
  for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
  {
    db.readRec(recno, EDB_REC logEvent);
    Serial.print("ID: "); Serial.print(logEvent.id);
    Serial.print(" Temp: "); Serial.print(logEvent.temperature);
    Serial.print(" Data: "); Serial.println(logEvent.test);
  }
}

void loop()
{
}

The output:
Extended Database Library + Arduino Internal EEPROM Demo

Record Count: 0
Creating Records...
Record Count: 10
ID: 1 Temp: 2 Data: 3 whatever 1
ID: 2 Temp: 4 Data: 6 whatever 2
ID: 3 Temp: 6 Data: 9 whatever 3
ID: 4 Temp: 8 Data: 12 whatever 4
ID: 5 Temp: 10 Data: 15 whatever 5
ID: 6 Temp: 12 Data: 18 whatever 6
ID: 7 Temp: 14 Data: 21 whatever 7
ID: 8 Temp: 16 Data: 24 whatever 8
ID: 9 Temp: 18 Data: 27 whatever 9
ID: 10 Temp: 20 Data: 30 whatever 10

I'll try to look into this.

I tried this and it is working as you said. Maybe my problem is with the SD Card library SD.h

@Xirb or reader/writer is not working as expecter. I've used different signatures - it's called for each byte


text:
3.3V Conversion
I'm writing a SPI Master module for my FPGA and I would like test it with my Arduino Uno.
What's the problem? My FPGA has 3.3V logic and Arduino has 5V TTL logic.
So, what's the simplest solution to convert 5V TTL logic into 3.3V logic?
I know this topic has been already discussed in many sites but I can't find an unified answer.
Thanks in advance!

Logic level Converter boards

Just about any 5V powered IC will take 0-3.3V and output 0-5V.
Like this one for example

If you don't need the 16 MHz clock speed, running your Arduino at 8 MHz/3.3v is an option.  Or there are chips that run far faster at that voltage.  Or you can use level conversion, either fully push/pull or low side with pullup - it's not really possible to pick the best solution without considering context that is missing from your question.

Use a 3.3v Arduino or NodeMCU and simplify life.

You will get better answers (and maybe stop people arguing with each other) if you mention what FPGA you have in mind, and maybe a link to its datasheet, so we can see what its requirements are. Please read How do I ask a good question?.

But just any 3.3V device won't take 5V.

You can get 5, 4 channel bi-directional logic level converters for less than $1 USD Logic Level Module
Not only will they "translate" 3.3V to 5V and 5V to 3.3V, but they also work with higher voltages as well. For example, a vehicle with a 12V electrical system to 5V and vice versa works too.

While this clever circuit will work for some purposes, one should beware that such devices only actively drive low.  The high side output is provided by a pull-up resistor only, typically 10K (though could be smaller).  As a result, it is limited to moderately low speeds and short wire runs in quiet environments.

The OP asked for the "the simplest solution". My answer is simple and very inexpensive. If you have a simpler method, please share it with us.

Your answer is indeed simple, but it is not always suitable.  The point of my comment was to point out the limitation so that an informed decision can be made.  Engineering almost always comes down to such a trade off between needs and costs, so the key to success is knowledge rather than blind assumption.  I've used circuits such as you suggest in projects, but I've also had needs which they cannot meet.

Just like I thought, you don't have a simpler way to level translate.

If you prefer to shop US instead of ordering from China, both Sparkfun & Adafruit manufacture similar modules.

-1 If you are going to absolutely beg for a downvote by positioning your suggestion as a contest entry rather than a technical solution limited to some circumstances, you are welcome to one.  As for a "simpler" way, there are circumstances where just a series resistor is enough (one of which is in a Xilinx FPGA app note, no less!).  And there are circumstances where you do not need anything at all.  But as always, what is suitable depends on the unstated details of the need.

@Chris Stratton - If you don't like my answer and have a better one, why won't you answer the question? Comments are for clarifying the question, not answering it.


text:
how to make this work auto on off led with fading
I'm working on a project with Arduino to make LED timer with fading feature. After doing some research finally I wrote some code but it's not working until now
P.S i don't have any knowledge in coding at all T_T
Edit: Adding more details about the issue;
when trying to check upload this error is always shown.
Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

\SunRisetimer.ino: In function 'void loop()':

SunRisetimer:55: error: 'startOff' was not declared in this scope

     startOff();
\SunRisetimer.ino: In function 'void startOn()':

SunRisetimer:89: error: variable or field 'startOff' declared void

 void startOff

SunRisetimer:91: error: expected '}' before ';' token

analogWrite(uled, 1);

SunRisetimer:116: error: expected '}' at end of input

 }
exit status 1
'startOff' was not declared in this scope

Code:
#include <DS3231.h> //Include the clock library

// Changable Vars
int fadeTimeOn = 30; // How long the light will fade to max
int fadeTimeOff = 30; // How long the light will fade to min
int setHourOn = 9; // Set hours to wake (military time)
int setMinOn = 15; // Set minute to wake
int setHourOff = 9; //set off h
int setMinOff = 30; //
int uled = 9; // Set pinout with with PWM

// Set up Vars
DS3231  rtc(SDA, SCL);
Time t;
void start();

void setup()
{
  pinMode(uled, OUTPUT);
  Serial.begin(9600); // Match to serial monitor
  rtc.begin();
}

void loop()
{
  t = rtc.getTime(); // Make a time class called 't'

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

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

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

  if (t.hour == setHourOn && t.min == setMinOn) // Check if it's time to wake up!
  {
    startOn();
  }

  // Wait one second before repeating
  delay (1000);

 if (t.hour == setHourOff && t.min == setMinOff) // Check if it's time to off!
  {
    startOff();
  }

  // Wait one second before repeating
  delay (1000);
}

void startOn()
{
  // Fix for SB LED
  analogWrite(uled, 1);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 2);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 3);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 4);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 4);
  delay((fadeTimeOn * 60000)/50);
  analogWrite(uled, 5);
  delay((fadeTimeOn * 60000)/50);

for (int i = 6 ; i <= 255; i++)
    {
    analogWrite(uled, i);
    delay(((fadeTimeOn * 60000)/306));
    Serial.print(" mil sec ");
    Serial.print(((fadeTimeOn * 60000)/306));
    Serial.print(" PWM " );
    Serial.print(i);
    {
}

void startOff
{
  analogWrite(uled, 1);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 5);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 4);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 3);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 2);
  delay((fadeTimeOff * 60000)/50);
  analogWrite(uled, 1);
  delay((fadeTimeOff * 60000)/50);

  // Fade script
  for (int i = 6 ; i <= 255; i++)
  {
    analogWrite(uled, i);
    delay(((fadeTimeOff * 60000)/306));
    Serial.print(" mil sec ");
    Serial.print(((fadeTimeOff * 60000)/306));
    Serial.print(" PWM " );
    Serial.print(i);

  }

}

"it's not working" is not a useful description of the problem. Please edit your question to provide specific details.

sorry for not gifting the complete information :) error log put in the post now

What you have are compiling errors, not "problems making it fade". For example, you need to put "()" when declaring the startOff function. Things like that, elementary syntax.

I'm voting to close this question as off-topic because this is not a programming school.

Look at your function definitions:
void startOn() // works
void startOff    // doesn't work

You are missing the () after startOff.

great its work even tough its not dim out and off but it make me one step ahead. thanks


text:
Problem to display Ntp time on an oled using U8G2 lib
So I have this code to get ntp time and display it on serial port. But I want to display it on a 1.30 inch I2C oled with a SH1106 controller using the U8G2 library. The only problem is I don't know the correct syntax. I have tried
Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs
per day)
int ho = ((epoch  % 86400L) / 3600+9);
itoa(ho,hours,10);
u8g2.clearBuffer();         // clear the internal memory
u8g2.setFont(u8g2_font_ncenB14_tr); // choose a suitable font
u8g2.drawStr(0,20,hours);

and also
{
u8g2.setFont(u8g2_font_ncenB14_tr);
u8g2.firstPage();
do {
u8g2.setCursor(0, 20);
u8g2.print(hours,DEC);
u8g2.setCursor(33, 20);
u8g2.print(minutes,DEC);
}
while ( u8g2.nextPage() );
}

This is my code
//This is a code to display ntp time using Nodemcu

#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

U8G2_SH1106_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);

char ssid[] = "123456";     //  your network SSID (name)
char pass[] = "123456";     // your network password

//Your UTC Time Zone Differance  India +5:30
char HH = 5;
char MM = 30;

unsigned int localPort = 2390;      // local port to listen for UDP packets

//* Don't hardwire the IP address or we won't get the benefits of the pool.
//* Lookup the IP address for the host name instead */

//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server

IPAddress timeServerIP; // time.nist.gov NTP server address

const char* ntpServerName = "time.nist.gov";

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes
// of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing
//packets

// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;

                              //SETUP

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

// We start by connecting to a WiFi network
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);

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

Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.println("Starting UDP");
udp.begin(localPort);
Serial.print("Local port: ");
Serial.println(udp.localPort());
}

//  Send an NTP request to the time server at the given address

unsigned long sendNTPpacket(IPAddress& address)
{
Serial.println("sending NTP packet...");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);

// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011;   // LI, Version, Mode
packetBuffer[1] = 0;     // Stratum, or type of clock
packetBuffer[2] = 6;     // Polling Interval
packetBuffer[3] = 0xEC;  // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12]  = 49;
packetBuffer[13]  = 0x4E;
packetBuffer[14]  = 49;
packetBuffer[15]  = 52;

// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:

udp.beginPacket(address, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();

u8g2.begin();
}
                              //LOOP

void loop()
{
char hours;
char minutes;
char seconds;

// get a random server from the pool
WiFi.hostByName(ntpServerName, timeServerIP);

sendNTPpacket(timeServerIP);

// send an NTP packet to a time server
// wait to see if a reply is available
delay(1000);

int cb = udp.parsePacket();
if (!cb) {
Serial.println("no packet yet");
}
else {
Serial.print("packet received, length=");
Serial.println(cb);

// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);

// now convert NTP time into everyday time:
Serial.print("Unix time = ");
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);

// print the hour, minute and second:
minutes = ((epoch % 3600) / 60);
minutes = minutes + MM; //Add UTC Time Zone

hours = (epoch  % 86400L) / 3600;
if(minutes > 59)
{
hours = hours + HH + 1; //Add UTC Time Zone
minutes = minutes - 60;
}
else
{
hours = hours + HH;
}

Serial.print("The UTC time is ");       // UTC is the time at Greenwich //Meridian (GMT)

Serial.print(hours,DEC); // print the hour (86400 equals secs per day)
Serial.print(':');

if ( minutes < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print(minutes,DEC); // print the minute (3600 equals secs per minute)
Serial.print(':');

seconds = (epoch % 60);
if ( seconds < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(seconds,DEC); // print the second
}
// wait ten seconds before asking for the time again
delay(10000);
}

Adding the second block of code (print one) to the main code gives me correct time on the oled screen but only when the ntp receives a packet. Otherwise its some 10 digit number. How do I get rid of the number and keep displaying the time till it is update with a valid newer value. I have attached images of display.

Code has many sintax errors, none like the ones you describe. Try again: compile the same code you posted, and edit your question to include the actual error message

More generally, you should reduce your code to a minimal, complete, verifiable example example.

Edited. It compiles now.

The title of your question  and most of the first part as nothing to do with your problem (only receive one UDP packet). Please, edit your question to deleted the non related parts (u8g2) and correct your title

EDIT: I checkout Internet access is working OK. Problem is the server.
Your sketch works well (after some refactoring) against my local LAN NTP server and ntp.shoa.cl, but not against time.nist.gov, the one in your sketch.
It looks like the NTP server time.nist.gov itself is having problems. ntpdate reports:
> look@gear ~/Downloads/mover $ ntpdate -q time.nist.gov server
> 129.6.15.28, stratum 0, offset 0.000000, delay 0.00000 11 Feb 13:11:05 ntpdate[5855]: no server suitable for synchronization found

so that may explain that your code fails.
Anyway, I refactored your code before testing before delays are source of all kind of problems. I run OK at the first test.
I only modify loop; everything else is the same. I made it a state machine with three states: idle, your are reading to send an UDP packet; reading, you are trying to read the answer; and waiting, where you spend 10 seconds doing nothing.
I also move all printing to a new processPacket function, to keep loop short and easy to read.
Never use delay(). Use the scheme provide here to wait using millis().
void loop() {
    enum st {idle, reading, waiting};
    static st status;
    static unsigned long prev = 0;
    unsigned long now = millis();

    switch(status) {
    case idle:
        // get a random server from the pool
        WiFi.hostByName(ntpServerName, timeServerIP);

        sendNTPpacket(timeServerIP);
        status = reading;
        prev = now;
        break;

    case reading:
        if(now - prev > 1000L) {
            int cb = udp.parsePacket();

            if(cb) {
                status = idle;
                Serial.print("packet received, length=");
                Serial.println(cb);
                processPacket();
            } else {
                Serial.println("no packet yet");
            }

            prev = now;
        }

        break;

    case waiting:
        if(now - prev > 10000L) {
            status = idle;
            prev = now;
        }
    }
}

void processPacket()
{
    char hours;
    char minutes;
    char seconds;

    // We've received a packet, read the data from it
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);

    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = ");
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);
    // print the hour, minute and second:
    minutes = ((epoch % 3600) / 60);
    minutes = minutes + MM; //Add UTC Time Zone
    hours = (epoch  % 86400L) / 3600;
    if(minutes > 59) {
        hours = hours + HH + 1; //Add UTC Time Zone
        minutes = minutes - 60;
    } else {
        hours = hours + HH;
    }
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich //Meridian (GMT)
    Serial.print(hours,DEC); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if(minutes < 10) {
    // In the first 10 minutes of each hour, we'll want a leading '0'
        Serial.print('0');
    }
    Serial.print(minutes,DEC); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    seconds = (epoch % 60);
    if(seconds < 10) {
        // In the first 10 seconds of each minute, we'll want a leading '0'
        Serial.print('0');
    }
    Serial.println(seconds,DEC); // print the second
    u8g2.setFont(u8g2_font_ncenB14_tr);
    u8g2.firstPage();
    do {
       u8g2.setCursor(0, 20);
       u8g2.print(hours,DEC);
       u8g2.drawStr(25, 17,":");
       u8g2.setCursor(33, 20);
       u8g2.print(minutes,DEC);
       }
    while(u8g2.nextPage());
  }

And this is the output:

Thanks for the feedback. Can you please also show me how do I display it on the oled using u8g2 lib?? I tried
{ u8g2.setFont(u8g2_font_ncenB14_tr);                            u8g2.firstPage();                                                                                do { u8g2.setCursor(0, 20); u8g2.print(hours,DEC);                                             u8g2.drawStr(25, 17,":"); u8g2.setCursor(33, 20);  u8g2.print(minutes,DEC); }  while ( u8g2.nextPage() ); }but it says hours was not declared in this scope

@Akshayk420. Put it at the end of processPacket(). I edited the answer to include that.


text:
Arduino keeps blinking when LED is in high
I have implemented a very simple program that turns a LED off when a switch is pressed.
My code works, but, when the LED is in high state, the LED blinks fast then turns off.
When I try to use the switch, the LED lights up without me even touching the switch. It seems like there is an invisible current that flows.
Observing carefully, I found out that the body of my laptop is probably causing this issue. My laptop has a metal body.
Since my Arduino is powered via USB from my Laptop, on "HIGH" state and I touch the body of my laptop, the LED turns off but when I let go of my laptop, the LED turns back on but blinks very fast.
Pushing the switch button, turns off the LED but when I release the button, the LED lights up but blinks very fast again.
I tried using a power adapter set to 12V but it just lights up the LED on the arduino board but not the LED on the breadboard.
I tried plugging the USB to a desktop, it lights up the LEDs on the arduino board but not the LED on the breadboard as well.
The schema is like below.

My code works. It's just the rapid blinking stuff. Is it the static electricity or noise or something that is causing this issue?
const int ledPin = 13;
const int buttonPin = 7;

int buttonState = 0;

void setup(){
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if(buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    Serial.println("LED ON +++++++++++");
  }
  else{
    digitalWrite(ledPin, LOW);
    Serial.println("LED OFF ------------");
  }
}

Post a schematic of your connection.

Please see the update above.

My code works, but, ... - please post that code.

I can actually see in my serial command that the "LED ON +++++++" then immediately goes to  "LED OFF ----------". This goes on and on when I am not touching the switch.

Try making buttonPin INPUT_PULLUP. And get rid of that resistor between the button and earth (what is that for?).

@NickGammon, it is a button which signals HIGH if pressed and needs pull-down to signal LOW. I know it is stupid, but the tutorials teach this https://www.arduino.cc/en/Tutorial/Button

@stackquestions, always use this button connection https://www.arduino.cc/en/Tutorial/InputPullupSerial

I am just following a tutorial and trying to figure things out. Thank you @Nick. Your suggestion worked!

The schema is like below.  Is it like that, or is it actually that?

This weird behavior sound a lot like a floating input. Double check the connections on the pull-down resistor you are using. Try wiggling the wires in the breadboard. Sometimes you get a bad connection in a breadboards. Also note that some breadboards don't have the blue and red lines connected all the way, but have a split in the middle (though that's not applicable if your wiring is exactly the way is shown in the picture).

The input impedance of a digital pin is extremely high. When something changes if you touch something or move your hand, that is an indication of a floating input pin. I prefer that all inputs and outputs have a GND connection, therefor I prefer that one side of the button is connected to GND, and the other one with INPUT_PULLUP or an extra pullup resistor.

@Juraj I know it is stupid, but the tutorials teach this arduino.cc/en/Tutorial/Button - that page shows a Fritzing picture which does not match the schematic further down the page. On the schematic the resistor is in a different place.

remove the ground wire to the LED.  use the busbar ground for the LED (same as the switch) .... the arduino already has an LED on pin 13, use that


text:
Servo causes disconnection
I've only started using Arduino in the last week, and I'm having a problem with the servo supplied with the kit I purchased. It's a SG90 microservo. I'm trying to connect the servo as shown on the Arduino tutorial site:

But when I connect the power and ground pins to the board, the board powers down and disconnects from the USB. I've had the servo working before without a problem.
Yesterday I was trying out another tutorial without any luck, and I noticed the servo getting hot (not too hot to touch though).
Could I have accidentally fried the control board in the servo?

Probably. It sounds like it's causing the power to short.

Never run power to a servo or other motor through an Arduino or from its regulator.  Also do not power servos from USB.

@ChrisStratton Nice information. I think I do that mistake for several times. Cares to elaborate?

@ChrisStratton I don’t think I did. What would that look like?

@Jim421616 It would look like your schematic.

Oh! But that schematic is from the tutorial!

Have a look at the current requirements of the SG90 and compare this to the maximum current available from an Arduino Uno.

Another thing to look at is how much current your computer's USB port can supply. My laptop, for example, can only supply 500mA per USB port.
My advise is to use a separate 5V power supply for the servo.

So the technique I used should be ok if I power the board with a 9V battery rather than through the USB?

There's a couple of problems with that idea. If you are talking about an everyday alkaline 9V battery with an approximate mA hour rating of 580, and you draw the SG90's "running current" of approximately 270mA from it, how long do you think the battery will last?

If your Arduino has a AMS1117 voltage regulator, then it's maximum power dissipation specification is 1.2W. Supplying 9V at the power input jack will give you a maximum output current of approximately 360mA. (9 - .7 - 5) * .360 = 1.19W. The "stall current" of the SG90 is up to 730mA, more than double the current you have available. A separate, 1A, 5V power supply is what I would use.

I'm sorry to harp on about it, but pretty much all of the tutorials I've been able to find online suggest hooking up the servo in the way I originally posted about. I guess maybe I hooked it up incorrectly, but as far as I can tell, you're all advising against this method anyway. So I'm confused; is this a good way to hook up the servo, or not? And if not, what would the best way look like in a schematic?

Unfortunately, there are several tutorials on the internet showing the servo connected directly to an Arduino Uno, which is incorrect. Here is a tutorial with a connection diagram showing a separate power supply for the servo in Step 3: http://www.instructables.com/id/Arduino-How-to-Use-a-Servo-Motor-With-an-External-/


text:
AVR-Toolchain for Arduino crashes on Mac OSX 10.11.6: Hints or debugging help needed
My Arduino IDE does not compile any project since I updated from Mac OSX 10.6.8 to 10.11.6.
I even tried reinstalling and also manually installing the original AVR-toolchain. But the behaviour did not change.
I still get the following error messages
signal: bus error
Fehler beim Kompilieren für das Board Arduino/Genuino Uno.

English translation of the error message is:
Error compiling for board Arduino/Genuino Uno.

Is this problem known? I could not find information about it.
Are there any known solutions to it?
Can I start Arduino IDE in debug
mode to give some usefull output what exactly causes the crash?

EDIT
I am using the current IDE 1.8.5 and also tried the nightly builds. I also tried some older versions down to 1.6.0.
EDIT 2:
Arduino 1.0.5 produces the following error:
cc1plus: internal compiler error: Segmentation fault: 11
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://gcc.gnu.org/bugs.html> for instructions.

Thanks for your help!
EDIT 3
After installing UECIDE (what went smoothly) I am facing the same problem. The error happens in the AVR toolchain when calling the avr-gcc 4.9.2 compiler. In UECID the output tab shows the following output (I added linebreaks for readability):
~/Library/uecide/compilers/avr-gcc/bin/avr-g++
  -c /var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-faf1be1e-2186-438b-9e1a-c56f50ce26d1/MySource.cpp
  -o /var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-faf1be1e-2186-438b-9e1a-c56f50ce26d1/MySource.cpp.o
  -mmcu=atmega328p -g -std=gnu++11 -fno-threadsafe-statics
  -fno-exceptions -ffunction-sections -fdata-sections
  -DF_CPU=16000000L -DARDUINO=106 -DARDUINO_UNO -DARDUINO_ARCH_AVR
  -I~/Library/uecide/cores/arduino/arduino
  -I~/Library/uecide/boards/Arduino/arduino-uno
  -I/var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-faf1be1e-21
86-438b-9e1a-c56f50ce26d1
  -I~/pro/Arduino/MySource -Os -w

The status tab of UECID only shows Compiling Failed.
EDIT 4
After starting UECID from console with --debug --verbose options specified it did print the failing command to console:
~/Library/uecide/compilers/avr-gcc/bin/avr-g++
   -c /var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-5ccb5f12-fcd1-4893-8c41-39fc056ec544/MySourve.cpp
   -o /var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-5ccb5f12-fcd1-4893-8c41-39fc056ec544/MySourve.cpp.o
   -mmcu=atmega328p -g -std=gnu++11 -fno-threadsafe-statics
   -fno-exceptions -ffunction-sections -fdata-sections
   -DF_CPU=16000000L -DARDUINO=106 -DARDUINO_UNO -DARDUINO_ARCH_AVR
   -I~/Library/uecide/cores/arduino/arduino
   -I~/Library/uecide/boards/Arduino/arduino-uno
   -I/var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-5ccb5f12-fcd1-4893-8c41-39fc056ec544
   -I~/pro/Arduino/MySourve -Os -w

This command is identical to the one created by Arduino.
I found another hint on a bug in gcc 4.8 that seems not to be AVR specific.
After reducing the command line to
~/Library/uecide/compilers/avr-gcc/bin/avr-g++
  -c /var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-5ccb5f12-fcd1-4893-8c41-39fc056ec544/MySource.cpp
  -o /var/folders/2h/8pdnzj197tq906bzs81ksn6m0000gn/T/build-5ccb5f12-fcd1-4893-8c41-39fc056ec544/MySource.cpp.o

the crash stays the same: Segmentation fault 11

Arduino IDE version? Maybe is time to try UECIDE (http://uecide.org)

I run 10.13.3 without any problem. Suggest to update the IDE. You can read also this article to use TextWrangler or BBEdit as editor with direct link to compile, assemble and so on. https://feroce-lapin.blogspot.com.br/2017/12/arduino-et-bbedit-textwrangler.html

I just tried the arduino web IDE. Strangely this crashes on uploading the sketch with avrdude. If I copy paste the command to a terminal window it runs and program is flashed to arduino board.

@Look Alterno: I am using the current IDE 1.8.5 and also tried the nightly builds. I also tried some older versions down to 1.6.0

There are a lot of older versions of the IDE on the Arduino web site. I don't think it particularly matters which one you use. Try using an earlier one.

When you try re-installing the IDE, make sure you clear out any old preferences that may be referencing any manually installed toolchain that may not be correct. Especially at /Users/(username)/Library/Arduino15

I have done so.

Do you happen to have any anti-virus software running which might be blocking the compiler?

I also thought about this possibility. I use Intego VirusBarrier. I deactivated the real time protection, no change.

What about your source? Does it have any multi-byte characters (Unicode)? Call any external libraries?

It seems to happen with any source. e.g "blink" example from arduino


text:
How do I get multiple readings(binary) based on my arduino output?
I am new to arduino and therefore not much experience in handling codes, please be forgiving and help me!
For my school project, make use of arduino to make 4 capacitive sensors (which has already been successful). Now I am trying to make use of the 4 sensors to be shown in a table format(one for each output) so that I can use that data to be plotted into either Excel or Matlab. Hence I would like to ask how do I group up my data into different columns? Also is it possible to get convert my results into binary format so that it would be easier when trying to plot the data?
My arduino code is here:
#include <CapacitiveSensor.h>

CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4); // 1M resistor between pins 4 & 8, pin 8 is sensor pin, add a wire and or foil
CapacitiveSensor   cs_5_7 = CapacitiveSensor(5,7);
CapacitiveSensor   cs_8_10 = CapacitiveSensor(8,10);
CapacitiveSensor   cs_11_13 = CapacitiveSensor(11,13);
void setup()
{
   cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);// turn off autocalibrate on channel 1 - just as an example
   cs_5_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_8_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
   cs_11_13.set_CS_AutocaL_Millis(0xFFFFFFFF);
 Serial.begin(9600);
   pinMode(3,OUTPUT);
   pinMode(6,OUTPUT);
   pinMode(9,OUTPUT);
   pinMode(12,OUTPUT);
}

void loop()
{
 long sensor1 =  cs_2_4.capacitiveSensor(50);
 long sensor2 =  cs_5_7.capacitiveSensor(50);
 long sensor3 =  cs_8_10.capacitiveSensor(50);
 long sensor4 =  cs_11_13.capacitiveSensor(50);

Serial.println(sensor1);  // print sensor output
    Serial.print("\t");
    Serial.println(sensor2);
    Serial.print("\t");
    Serial.println(sensor3);
    Serial.print("\t");
    Serial.println(sensor4);
 if(sensor1 >= 1000)
   {
    digitalWrite(3,HIGH);
   }
  else{
    digitalWrite(3,LOW);
   }
     if(sensor2 >= 1000)
   {
    digitalWrite(6,HIGH);
   }
   else{
    digitalWrite(6,LOW);
   }
    if(sensor3 >= 1000)
   {
    digitalWrite(9,HIGH);
   }
   else{
    digitalWrite(9,LOW);
   }
    if(sensor4 >= 1000)
   {
    digitalWrite(12,HIGH);
   }
   else{
    digitalWrite(12,LOW);
   }

   }

And with that code above the output I receive when I use the serial monitor is:

Serial.println() add a CR/LF after printing.

Serial.println(sensor1);  // print sensor output
Serial.print("\t");
Serial.println(sensor2);
Serial.print("\t");
Serial.println(sensor3);
Serial.print("\t");
Serial.println(sensor4);

If you want 4 columns don't use println for each number, as that starts a new line.

Also is it possible to get convert my results into binary format so that it would be easier when trying to plot the data?

Yes it's possible however I don't see how that makes anything easier.

Changing the println function really worked for me thank you! I prefer to change the codes into binary so that it could help with my data plotting (possibly graph). What kind of code could I use to change it into binary?

@JonnyL That's another, different question.


text:
Is there a way to play .mp3 files from an SD card on Arduino?
Is there a way to have mp3 files on an SD card in the SD card shield for the Arduino and play an mp3 file on that SD card with a buzzer?
If possible also with something like:
playmp3(thismp3.mp3);

So that if I execute that command, the Arduino will play thismp3.mp3 through a buzzer.
Thank you.

That will sound horrible, but with today's music probably makes no difference. Have a look at https://maker.pro/projects/arduino/arduino-audio-player/

it's going to be much simpler to play .wav files from the sd card

You can easily play .wav files because they are basically the sound levels recorded with a certain frequency. Here's a guide how to make an .wav music player: tutorial

If you're not specifically trying to make the arduino itself do the decoding and playback, you can get something like the Mini DFPlayer which would let you do essentially what you're asking for and offloads the decoding and playback so your arduino can do something else while the audio is playing.

It's not as easy as that. The SD card and playing audio are two different things.
However, probably the easiest way is to buy an MP3 shield (but that spoils the fun to make it yourself).
On the other hand, to make it yourself, takes quite some effort.
Also, the audio quality will be very low.
Besides that, decoding MP3 is far from trivial.
In case you want to make it yourself:

First write a program to read (stream) bytes from the SD card
Write an MP3 decoder (maybe/probably there are open source variants)
Forward the MP3 bytes to the decoder
Forward the audio bytes to the buzzer

Of course, there are time constraints otherwise you hear gaps in the music.

MP3 decoder on an Uno...? I think not. Maybe on a Due (I ported one to the PIC32 for chipKIT a while back, and it kinda worked), but not an Uno. Not enough memory. I used to run MAD on a 25MHz Sun SPARC system, but that had megabytes of RAM, not a couple of kilobytes. For an Uno external hardware is a requirement, not an option.

Note that it is possible to add memory to an Uno ... I did a test with a 23LC1024 and it worked. Slower than internal memory, but it worked.  But I agree, the speed might be a problem too (that's why I made the time constraint remark). I don't know exactly what the requirements are for MP3 decoding, looks like more than the Uno can process.

You're not adding memory to the Uno there - you're adding an external peripheral that happens to have memory. Adding memory to the Uno would entail including it in the memory map so you can use it for variables, etc - something the AVR doesn't support. Yes, you could offload some data into there for storage, but you can't process it while it's in there. It wouldn't just be slow - it'd be unusable for audio processing. Yes, the technology is SRAM, but in actuality it's more like an SD card or hard drive.

True ... that's also the reason I didn't use it in my project. Because i had to make my own 'memory map' from variables to external SRAM.
For MP3, I thought it could be used to store a small chunk of decoded data and to process it to undecoded data. But yes, it will not be advantage for the limited CPU speed of a Uno anyway.

@Majenko. It look like the good old days with extended memory and expanded memory and all sort of trick around the 640KB barrier.

Yeah - the difference between page mapping (hardware implementation) and page swapping (software implementation). For the former you need the chip to have external memory in the first place, so you can switch in and out different physical banks of memory (like the C= 64, Spectrum +2/3, etc did to get round the 64k limit). For the latter the chip has to have an MMU or some similar form of page fault mechanism to implement a virtual memory map. Neither of those are available in the AVR... ;)

@Majenko my initial plan was to store some arrays in external SRAM. That is easy to reference from a pointer stored in Uno's SRAM. However, I needed linked lists and lots of small objects, so it is too complicated. So what I intended was some kind of 'user made' MMU). A bit too much outside the scope of the project (which I still wonder if I will finish it, even on STM32). But meanwhile I learn a lot doing side tests for my hobby projects, also thanks to your comments (so thanks again). Sorry for thiss off-topic comments.

I believe MP3 uses licensed software that is implemented on decoder chips like VS1053.
Usually one would use a board like this, with an SD card for holding the massive amount of info that makes a sound.
http://www.oddwires.com/mp3-decoder-module-vs1053-for-arduino/?gclid=EAIaIQobChMInKS7lJGm2QIVE4_ICh1kTQa4EAQYAiABEgIKH_D_BwE
You then send commands to the unit to tell it to start, stop, advance, etc.