text:
Format Integer in Arduino
How to format an integer as 3 digit string? If I give 3 formated string should be 003
printf("%03d\n", 3); // output: 003

This doesn't work in Arduino.

You can use sprintf with a char array buffer and then pass it to Serial.print().

Thanks its worked,
'char buff[3];
sprintf (buff,"%03d",3);
Serial.print(buff);'

Rather use char buff[4] as you need one byte for the terminating zero that will be added by sprintf. If you don't, it may overwrite some value in your stack, leading to hard to understand problems.

Or you could setup printf() to print through Serial. This way you don't have to allocate room for sprintf(), which can be (as you just experienced) error prone.

BTW, you will need more than 4 chars if the number you print happens to be less than -99 or more than 999. With buffer[7] you can safely print any int, and with buffer[12] you can print any long.

See this if you have a lot of strings and don't want them using up the limited amount of RAM.  https://www.arduino.cc/en/Reference/PROGMEM

The standard C function printf print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.
Instead of printf, use snprintf. It prints to a char array, which you later can use with Serial.print, or whatever other function that take a string.
void setup() {
  Serial.begin(9600);
  while(!Serial);

  char buffer[4];
  snprintf(buffer,sizeof(buffer), "%03d", 3);
  Serial.println(buffer);
}

void loop() {

}

Note: all the comments apply to this answers.


text:
Dual OLED displays showing the same image via SPI?
Is it possible to connect two oled displays via SPI to my Uno and send a single image to both displays, with each refreshing at an identical rate?
I have gotten a single oled display (SSD1306) to work using the U8g2 library, however i am not sure which pins can be shared in a dual display setup. There are no CS pin on my displays, only GND, VCC, SCL, SDA, D/C, and RST.
thanks!

Those displays use I2C, not SPI.

Here is a link to the displays I purchased: http://www.ebay.com/itm/141494092860?ul_noapp=true
I have a single screen running using the 4 Wire SPI bus setup in the U8g2 lib, is that possible if the displays are I2C? I'm new to this, so honest question...

My bad. The labeling made me think it was I2C, but apparently it support both I2C and SPI. Since in 4 wire SPI, you can only write to the display, and not read, I don't see why you shouldn't be able to connect two displays. Just connect all six lines in parallel.

source: Stack Exchange

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

sort: votes


text:
ESP8266 Timing question / Do something in 2 seconds even
I am able to synch my ESP8266 running on Arduino core with the time.nist.gov-Server but how can I achieve to trigger i.e. a digital pin in 2 seconds even? What I mean is that following:

The MC recieves the signal for trigger by the user on 09:25:18:312
It waits until it is exactly 09:25:19:000
It triggers the digital out on +2 seconds, on 09:25:21:000

Thanks!!
Edit: Corrected Times.

The description isn't clear.  Where did time 09:25:18:312 come from?  If that's the time the request was issued, step 2 won't work out.  Why is step 2 included anyway?

Also, the time in step 2 is later than the time in step 1. You can't wait for something in the past, so that confuses it more.

Sorry that I didn't make that clear.  What I meant was, that there is a (fictional) time and I want the ESP to wait for a specific time. I correct the upper values. Sorry!

You can, but I think you are probably not looking at the best solution.  This link has details of how to program the "OS" timer http://www.switchdoc.com/2015/10/iot-esp8266-timer-tutorial-arduino-ide/ I haven't tried it, I'm not even sure it will work, but...
The fact that setting the timer interval to 2uS causes issues with the WIFI implies that it might not be accurate enough for your purposes.  It might be better to use "something" to trigger a HW interrupt.  From the moment the interrupt triggers to the moment the signal is sent out on the pin is a calculable finite time, so rather than 2,000,000 uS you want the event to trigger after 1,999,524uS (that's a made up number).
Of course if you are using a device that can trigger a pin on the ESP8266 there is no reason it can't trigger the 'output' pin, without involving the ESP at all.
You could use an RTC DS3221(?), the ESP sets the time on the RTC and then sets the alarm.  The alarm interrupt pin is connected to the ESP and it relays the signal to the output, or the alarm interrupt pin is directly connected to the output pin.  The limiting factor here is the accuracy you require.

Probably yes. Is there a way to synch multiple RTC on different ESPs? As far as I know, the ESP-variant of the time.h library does not include the WiFi-Signal-lag.

Have a look at NTP implementation (Network time protocol) if you want to do that, but it might be better to have only one RTC and then calculate the average hop time between the master and slaves.

Indeed. the Arduino Core Library Time.h has a functions for synchronising time from an external time source: setSyncProvider(getTimeFunction) and setSyncInterval(interval) See: https://github.com/PaulStoffregen/Time

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


text:
Read data from arduino once only serial communications (jSSC)
I am trying to get the UID of RFID from Arduino to netbeans. I was able to display it to a textfield, but once another rfid was scanned, it is displayed together with the UID from the prev scan. How do I stop Arduino to send data so the only thing displayed in the textfield was the first UID scanned.
Here is Arduino code:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_PIN          10         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
    Serial.begin(9600);     // Initialize serial communications with the PC
    while (!Serial);        // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init();     // Init MFRC522

    //mfrc522.PCD_DumpVersionToSerial();    // Show details of PCD - MFRC522 Card Reader details
    //Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
    // Look for new cards
  String code = "";
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
  for (byte i = 0; i < mfrc522.uid.size; i++) {
      code += String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" :" ");
      code += String(mfrc522.uid.uidByte[i], HEX);
  }
  code.toUpperCase();
  Serial.println(code);
  mfrc522.PICC_HaltA();
}

Only the first card scanned or the current card being scanned?

the first scanned

I'm voting to close this question as off-topic because the problem is with the PC code, no the Arduino

Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.
The fault is with the receiving java code, pump test data into that to see what is wrong.


text:
Arduino Nano BME280 weird values
My goal is to measure temperature, pressure and humidity using my Arduino Nano and the BME280 (GY-BME/P280).

To do this I use this library from SparkFun and that works almost. What I notice is probably invalid values for temperature and no humidity values at all.
The PINs:

GND -> GND
VCC -> 3.3V
SDO -> D12
CSB -> D10
SDA -> D11
SCL -> D13

I have noticed that I can unplug the VCC pin, it makes to difference to the measurements. I find that odd.
And I have noticed that the results are the same for 5V to VCC.
This is the result, I have tested this with I2C and SPI, it's the same:
Program Started
Starting BME280.Program Started
Starting BME280... result of .begin(): 0x58
Displaying ID, reset and ctrl regs
ID(0xD0): 0x58
Reset register(0xE0): 0x0
ctrl_meas(0xF4): 0x27
ctrl_hum(0xF2): 0x0

Displaying all regs
0x80:9A 70 90 28 92 2D AF 00 76 6F 7D 67 32 00 93 8C
0x90:C1 D6 D0 0B CF 18 AD FF F9 FF 8C 3C F8 C6 70 17
0xA0:00 45 82 00 00 00 00 00 00 00 00 00 33 00 00 C0
0xB0:00 54 00 00 00 00 60 02 00 01 FF 82 13 4E 08 00
0xC0:00 87 27 FF 00 00 00 00 00 00 00 00 00 00 00 00
0xD0:58 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0xE0:00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0xF0:00 00 00 0C 27 00 00 58 DD 00 82 72 00 00 00 00

Displaying concatenated calibration words
dig_T1, uint16: 28534
dig_T2, int16: 26493
dig_T3, int16: 50
dig_P1, uint16: 35987
dig_P2, int16: -10559
dig_P3, int16: 3024
dig_P4, int16: 6351
dig_P5, int16: -83
dig_P6, int16: -7
dig_P7, int16: 15500
dig_P8, int16: -14600
dig_P9, int16: 6000
dig_H1, uint8: 69
dig_H2, int16: 0
dig_H3, uint8: 0
dig_H4, int16: 0
dig_H5, int16: 0
dig_H6, uint8: 0

Temperature: 24.59 degrees C
Temperature: 76.26 degrees F
Pressure: 101121.63 Pa
Altitude: 18.25m
Altitude: 59.87ft
%RH: 0.00 %

My script is almost exactly like the example from the library.
/******************************************************************************
I2C_ReadAllData.ino
BME280 Arduino and Teensy example
Marshall Taylor @ SparkFun Electronics
May 20, 2015
https://github.com/sparkfun/SparkFun_BME280_Arduino_Library

This sketch configures the BME280 to read all measurements.  The sketch also
displays the BME280's physical memory and what the driver perceives the
calibration words to be.

Resources:
Uses Wire.h for I2C operation
Uses SPI.h for SPI operation

Development environment specifics:
Arduino IDE 1.6.4
Teensy loader 1.23

This code is released under the [MIT License](http://opensource.org/licenses/MIT).
Please review the LICENSE.md file included with this example. If you have any questions
or concerns with licensing, please contact techsupport@sparkfun.com.
Distributed as-is; no warranty is given.
******************************************************************************/

#include <stdint.h>
#include "SparkFunBME280.h"
//Library allows either I2C or SPI, so include both.
#include "Wire.h"
#include "SPI.h"

//Global sensor object
BME280 mySensor;

void setup()
{
  //***Driver settings********************************//
  //commInterface can be I2C_MODE or SPI_MODE
  //specify chipSelectPin using arduino pin names
  //specify I2C address.  Can be 0x77(default) or 0x76

  //For I2C, enable the following and disable the SPI section
  //mySensor.settings.commInterface = I2C_MODE;
  //mySensor.settings.I2CAddress = 0x76;

  //For SPI enable the following and dissable the I2C section
  mySensor.settings.commInterface = SPI_MODE;
  mySensor.settings.chipSelectPin = 10;

  //***Operation settings*****************************//

  //renMode can be:
  //  0, Sleep mode
  //  1 or 2, Forced mode
  //  3, Normal mode
  mySensor.settings.runMode = 3; //Normal mode

  //tStandby can be:
  //  0, 0.5ms
  //  1, 62.5ms
  //  2, 125ms
  //  3, 250ms
  //  4, 500ms
  //  5, 1000ms
  //  6, 10ms
  //  7, 20ms
  mySensor.settings.tStandby = 0;

  //filter can be off or number of FIR coefficients to use:
  //  0, filter off
  //  1, coefficients = 2
  //  2, coefficients = 4
  //  3, coefficients = 8
  //  4, coefficients = 16
  mySensor.settings.filter = 0;

  //tempOverSample can be:
  //  0, skipped
  //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
  mySensor.settings.tempOverSample = 1;

  //pressOverSample can be:
  //  0, skipped
  //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
    mySensor.settings.pressOverSample = 1;

  //humidOverSample can be:
  //  0, skipped
  //  1 through 5, oversampling *1, *2, *4, *8, *16 respectively
  mySensor.settings.humidOverSample = 1;

  Serial.begin(57600);
  Serial.print("Program Started\n");
  Serial.print("Starting BME280... result of .begin(): 0x");

  //Calling .begin() causes the settings to be loaded
  delay(10);  //Make sure sensor had enough time to turn on. BME280 requires 2ms to start up.
  Serial.println(mySensor.begin(), HEX);

  Serial.print("Displaying ID, reset and ctrl regs\n");

  Serial.print("ID(0xD0): 0x");
  Serial.println(mySensor.readRegister(BME280_CHIP_ID_REG), HEX);
  Serial.print("Reset register(0xE0): 0x");
  Serial.println(mySensor.readRegister(BME280_RST_REG), HEX);
  Serial.print("ctrl_meas(0xF4): 0x");
  Serial.println(mySensor.readRegister(BME280_CTRL_MEAS_REG), HEX);
  Serial.print("ctrl_hum(0xF2): 0x");
  Serial.println(mySensor.readRegister(BME280_CTRL_HUMIDITY_REG), HEX);

  Serial.print("\n\n");

  Serial.print("Displaying all regs\n");
  uint8_t memCounter = 0x80;
  uint8_t tempReadData;
  for(int rowi = 8; rowi < 16; rowi++ )
  {
    Serial.print("0x");
    Serial.print(rowi, HEX);
    Serial.print("0:");
    for(int coli = 0; coli < 16; coli++ )
    {
      tempReadData = mySensor.readRegister(memCounter);
      Serial.print((tempReadData >> 4) & 0x0F, HEX);//Print first hex nibble
      Serial.print(tempReadData & 0x0F, HEX);//Print second hex nibble
      Serial.print(" ");
      memCounter++;
    }
    Serial.print("\n");
  }

  Serial.print("\n\n");

  Serial.print("Displaying concatenated calibration words\n");
  Serial.print("dig_T1, uint16: ");
  Serial.println(mySensor.calibration.dig_T1);
  Serial.print("dig_T2, int16: ");
  Serial.println(mySensor.calibration.dig_T2);
  Serial.print("dig_T3, int16: ");
  Serial.println(mySensor.calibration.dig_T3);

  Serial.print("dig_P1, uint16: ");
  Serial.println(mySensor.calibration.dig_P1);
  Serial.print("dig_P2, int16: ");
  Serial.println(mySensor.calibration.dig_P2);
  Serial.print("dig_P3, int16: ");
  Serial.println(mySensor.calibration.dig_P3);
  Serial.print("dig_P4, int16: ");
  Serial.println(mySensor.calibration.dig_P4);
  Serial.print("dig_P5, int16: ");
  Serial.println(mySensor.calibration.dig_P5);
  Serial.print("dig_P6, int16: ");
  Serial.println(mySensor.calibration.dig_P6);
  Serial.print("dig_P7, int16: ");
  Serial.println(mySensor.calibration.dig_P7);
  Serial.print("dig_P8, int16: ");
  Serial.println(mySensor.calibration.dig_P8);
  Serial.print("dig_P9, int16: ");
  Serial.println(mySensor.calibration.dig_P9);

  Serial.print("dig_H1, uint8: ");
  Serial.println(mySensor.calibration.dig_H1);
  Serial.print("dig_H2, int16: ");
  Serial.println(mySensor.calibration.dig_H2);
  Serial.print("dig_H3, uint8: ");
  Serial.println(mySensor.calibration.dig_H3);
  Serial.print("dig_H4, int16: ");
  Serial.println(mySensor.calibration.dig_H4);
  Serial.print("dig_H5, int16: ");
  Serial.println(mySensor.calibration.dig_H5);
  Serial.print("dig_H6, uint8: ");
  Serial.println(mySensor.calibration.dig_H6);

  Serial.println();
}

void loop()
{
  //Each loop, take a reading.
  //Start with temperature, as that data is needed for accurate compensation.
  //Reading the temperature updates the compensators of the other functions
  //in the background.

  Serial.print("Temperature: ");
  Serial.print(mySensor.readTempC(), 2);
  Serial.println(" degrees C");

  Serial.print("Temperature: ");
  Serial.print(mySensor.readTempF(), 2);
  Serial.println(" degrees F");

  Serial.print("Pressure: ");
  Serial.print(mySensor.readFloatPressure(), 2);
  Serial.println(" Pa");

  Serial.print("Altitude: ");
  Serial.print(mySensor.readFloatAltitudeMeters(), 2);
  Serial.println("m");

  Serial.print("Altitude: ");
  Serial.print(mySensor.readFloatAltitudeFeet(), 2);
  Serial.println("ft");

  Serial.print("%RH: ");
  Serial.print(mySensor.readFloatHumidity(), 2);
  Serial.println(" %");

  Serial.println();

  delay(10000);

}

Are you connecting via I2C?  If so have you got two 4.7K resistors between SCL and VCC and SDA and VCC?

Thank you for your reply, I have placed these but it does not change the sensor behavior. There are still zero's for dig_H2 trough dig_H6 and I think there should be some value, by comparing it using Google...

The Arduino Nano is a 5V Arduino board, and the BME280 is a 3.3V sensor. You may not apply 5V signals to it. It might already be damaged, you have to buy a new sensor. I have tried the Adafruit library and the finitespace library, and chose the finitespace library: https://github.com/finitespace/BME280 I have not yet tried the Sparkfun library.

The photo of the board shows that it is for BM E/P 280. It can take either the BME280 chip which does temperature, pressure and humidity, or the BMP280 chip which only does temperature and pressure.
The Register 0xD0 contains an ID which has a value of 0x60 for the BME280 and 0x58 for the BMP280.
Your output shows the ID as 0x58 which means you have a BMP280 temperature pressure chip.
I have been sold one of these, claiming to be a BME280 chip. I shall be asking for a refund.

Welcome to Asrrduino SE.  Be sure to take the tour at https:/arduino.stackexchange.com/Tour - and earn a badge in the process.

From my experience 0x58 means BMP280, I haven't found anything else than this thread claiming that 0x58 means BMP260

I'm after getting a batch of these myself...
I can't get it working with the Adafruit libraries, but it will work with the SparkFun Ones
To get data... the wiring is, well, nonstandard.
I can't get it to work in SPI mode, but it will work in I2C mode
I'm using an Arduino mega so the pin layout is different from an uno.
Pin no|Label|Arduino pin
Pin 1 |VCC  |3.3V
Pin 2 |GND  |GND/Ground
Pin 3 |SCL  | The SCL pin, on a mega its digital 21
Pin 4 |SCA  | The SCA pin, on a mega its digital 20
Pin 5 |CSB  |Do not connect
Pin 6 |SDO  |3.3V
Weird as it sounds, it needs to be connected to power on 2 separate pins

The breakout board photo shows that it is not the original BOSCH BME280 sensor. The dimensions are off. The original is square. This is how it should look like.

You're correct. It's the BMP280.

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


text:
How to connect a digital sensor through SPI
I want to connect a ADXL355 development board accelerometer to an Arduino. I cant get any data form the sensor. The data_ready pin is never high and I can't read the registers.
The connections (user guide):
I connected VDD and VDDIO to 5V, ground to ground, DRDY to the correct pin, CS, SCLK, MOSI and MISO all to correct pins.
Code:
//modeled on https://www.arduino.cc/en/Tutorial/BarometricPressureSensor

#include <SPI.h>

const int ID = 0x00;
const int FIFO = 0x11;
const byte READ = 0b11111100;
const byte WRITE = 0b00000010;

const int dataReadyPin = 6;
const int chipSelectPin = 7;

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

    // put your setup code here, to run once:
    SPI.begin();

    // initalize the  data ready and chip select pins:
    pinMode(dataReadyPin, INPUT);
    pinMode(chipSelectPin, OUTPUT);

    delay(100);
    readRegister(ID);
}

void loop() {
    if (digitalRead(dataReadyPin) == HIGH){
        Serial.println("data ready");
        delay(500);
    }
}
void readRegister (byte thisRegister){
    byte inByte = 0 ;
    Serial.println(thisRegister, BIN);

    thisRegister = thisRegister<< 2;
    byte dataToSend = thisRegister & READ;
    Serial.println(thisRegister, BIN);
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(dataToSend);
    inByte = SPI.transfer(0x00);
    Serial.println("data: ");
    Serial.println(inByte);
}

You're shifting your address too far.

Read should be 0b00000001 not 0b00000010.
Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

byte readRegister (byte thisRegister){
    byte inByte = 0 ;
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer((thisRegister << 1) | 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}

void writeRegister (byte thisRegister, byte value){
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}

Thank you for your help. I thought it should be shifted by 2 because of the tutorial I am following... While debugging, I connected the ground pin on the 3-pin group labelled standby to ground, and it shorted out. What is the group for?

"Standby or Measurement Mode Selection Pin. Set this pin to ground to enter standby mode, or set this pin
to VDDIO to enter measurement mode. " - should do something similar to bit 0 of register 0x2d, but inverted.


text:
Demux 1 LED at a time
I have the 14051 Demux set up with an Arduino Uno R3 and I am able to light up all three LED's at once with a 1 second delay however, I want to light up 1 LED at a time how can I do this?

My Hardware Setup

Sketch

/*  Arduino sketch   */

int64_t wait= 1000;
void setup()
{
  pinMode(7,OUTPUT);
  digitalWrite(7,LOW);
  DDRB = 0b00000111;  //PORT 8,9,10 as output
  PORTB = 0b00000000; //PORT 8,9,10 set to LOW
}

void loop()
{
  PORTB=0b00000000; //Data falow - X0
  uint8_t Sensor0 =  analogRead(A0); //read data from X0
  delay(wait);

  PORTB=0b00000001;  //Data flow - X1
  uint8_t Sensor1 =  analogRead(A0); //read data from X1
  delay(wait);

  PORTB=0b00000010;  //Data flow - X2
  uint8_t Sensor2 =  analogRead(A0); //read data from X2
  delay(wait);

  digitalWrite(7,HIGH);  // Inhibit / stop all data
  delay(wait);
  digitalWrite(7,LOW);  // Inhibit /  let data flow
}

How would analogRead(A0) be able to feed current to the selected LED? Looks like a lot of cut-and-paste-programming?

The answer is the same as the one to your other question, which to me looks like a duplicate. Anyway you should not read the data from the analog pin, but rather digitalWrite(A0, HIGH);

@frarugi87 Can you post an example of this code implemented with the sketch I posted.

@MALKAVIAN in the setup write pinMode(A0, OUTPUT); digitalWrite(A0, HIGH); and in the loop remove all the lines with the analogRead (the A0 pin is already high from the setup)


text:
How to vary the frequency of a PWM sinewave with arduino uno?
I'm generating a sine wave using a table, a PWM pin and an RC filter on the output. I would like to be able to control the frequency of the sine wave, how can I do that easily?
By the way, which is the maximum frequency achievable and why? As far as my understanding goes, the limit is given by the time arduino needs in order to run the loop() function.
This is the code I am using on arduino UNO. Please point it out if this is a horrible way to generate a sine wave with arduino, and if it is, feel free to provide a better solution.
const int8_t SIN1024_DATA [] = {... data table values (1024 values) ...};
int i = 0;
void setup()
{
  pinMode(9, OUTPUT);
}

void loop()
{
  digitalWrite(9, SIN1024_DATA[i]);
  i++;
  if(i == 1024){i = 0;}
}

I haven't seen this method of generating a sin-wave. Most I've seen use a PWM pin, and analogWrite. But to get a bit more performance out of this method, i'd wrap the code inside loop, in a while(true){ ... }. Making it a few cycles faster. Secondly, don't use digitalWrite, as it's quite slow. Either use direct port manipulation, or use something like digitalWriteFast.

First thing, you must find a way to output the samples at a steady rate.
Your best bet is to use a timer. Ideally, you want to use the same timer
used for the PWM output, in order to have them synchronized. See for
example how it is done in the Mozzi sound synthesis
library.
Then you can lower the frequency by repeatedly outputting the same
value: if you output every value once, you get the “base” frequency
(sample frequency ÷ 1024). If you output each value n times you get
the base frequency divided by n. Conversely, you can get higher
frequencies by skipping samples. For example, if you output only every
other sample, you get twice the base frequency.
These two approaches can be conveniently combined in a very simple code:
you keep a phase variable and, on every sample, you increment it by an
amount proportional to the desired frequency. You then use the higher
bits of the phase as an index into your array. The lower bits then serve
only to increase the frequency resolution and allow frequencies lower
than the base one. Here is a simple implementation:
const uint8_t pin = ...;
uint8_t frequency;

// Call periodically.
static inline void output_a_sample()
{
    static uint16_t phase;
    analogWrite(pin, SIN1024_DATA[phase>>6]);
    phase += frequency;
}

This lets you set the frequency in units of the sampling frequency ÷
216, i.e. the base frequency ÷ 26.
Note that the phase here is 16-bits: 10 bits for the array index and 6
bits for the fractional part. Since all the bits are used, you do not
need to handle the rollover: a uint16_t automatically rolls over
modulo 216, which is just what you want here. You can use a
32-bit variable if you need more frequency resolution.


text:
Reading values from Wiznet w5500 chip over SPI
I am trying to get the MAC address that is stored on the Wiznet w5500 chip.
On page 29 - click here, it has the address of the values. It state that "This block can be selected by the BSB[4:0] value of SPI Frame". Then it lists the addresses of the MAC block from 0x001E to 0x0023.
How do I read these blocks using the SPI library? What does the BSB[4:0] mean?
EDIT 1: I am looking through the Wiznet Arduino library and it looks like there is a way to access the mac address through

Page 29 of what? Could you share this document with us please?

@MarkSmith thanks for pointing that out. I added the link.

The initial value is 00.00.00.00. The library/sketch sets the MAC address.

@MikaelPatel so there is no way to read the MAC into the software? I would have to use a separate MAC as a unique identifier?

You can read the SHAR register into the software but the initial value is not unique. Some Ethernet Shields have a sticker with an allocated MAC address to use. See http://wizwiki.net/forum/viewtopic.php?t=501 and http://arduino.stackexchange.com/questions/8719/didnt-have-mac-address-on-wiznet-based-ethernet-shield-cloned

@MikaelPatel ok. I thought the chip had a dedicated MAC burned into it. I guess I will just use an extra component with a MAC burned in the EEPROM.


text:
24LC1025 Arduino - Data Writing Problem
I have a very big problem by writing a list of strings to an eeprom (24LC1025) Your help with my problem highly appericiated.
I have a data matrix, PageData[111][96] and I want to write all them at once, line by line to the eeprom. I am using arduino for coding.
the code is :
{

#include <Wire.h>

#define EEPROM_ADDR 0xA0;

void setup()
{

  Wire.begin();

  Serial.begin(9600);
int PageData[111][96]={ my data is here ... }

 for (t=0; t<111; t++){
  for (unsigned long i=0; i<96; i++){
    m=i*2;
    value[m] = highByte(PageData[t][i]);
    value[m+1] = lowByte(PageData[t][i]);   }

  at=((t*192));

 for (unsigned long i=0; i< 192; i++) {
    i2c_eeprom_write_byte(EEPROM_ADDR,(at+i),value[i]);
    delay(5);                             }
      }

void i2c_eeprom_write_byte( int deviceaddress, unsigned long eeaddress, byte data )
{
if( eeaddress > 65535 )
    deviceaddress = deviceaddress | B00001000;

    deviceaddress = deviceaddress >> 1;

  byte rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8));    // Address High Byte
  Wire.write((int)(eeaddress & 0xFF));  // Address Low Byte
  Wire.write(rdata);
  Wire.endTransmission();
}

My problem in this code: when I want to read the eeprom for the checking the strings, I realize, it does not write the eeprom the whole 111 line. It just writes randomly sometimes half of this sometimes less than this amount.
I tried several ways to solve the problem. but now I am desperate , please check this and tell me where i miss a point. Please let me know, if any information you need for the answer.

111 x 96 x 2 Byte = 21312 Byte. How is this supposed to fit into your maybe 4096 Bytes SRAM? You're probably getting a stack overflow and undefined behavior.

@brhans: I am not talking about the Flash, I am refering to the SRAM of the Arduino controller. "Stack overflow" has nothing to do with external storage.

@Rev1.0 - doh - I should read more carefully - didn't even consider that the OP might be messing up the basics ...

arduino due has 96kbyte SRAM not 4096 bytes.
https://www.arduino.cc/en/Main/arduinoBoardDue

@AhmedTarhan: Granted, but you left us guessing what kind of Arduino you have. And since most have 8-bit controllers with very little ram, limited SRAM was a potential issue.

@AhmedTarhan. You have to clarify what hardware/software are you using. What run in Arduino Uno doesn't run in NodeMCU. As a rule, you have to says what libraries and IDE are you using,

Writing a single byte is really bad. You are causing a page write with each bye, and each page has a limited lifetime (100,000 - 1,000,000 cycles) so use block instead.

When writing any amount of data, including a single byte using this
  function,   the EEPROM will refresh the entire page (128 bytes) of
  data.   EEPROMs have a limited write endurance (often 1 million cycles
  per page).   Therefore, if you write one byte at a time, instead of
  writing a full block   at once, you are wasting the chip's lifetime
  (doing so is also MUCH slower).   ONLY use this if you really only
  need to write ONE byte, and avoid it   when you can.   Using a block
  write (below), you can write 128 bytes and only use a single   page
  write (or at most two, if the write is not aligned to a page
  boundary).

This library should do the trick for you:
https://github.com/exscape/electronics/tree/master/Arduino/Libraries/EEPROM/EEPROM_24XX1025

Duh! Please, expand your answer. Other than avoid unnecesary writings, I haven't found much about EEPROMs. Is your info valid for all kinds of EEPROM?

Im sorry buddy, I don't get what you mean? Expand my answer of not writing one byte at a time? I referenced a well written out description on why, and a library that will take care of writing with pages. If you need more information, you can click on the link and read about which modules are supported. Do you need help for a specific module, or a specific scenario? The original post is about a 24LC1025 module, which is supported for the first block (64KB) by the referenced library.

authors: Виктор Аверков


text:
Simple reading and writing on Floppy Disk
I am trying to interface a 3.5" floppy drive (read and write data onto floppy disc). Since I need to write just few bit long number on it (16 is more than enough) I am thinking I could write it track-wise (each track is one bit), which gives me teoretically 80 bit long number, so I could write 4 times 16 bit long number for some redundancy.
I found this code, which solves reading data out. For writing I found this page which says, that writing should be similar easy process.
I attached code I am running here. Reading seems to work, but writing not. The interesting part of code is:
void writeData(byte data){
  Serial.println("Writing");
  digitalWrite(writeEnablePin, LOW); //starting spining a motor
  digitalWrite(motorEnableBPin, LOW); //enabling motorEnable
  stepAllTheWayOut(); //moving head to the edge of drive
  for(unsigned i = 0; i<10; i++){ //repeating 10 times
    for(unsigned index = 0; index<=8; index++){ //repeating 8 times (there are 80 tracks)
      digitalWrite(writeDataPin,bitRead(data,index)); //setting data pin
      Serial.print(bitRead(data,index)); //printing out what is being written
      delay(500); //spinning for a while to write all over the track
      digitalWrite(writeEnablePin, HIGH); //stepping not working when writeEnablePin is LOW
      stepIn();
      digitalWrite(writeEnablePin, LOW);
    }
    Serial.println("");
  }
  digitalWrite(motorEnableBPin, HIGH);
  digitalWrite(writeEnablePin, HIGH);
}

The output is:
Setup done.
Writing
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
010101010
Reading
111001000
101010001
110111001
001000101
001011001
111111101
110101101
111110011
111111001
101111110

The output is not what should be written. (the bits are changed every time i run the code)
Any idea what am I doing wrong when writing?

Okay, I have little knowledge but I will try my best. 1)Have you tried erasing the disk completely you might be trying to read already written data. 2) Have you checked the timings of the byte sequence. That's all I can think of, sorry if it's not helpful.

for(unsigned index = 0; index<=8; index++)

I think that need to be
for(unsigned index = 0; index<8; index++)

Otherwise you are trying to read the 9th bit in a byte.

Nice. That is faulty indeed. Doesn't solve reading-writing problem at all though...


text:
Stop time in Tkinter Stopwatch with a PushButton
So, my main goal is to make a stopwatch with Tkinter, in which time is stoppped with an external pushbutton
My void loop function in Arduino Uno is
void loop() {

if(digitalRead(BUTTON) == HIGH){
    Serial.print("E\n");
digitalWrite(LED, HIGH);

while(1){

 if(digitalRead(BUTTON) == HIGH){
  continue;
  }

if(digitalRead(BUTTON) == LOW){
break;}

        }
                               }

}
Basically, whenever the pushbutton is pressed I send via serial the message "E\n" and the arduino enters in an infinte loop that only breaks when the pushbutton stops being pressed (to avoid sending more than one message).
Then I have my Python code that reads the serial through the serial.readline() function.
Part of my Python code is (remember that i'm making a stopwatch and time is appearing in the screen - variable timer[i] is what saves the second and the ms):
def update_timeText():
    if (state):
       global timer
       # Every time this function is called,
       # it increments 1/100 of a second
       timer[1] += 1

      # Every 100 centisecond is equal to 1 second
       if (timer[1] >= 100):
           timer[1] = 0
           timer[0] += 1

       if arduino.readline() == 'E\n':
           print("FLAG\n")

       # TIME STRING
       timeString = pattern.format(timer[0], timer[1])

       # UPTADE THE LABEL WITH TIME STRING
       timeText.configure(text=timeString)

   # Call the update_timeText() function after 1 centisecond
   root.after(10, update_timeText)

The variable state goes True whenever I start the stopwatch (via a Tkinter button, but that's irrelevant for this case).
My problem, is that the program stops in the line
if arduino.readline() == 'E\n':

i.e., it only continues if I press the pushbutton. What I think that is happening, is that the .readline() continues waiting and waiting until it receives the message 'E\n'... I've tried with the .readline.strip() and also only .read() but none of them worked.
It is though very strange, because if the condition in front of If is not verified, it should just continue...
Any suggestion?

It looks like your 'readline()method blocks.  You need a non-blocking version.  It's a Python question, not an Arduino question, but if you edit into your question the Python library you are using (what is yourarduino` object?) I'll try to help.

In the pyserial docs it states this:

Be careful when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

You need to specify the timeout and the end of line string. Try using this  modified line:
if arduino.readline(eol='\n') == 'E\n':

Also, add the timeout option where you define arduino as a pyserial object. For example:
arduino = pyserial.serial(port,baud,timeout=t,etc...)


text:
Reading a 10-byte buffer out of a PROGMEM string stored in a string table
I'm storing a large snippet of text in three separate PROGMEM char arrays:
const char script1[] PROGMEM = "....";
const char script2[] PROGMEM = "....";
const char script3[] PROGMEM = "....";

The first two are 32766 characters, and the last one is 23867 characters (the whole string is 89400 characters in total). I store these in PROGMEM on an Arduino Mega 2560 (which then uses about 90K of 256K of available program memory).
I stored these three strings in a table, together with their lengths:
const int TABLE_SIZE = 3;
const char * const scriptTable[] PROGMEM =
{
  script1,
  script2,
  script3
};

const int scriptLengths[] {32767, 32767, 23867};

I have some issues trying to chunk up the string into 10-byte buffers, and processng it that way. I want to iterate through the table, process the first part in 10-byte chunks first, then move on to the second part, and finally the last part.
For a single string (code), the following works fine:
const char code[] PROGMEM = "....";

// Chunk up large code string in PROGMEM.
const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
char workingSpace[CHUNKSIZE + 1];
int baseIndex = 0;

while (baseIndex < sizeof(code)) {
    int chunk;
    if (baseIndex + CHUNKSIZE > sizeof(code)) {
        chunk = sizeof(code) - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        memcpy_PF(workingSpace, ((uint_farptr_t)code) + baseIndex, chunk);
        workingSpace[chunk] = '\0';

        // for debugging
        Serial.print("#");
        Serial.print(baseIndex);
        Serial.print("– Got a chunk [");
        Serial.print(workingSpace);
        Serial.println("]");

        baseIndex += CHUNKSIZE;

However, I'm having some difficulties doing the memcpy_PF call using the table.
int tableIndex = 0;
// for each of the three script strings
for (tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++) {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    int baseIndex = 0;

    // we can only use sizeof if it's a static var.
    // strlen should only be calculated once, expensive operation (loop until we encounter '\0').
    // now stored statically in scriptLengths table.
    Serial.println("tableIndex: ");
    Serial.println(tableIndex);
    int strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
        int chunk;
        if (baseIndex + CHUNKSIZE > strLength) {
          chunk = strLength - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        // do memcpy_PF call here

I have tried several options here, mostly having difficulties with the second parameter (how to address the string stored in the table, and increase its indexing parameter). I read that the way to get a string out of a string table is to use pgm_read_word. However, with both of these below, I either get gibberish in the buffer string, or it seems to start in an incorrect location in the string.
memcpy_PF(workingSpace, ((uint_farptr_t) &scriptTable[tableIndex][baseIndex]), chunk);
memcpy_PF(workingSpace, ((uint_farptr_t) (char*)pgm_read_word(&(scriptTable[tableIndex])) + baseIndex), chunk);

Any help would be greatly appreciated!
Thanks!

The first thing you need to fix is this:
/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino: In function 'foo()':
/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino:42:27: warning: iteration 3276 invokes undefined behavior [-Waggressive-loop-optimizations]
     baseIndex += CHUNKSIZE;

You are adding 10 to 32760 hoping to be >= sizeof(code) however now baseIndex will become negative as an int goes from -32768 to +32767.

There were some interesting subtleties to getting this working. :)
One of your major problems is this:
const char * const scriptTable[] PROGMEM =

That will give you 2-byte pointers (const char *) which will not be large enough to index into 89400 characters.
So you need to have an array of 4-byte pointers like this:
uint_farptr_t  scriptTable [TABLE_SIZE] =

However you can't just initialize those like you tried to. That has to be done procedurally with a macro that pulls in the full address. My working code is below:
#include "code.cpp"

const int TABLE_SIZE = 3;
uint_farptr_t  scriptTable [TABLE_SIZE];  // values calculated at runtime
const int scriptLengths[TABLE_SIZE]
  {
  sizeof (script1),
  sizeof (script2),
  sizeof (script3)
  };

void foo ()
{
  // for each of the three script strings
  for (byte tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++)
    {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    long baseIndex = 0;

    Serial.println ("----------------");
    Serial.print("tableIndex: ");
    Serial.println(tableIndex);
    long strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
      int chunk;
      if (baseIndex + CHUNKSIZE > strLength) {
        chunk = strLength - baseIndex;
      }
      else {
        chunk = CHUNKSIZE;
      }
      memcpy_PF(workingSpace, scriptTable [tableIndex] + baseIndex, chunk);
      workingSpace[chunk] = '\0';

      // for debugging
      Serial.print("#");
      Serial.print(baseIndex);
      Serial.print("- Got a chunk [");
      Serial.print(workingSpace);
      Serial.println("]");
      delay (50);
      baseIndex += CHUNKSIZE;
    } // end of while
  } // end of for
} // end of foo

void setup()
{
  // get proper pointers to the various pieces of progmem
  scriptTable [0] = pgm_get_far_address (script1);
  scriptTable [1] = pgm_get_far_address (script2);
  scriptTable [2] = pgm_get_far_address (script3);

  Serial.begin (115200);
  foo ();
}

void loop()
{
}

The file "code.cpp" just has the actual data in it (generated at http://www.lipsum.com).
As in:
#include <Arduino.h>

const char script1[] PROGMEM =  {

"Lorem ipsum dolor sit amet, consectetur adipiscing elit.  ... " };

const char script2[] PROGMEM =  {

"Aliquam erat volutpat. Praesent aliquet accumsan arcu,  ... " };

const char script3[] PROGMEM =  {

"Ut neque dolor, condimentum ut odio iaculis,  ... " };

Output:
----------------
tableIndex: 0
length script string: 32767
#0- Got a chunk [Lorem ipsu]
#10- Got a chunk [m dolor si]
#20- Got a chunk [t amet, co]
#30- Got a chunk [nsectetur ]
#40- Got a chunk [adipiscing]
#50- Got a chunk [ elit. Pro]
#60- Got a chunk [in sit ame]
#70- Got a chunk [t purus cu]
#80- Got a chunk [rsus, dict]
#90- Got a chunk [um magna q]
#100- Got a chunk [uis, place]
#110- Got a chunk [rat dui. I]
#120- Got a chunk [nteger ali]

...

#32700- Got a chunk [, eget tem]
#32710- Got a chunk [por dui te]
#32720- Got a chunk [mpor a. Do]
#32730- Got a chunk [nec malesu]
#32740- Got a chunk [ada mi et ]
#32750- Got a chunk [dolor cras]
#32760- Got a chunk [ amet.]
----------------
tableIndex: 1
length script string: 32767
#0- Got a chunk [Aliquam er]
#10- Got a chunk [at volutpa]
#20- Got a chunk [t. Praesen]
#30- Got a chunk [t aliquet ]

It successfully transitioned from the first array to the second one.

Good point, I missed that, thanks! Probably best to limit the size of script1,script2,script3, etc. to avoid overflows (e.g., to 30.000)?

Or use a long as an index.

Right, thanks! Any thoughts on the memcpy?

Maybe the avr-gcc compiler can not handle a PROGMEM section beyond 64kbytes. With a test sketch I am able to declare a lot of data (150kbytes), but the pointers in the Table[] stay 16-bit. They should be forced to 32-bit, but I don't know how. Even then, the memcpy_PF might not read beyond the first 64kbytes of the PROGMEM segment. So far I can't even read script3 directly with a function (when it is at the end of 150kbytes data).

See my amended answer.

I have tried a few things, and it it possible to create a 32-bit list of pointers with "const uint_farptr_t Table[] PROGMEM = ", but filling them during initialiazation will not fill them with the proper 32-bit addresses. I can't find another way to make it work than the workaround by Nick Gammon. The memcpy_PF() can retrieve data from PROGMEM that is beyond the 64kbytes border. It is the table that causes the problem. Also sizeof() and declaring too much data in a single array will cause trouble beyond the 64kbytes border, sometimes there is not even a compiler warning.

Thanks Nick and Jot! Nick's version is the solution we used eventually, and it seems to work. Particularly pgm_get_far_address seemed to be the missing puzzle piece. When reading data byte by byte from the strings in the table, it's also important to use pgm_read_byte_far() (vs. pgm_read_byte()).
As you mentioned Jot, there is an open Arduino bug where built-in macros stop working once you go beyond 64K: see http://forum.arduino.cc/index.php?topic=455577.0 & https://github.com/arduino/Arduino/issues/2226 We have reduced our strings to 40K in total to avoid that.


text:
Aurduino Smart Wifi Wall Socket
i wanted to make a remote controlled wall socket over wifi (and maybe internet in the future) with an Arduino, i'm relatively new to Arduino, i know only the basics of programming. My idea was to use a Arduino Pro Mini, a relay, a Esp8266 wifi module to connect to my home wifi and maybe a module to monitor consumption like the ACS712 current sensor but i don't know how to make all of this work, maybe i can get the Arduino working but i don't know how to control it on the client side like an app or web interface on my phone/computer.

You only need the ESP8266, which can be programmed using the Arduino IDE as if it were "an Arduino"

Or buy a Sonoff, which contains an ESP8266, and hack it if it doesn't already do what you want.

@hapi how could you do that? Isn't the ESP8266 just a wifi module?

@MarkSmith the Sonoff is not bad but i want to control it over WiFi network not over RF so it doesn't do what i want.

They are wifi controlled. (Wifi is RF, given that it's radio...)

@MarkSmith you're right, sonoff is just what i want and what karx suggested i could do, but if I want to monitor consumption?

The hardware you have chosen is perfect for the job at hand.
But what @Hapi also mentioned was that you could probably do away by not using the Arduino !
The ESP8266 is in itself programmable. There are many Firmwares available to help you do so. (You can even program your own)
This can help you getting started : http://randomnerdtutorials.com/esp8266-web-server/
This is something like what you need at the end : https://hackaday.io/project/4562-esp8266-wifi-smart-garage-door
One thing to note : ESP8266 works with 3V, while your Relay would require 5V.
Happy hacking my friend.

All the Hardware mentioned are correct,
Arduino Pro Mini (Micro-controller) - To control the Relay
5V Trigger Relay(240V) which would be trigger using a digital Pin on the Arduino.
http://www.instructables.com/id/Controlling-AC-light-using-Arduino-with-relay-modu/
Once you accomplish the steps above you must hook up your wifi module.
Then write a software in your preferred/environment for example, Visual Studio C#, and Use the a UDP or Telnet or HTTP Web-Server ( http://blog.nyl.io/esp8266-led-arduino/ ) connection to sends command to the Arduino though the Wifi Shield, which will trigger the Relay and therefore turn on the Switch.
Also you must find an adapter that sits into the socket and convert 240V AC to 5V DC power to match the consumption of your Arduino.

The adapter to convert 240V AC to 5V DC is not a problem, i can use an old cellphone charger, the HTTP Web-Server connection is very interesting i took a quick look at it maybe i will use it. I still haven't all of the hardware to make a proof of concept but i will soon.

@alex3850 well keep me updated,  hope the answer help you out.

For now I'm waiting for the Arduino and other stuff to arrive then I will try to do some thing, your answer is really helpful.


text:
Store a variable?
I want to have a switch, that when on, will grab an analog number and essentially "freeze" it. Similarly to how STO> works on a TI83. What should I be using? Excuse my lack of technical terms, I'm not sure what to search and therefore do not know what to use. Thank you :)

Store/freeze it permanently, so it can be retrieved after power off, or just hold it in memory while power remains on?

@MarkSmith sorry, should have clarified. Just while power is on.

Then you don't need to do anything special - that's what variables do. Just read it: int value = analogRead(...);.  value now contains the value you read.

@MarkSmith but it will continuously read my analog input, which will be changing. I want it so when I press a button it'll grab that number and not keep reading from analog

Only if you tell it to. Can you think of a way to tell it only to read when the button is pressed? (Can you think of a way to tell it to do anything when a button is pressed?)

@MarkSmith I was planning on using a switch, not a button, so I will be using an if statement, but that will loop.

My recommendation:

Configure an external interrupt on the raising edges of the input where the button/switch is wired. Note that only pins 2 and 3 of Uno are capable of external interrupts.
Write a very simple ISR that just sets to True a global volatile variable (a flag to signal that the button/switch has been actuated) and does nothing else.
In the loop() check if the flag variable has been changed by the interrupt. If that's the case, then:

Debounce/deglitch the button/switch (optional, but highly recommended).
Read the analog input of your choice and store its value or do whatever you want to do with it.
Reset the flag variable to False so it can be changed the next time the interrupt is fired.

You could use EEPROM on the Arduino. For example:
#include <EEPROM.h>

int valAddr = 0;

#define analogPin 0
#define buttPin 3
void setup() {
  pinMode(buttPin,INPUT);
}

void loop() {
  /***
    Need to divide by 4 because analog inputs range from
    0 to 1023 and each byte of the EEPROM can only hold a
    value from 0 to 255.
  ***/
  if(digitalRead(buttPin)){
     int val = analogRead(analogPin) / 4;
     EEPROM.write(valAddr, val);
     //access this value again by using int newvalue = EEPROM.read(valAddr)*4;

  }
}

By using EEPROM your value will be stored in non-volatile memory, meaning it will stay in memory even after a power cycle which is similar to how STO> works.

As noted in the EEPROMWrite page at arduino.cc,  “The EEPROM memory has a specified life of 100,000 write/erase cycles, so you may need to be careful about how often you write to it.”  The above program is not careful.   At 3.3 ms per EEPROM write, the above program will finish 100000 writes to valAddr in about 6 minutes if pin 3 is high.

Yes, definitely be careful of this. If your button is held down in your application you will have to write code to make sure it only writes once and only registers the button click once (debounce).

Only read the analogue pin if the button is pressed.
#define analogPin 0
#define buttPin 3

int analogVal = 0;

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

void loop() {
    // You can do stuff here

    // If the button is pressed...
    if (digitalRead(buttPin)
    {
        // ..read the analogue pin
        analogVal = analogRead(analogPin) / 4;
    }

    // You can do stuff here
}

I'm not using a button, I'm using a switch. I just want when the switch is first turned on it will freeze a number, and when turned off it will unfreeze.

What do you mean "unfreeze"?  Throw the number away? Read continually?

Here's a simple way of tracking the switch and managing the bit of state you need to manage:
int analogPin = 0;
int switchPin = 3;
int switched = 0; // the last-known state of the switch
int lastRead = 0; // the last-desired analog sample

void setup() {
  pinMode(switchPin, INPUT_PULLUP); // connect switch to switchPin+GND w/o resistors
}

void loop() {

  if(digitalRead(switchPin)){ // switch on:
    if(!switched){ // switch on, but was unknown
      lastRead = analogRead(analogPin); // the wanted leading-edge value
      switched = 1; // seen it on
    }//end if switch changed?
  }else{ // switch off:
    if(switched) switched = 0;      //  remember that switch is off
    lastRead = analogRead(analogPin); // the latest value
  }

  Serial.println("Value is " + String(lastRead));
  delay(500);
}

Read the analog input and store it, continuously. If the switch is off, also write the value to the "freeze" value:
void loop(){
   int value, freeze;

   value = analogRead(ANALOGPIN);
   if( !digitalRead(SWITCHPIN) ){
      freeze = value;   // sw is off, upd freeze value
   }
}

This doesn't take into account possible bouncing of the switch. That may or may not matter depending on the actual rate of sampling the analog input and what you intend to do with the frozen output, as the switch bouncing will be shorter than human perception but long enough (10s of msec, perhaps) for the MCU to notice and react to changes.

it will continuously read my analog input.

easy:

have the adc in free running mode and in the isr writes the adc value to a buffer.
watch the state of the button in an isr. if it changes, save the buffer value to something else.

there are simpler ways of doing it but less real time than that. need to watch out for atomicity if a multi-byte value is involved.


text:
Read value from a file inside SD card
it's possible to read value from a file inside sd card?
I'm trying to start with the sample code
/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 11
 ** MISO - pin 12
 ** CLK - pin 13
 ** CS - pin 4

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

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

File myFile;

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing1 1, 2, 3.");
    myFile.println("testing2 1, 2, 3.");
    myFile.println("testing3 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}

but here he read all the contnent of the file, i want to read only testing 3 part . Thank's for help

Yes it's possible. Please be more specific in what your actual question is. As now, it's too vague to be answerable.

Do you have any part of this working? For example, do you have a device with an SD card slot? Is it attached to your Arduino? Can you read or write anything? Please try and make a start, and when you get stuck, post a specific question, with code.

it's possible to read value from a file inside sd card? - of course it is. Why would you connect one otherwise?

i found this solution with use of strcmp:
when i read the file i compare the result str coming from file flux
/*
 SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SD.h>

File myFile;
char buf[10];

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

 Serial.print("Initializing SD card...");
 // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
 // Note that even if it's not used as the CS pin, the hardware SS pin
 // (10 on most Arduino boards, 53 on the Mega) must be left as an output
 // or the SD library functions will not work.
  pinMode(10, OUTPUT);

 if (!SD.begin(53)) {
   Serial.println("initialization failed!");
   return;
 }
 Serial.println("initialization done.");

 // re-open the file for reading:
 myFile = SD.open("test.txt");
 if (myFile) {
   Serial.println("test.txt:");

   // read from the file until there's nothing else in it:
   while (myFile.available()) {
      myFile.read(buf,2);
       if(strncmp(buf, "12", 2) == 0)//for lenght i use 2 becouse im looking for a number with 2 digit
       {
           Serial.println("Match!");
           }
          break;
       }
   }
   // close the file:
   myFile.close();
 } else {
  // if the file didn't open, print an error:
   Serial.println("error opening test.txt");
 }
}

void loop()
{
  // nothing happens after setup
}

You have 2 options for doing this, depending on what exactly you want to read and how your file is arranged.

Read from the beginning until you find what you want. Throw away (just don't keep) what you don't want.
Use the File::seek(uint32_t) method to jump to a specific byte in the file and read from there. Only useful if you already know where in the file your data is.

how with reply number 1? Thank's

Exactly as with the example code. You just have to have the program examine what is read and make a decision on if it wants it or not.

yes, but I'm little bit noob, how? tnks again

Here's a clue: A File is a Stream. So is Serial. What you can do with Serial you can do with File.

an example please

Your posted question already has an example of reading from the file.


text:
How to verify that my FTDI bridge for ESP8266 is communicating with my PC?
As I couldn't make my ESP8266 be programmed using an Arduino board as FTDI bridge, I decided to buy an FTDI232 board to upload code directly to ESP module via USB. However, when new I connected it to my PC and nothing happened, no new device's notification, not listed on Device Manager; then I downloaded the chip and VCP drivers, installed them, and it keeps not communicating and not even showing its port as busy at Arduino IDE. Actually, I just disabled driver signature enforcement, repeated the process but communication between FTDI and PC keeps dead.
By testing uploading code to an Arduino Micro via FTDI (no USB connected to Micro), I checked Tx/Rx signals with an oscilloscope and both were not responding.
May it be a problem of communication PC<--->FTDI board? Or could it be that FTDI's chip is fried?
Thanks.

did you connect the ardunio's reset to ground to use it as an "ftdi"? that's the only way i could connect to my ESP-01s before i got a handy usb socket...

Which Arduino board did you use? I tried with connecting reset to ground on Micro, Uno and Leonardo, but any of them seemed to work. Of course I followed the tips of grounding GPIO0 while uploading code and that stuff, but no one worked (everybody in the internet who use it has success since the first attempt, that's confusing and sad)

a cheap fake uno worked fine for me; no level shifting or anything. might try uncrossing the pins.


text:
Run Code Based on Time From GSM Module (SIM900)
I am trying to check the time from the GSM module to let my code run or do nothing.
If I send the command, AT+CCLK? to the SIM900. This is the response:
AT+CCLK?

+CCLK: "17/02/14,16:58:25-20"

OK

How do I parse the time information from the SIM900 and setup a loop for my code to run if it is past 6pm but before 6am?
My code currently:
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7,8); //RX,TX

void setup() {
  PowerOn(); //power on GSM Module
  delay(10000); //delay 10 seconds
  SIM900.begin(19200); //software serial for GSM Shield
  delay(500);
}

void loop() {

// if time is past 6pm and before 6am send text message else do nothing

SendTextMessage();

}

///GetTime
void GetTime()
{
    SIM900.print("AT+CCLK?");
}

///SendTextMessage
void SendTextMessage()
{
    SIM900.print("AT+CMGF=1\r");//Because we want to send the SMS in text mode
    delay(100);
    SIM900.println("AT + CMGS = \"+12137777777\"");//send sms message, be careful need to add a country code before the cellphone number
    delay(100);
    SIM900.println("Motion Detected!");//the content of the message
    delay(100);
    SIM900.println((char)26);//the ASCII code of the ctrl+z is 26
    delay(100);
    SIM900.println();
}

///PowerOn
void PowerOn()
{
  ///software equivalent of pressing the GSM shield "power" button
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

I'm imagining SIM900 is a serial stream that supports input methods available() and read().  The hour portion of the response string is a two-digit integer delimited by a comma and a colon.  The following snippets of code assume you trigger a response and then start a listen() to connect to the software serial input.  Since listen() discards old data, presumably a message like +CCLK: "17/02/14,16:58:25-20" will be the next data to arrive.
This code converts any string of digits that it sees into a number.  Whenever it sees a non-digit character, it treats it as a delimiter.
When the previous and current delimiters are ',' and ':', it checks if the current number value is in the desired time range, and if so, it sets a flag, else clears a flag.
When the previous and current delimiters are '-' and '"', it assumes it is done with the parse.  Or one could, possibly, end the parse as soon as the hour field has been processed.
void loop() {
  // ...
  // somewhere within loop()
  byte num, dell;       // Currrent number and left delimiter
  byte timeFlag, readMore, foundTime;
  //...

  // Send string to elicit +CCLK and tell parser to handle response
  SIM900.listen();      // Discard old input
  SIM900.write("AT+CCLK?"); // Elicit new input
  readMore = true;
  timeFlag = foundTime = false;
  num = 0;
  dell = 0;
  // Read and parse +CCLK input; set or clear timeFlag
  while (readMore) {
    while (!SIM900.available()) {}; // Wait for a character
    char c = SIM900.read();
    if (c >= '0' && c <= '9') { // Is c a digit?
      num = 10*num + c-'0'; // Yes, add it to num
    } else {   // Not a digit, so check for Hour field or End of parse
      if (dell=='-' && c == '"') {
        readMore = false;
      } else
        if (dell==',' && c == ':') {
          timeFlag = (num < 6) || (num >= 18);
          foundTime = true;
        }
      dell = c;            // Record left delimiter of next number
      num = 0;             // Get ready to evaluate next number
    }
  }
  // If foundTime, then timeFlag is true for time in 6 PM to 6 AM, else false
  // ...
  // etc
}


text:
How to power my Arduino mini using wall socket?
I am trying to power my Arduino Mini (which is connected to IR receiver and a relay board). The idea is to hide the entire setup behind the electrical board including the power supply. I have hacked more than a few power adapters (ranging from Mobile chargers 5-7V to 12 V adapters)
This is what I understand from what I have read so far about Arduino Mini power supply.

I can power directly using Vcc pin if I supply 5V DC regulated. (not recommended)
I can power Raw pin by using 5-12V DC and the onboard regulator will take care of converting it. 12V is the maximum, I should not use 12V it can fry the regular if used for a long period as the on-board regulator is a linear one, so a lot of heat.

This is what I understand from what I have tried so far about Arduino Mini power supply:

Don't connect power supply EVER to Vcc, it will harm the board. ALWAYS use Raw.
12 V supply = puff. instantaneously. No more on-board regulator. Now that Arduino Mini only works if I connect it using Vcc. (the charger was rated 12V 500mA)
Connecting 5V DC (300mA) is heating the regulator alot.

I have connected the Relay and IR receiver directly to the Arduino mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.
The mini works with these 5V mobile chargers but the amount it heats up scares me.  Any suggestions on what I should do?
Also how much current consumption would be needed. I have tried using a 5V 300mA charger and 5V 700mA charger. Both work almost the same. Why?
I am a computer engineer and very new to Arduino.
Linking a similar question: Most compact method of powering Arduino from wall socket

What? Just take a USB cable apart and solder the positive lead to raw/vin/vcc. You'll get a lower onboard voltage (~4.5V) but it works fine for both relay and IR (rx and tx). You can probably go as low as 3.78V onboard before it gets too weird. Got such a device running here, it's working perfectly. If you've got a clean 5V (+/- 5%) you can solder the positive lead to 5V pin.

Exactly what I have done as of now. The issue was the regular heating up. I have not measured the temperature, any good easy way of doing so?

I use an off-the-shelf laser IR thermometer with ~95% of temperature (so multiply by 1.05), it works well. The regulator heats up because you pull too much current, drive your loads with transistors. Only use 20mA per output pin, don't get greedy on 5V/3V3 pins, use 200mA, 100mA respectively (yes, they can handle more, I know)

I have connected the Relay and IR receiver directly to the Arduino
  mini. Pin 10-14 are used for the relays Ins and PWD 3 for IR output.

I hope you don't mean that you have connected the coils of the relays directly to the Arduino pins. If that's the case, the surprise won't be the regulator blowing up, but the MCU surviving. Please edit the post and add complete schematics and/or photos of your prototype.

The mini works with these 5V mobile chargers but the amount it heats
  up scares me. Any suggestions on what I should do.?

Use a small heatsink if you're concerned about the regulator heating up. But it really shouldn't be a problem unless you're driving too much current from it. Have you actually measured the temperature it reaches?
Also, don't feed the coil through the regulator, but directly from the 5V adapter (presuming your relays are 5V). This will save a lot of dissipation in the regulator. NOTE: don't do this if you use a higher (> 5) voltage adapter!!

Also how much current consumption would be needed. I have tried using
  a 5V 300mA charger and 5V 700mA charger. Both work almost the same.
  Why?

Those current ratings are maximum values, not constant values. So, if your circuit draws let's say 290 mA, both adapters will be able to do the job.
EDIT: additional information
To safely and properly use relays with arduino, you need some interfacing electronics like this:

Full article from the source, here. Flyback diode: 1N4148. You can use almost any "logic-level" N-channel MOSFET.
If you're using instead a relay module similar to the shown below, all the required interfacing electronics are already built into it and your digital pins won't suffer any overcurrent condition.

However, the regulator will (probably) still suffer from excessive current through it. In some of these relay modules you can optionally use a different power line (JD-VCC, see below) for the relay coil. If you own one of these, feed it directly from the 5V adapter, skipping the regulator.

If the relay module doesn't have a separate power line, it may still work when connected to the 5V adapter if the dropout in the regulator is not too big (i.e., the "high" level from the digital pins is not too far away from the adapter voltage).

Hi, thanks for answering one point after the other. When you say "connected the coils of the relay", you mean to say Vcc is connected from the boards 5V pin?  Well the answer would be yes in any case because all 6 pins connected to relay are from the board itself and I will change it. Just want to understand what you mean by coil. Also as suggested I will measure the temperature and update you, as of now I don't have a good way measuring the temperature. I will see and get a laser temperature thermometer.

You're welcome. I'm concerned about how you may be wiring the relay, so I will update the post will some additional info about it.

The coil is located between the input (control) terminals. The relay is activated by making a current flow through the coil, which is achieved by applying a voltage to it. Depending on the relay, this current can be as high as 100-120 mA per relay. The arduino pins can't neither source nor sink that much current. The arduino mini onboard regulator may also struggle if several relay are powered from it.

If you have a multimeter, check whether it can do temperature readings. If it can, then you just need a temperature probe (they're not expensive) for it.

The Arduino website says you should not power your Arduino Mini with more than 9 volts.

Warning: Don't power the Arduino mini with more than 9 volts, or plug
  the power in backwards: you'll probably kill it.

https://www.arduino.cc/en/Main/arduinoBoardMini
The 5 to 12 Volts (not more than 12V for long time periods) refers to the Arduino UNO and probably others.

You certainly can connect a 5v or 3.3v to the Vcc pin for most boards. Most regulators can take a reverse voltage. To be sure, check the data sheet or place a reverse diode on the regulator.
Again, depending on the particular regulator your board has. Most of them are good for 16 to 18v. But that can change drastly if more load current is involved.
Well, that's your answer then. Put a reverse diode across the regulator, Between the Vcc and raw pins.


text:
How to make a servo sweep from 0 to 180 on press of a button on PS2 controller? (without delay)
I am working on a project that requires the servo to make a complete sweep once on pressing a button say r2 on the pS2 controller. I am using the Arduino Mega 2560,a PS2 controller clone, Bill porter's Ps2x library.
I have figured out a way to do so by adding a delay to the code but when the delay is used I can't use other parts of my project. What should I do?
int pos = 0;    // variable to store the servo position
int button = 2;  // The button will be on Pin 7
void setup()
{
myservo.attach(9);  // attaches the servo on pin 9 to the servo object
pinMode(pos, OUTPUT);
pinMode(button, INPUT);
digitalWrite (button, LOW);
}

void loop()
{
if(ps2x.ButtonPressed(PSB_RED))

for(pos = 0; pos < 90; pos += 90)  // goes from 0 degrees to 90 degrees
{                                  // in steps of  degree
 myservo.write(pos);

}
  if(ps2x.ButtonReleased(PSB_RED))

 for(pos = 90; pos>=90; pos-=90)
 {
myservo.write(pos);
delay(50);                             // waits 50ms for the servo to reach the position

What should you do? Well, at first you can simplify the answerer's task by actually posting the code you are using, so everybody can check and suggest you the modifications..

You need to look at interrupts.  Rather than delay you should keep looping until the next time to do something occurs.

yes interrupts could be be used but i have 5 motors , 2 stepper motors to control excluding the servos. wont interrupts make the code more complex?An example would really help.

If you already have the code, if you have a good understanding of how it works it shouldn't be too difficult to implement, but you would multitasking it by creating several objects that use a central time value. It should all be here, if you follow them and read them they can explain better than I: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview

Thank you that helped a lot but , i am using an approach similar to the one described here http://playground.arduino.cc/Code/AvoidDelay

authors: Роман Шабалин


text:
How to find integer inside a file with STRNCMP
I'm trying to compare the int number 18 with strcmp but give to me wrong result, the program looking for char 18 and not for integer 18, how i can look for an integer with strcmp?
/*
 SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

#include <SD.h>

File myFile;
char buf[10];

char bufStringa[24];

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

 Serial.print("Initializing SD card...");
 // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
 // Note that even if it's not used as the CS pin, the hardware SS pin
 // (10 on most Arduino boards, 53 on the Mega) must be left as an output
 // or the SD library functions will not work.
  pinMode(10, OUTPUT);

 if (!SD.begin(53)) {
   Serial.println("initialization failed!");
   return;
 }
 Serial.println("initialization done.");

 // re-open the file for reading:
 myFile = SD.open("test.txt");
 if (myFile) {
   Serial.println("test.txt:");

   // read from the file until there's nothing else in it:
   int id=18;
   while (myFile.available()) {
      myFile.read(buf,2);
       if(strncmp(buf, id, 2) == 0) // i think the system give to me te char 18 and not the number 18 how to do this?
       {
           Serial.println("Match!");
           for(int i=0;i<10;i++)
           {
            Serial.print(buf[i]);

           }
            myFile.read(bufStringa, 24);
            for(int i=0;i<24;i++)
           {
            Serial.print(bufStringa[i]);

           }
          break;
       }
   }
   // close the file:
   myFile.close();
 } else {
  // if the file didn't open, print an error:
   Serial.println("error opening test.txt");
 }
}

void loop()
{
  // nothing happens after setup
}

Maybe make it as:
char id[] = "18";

This is if you want to find "18" in your file. That's what I understood from your question.
EDIT: I guess you want this http://playground.arduino.cc/Code/PrintingNumbers:
int num = 18;
char buffer[100]; // this will hold your number
itoa(num, buffer, 10);

Function description here. Also it's not to hard to make this your self for integers and it's a good exercise.

i have an Integer for input, i need to convert this integer to char for use it in STRNCMP , tnks

Check my edit, is this what you need?


text:
how can i generate square pulse at 50khz frequency to drive two mosfets at a duty ratio .6
I have to switch 2 MOSFET IRF640 at a duty ratio of .6 and the frequency of  switching is  50khz how can I generate it with a single aurdino

Please read How do I ask a good question?.

This could be achieved either with software (with a timer interrupt or
by polling micros()) or with hardware. The software methods, however,
are prone to a high level of jitter. If you want to have a steady
signal, you should use a hardware solution.
The most straightforward hardware option is to use a timer in PWM mode.
I would avoid fiddling with timer 0, as it is used by the Arduino
timekeeping functions. You are left with either timer 1 or timer 2. The
following program configures timer 2 to output the desired signal:

period = 20 µs = 5 × 64 CPU cycles
signal HIGH for 12 µs = 3 × 64 CPU cycles.

The output goes to pin 3, which is one of the two PWM pins controlled by
timer 2.
void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 = digital 3 as output
    OCR2A  = 5 - 1;       // period = 5 * 64 CPU cycles
    OCR2B  = 3 - 1;       // HIGH for 3 * 64 CPU cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22)   // ...ditto
           | _BV(CS22);   // clock at F_CPU / 64
}

void loop(){}

For some in depth information on how timers work, see
Nick Gammon's tutorial on timers.

Lots of ways.

Use a timer interrupt.
Use a pwm module.
Use the output compare module.
Use the SPI module.
Use a timer.
Use a pwm generator.

.......
Literally endless ways of doing it.

Endless ways of naming the same things: 2, 3 and 6 are the same, 5 is the same as either 1 or (2, 3, 6).


text:
Undefined reference in Eclipse of .h and .cpp files
I'm trying to create a linked list for use on the Arduino, in the Eclipse IDE with the Arduino/Sloeber plugin. The linked list is written in a .h and .cpp file, and included locally in the project.

However, when building, I get the error undefined reference to Structures::LinkedList<int>::LinkedList().
And despite the fact that I've added the local folder to the list of includes (and it can find the top level file containing setup() and loop()), the problem persists;

My relevant file listings are below. Any ideas of what settings I can add to Eclipse in order to solve this? Potentially, could it be something to do with the use of template<typename T> in the header file?
Thanks very much,
David
FYI: This problem does not occur with the core libraries i.e. I can run examples like Serial and Blink.
My top level .cpp is pretty simple:
#include "LinkedList.h"
#include "RAStarSearch.h"
#include "Arduino.h"

using namespace Structures;
void setup() { }

void loop() {
  LinkedList<int> list = LinkedList<int>();
  return;
}

And the referenced .h is:
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include "Arduino.h"

namespace Structures {
template<typename T>
class LinkedList {
  public:
    /// Struct inside the class LinkedList
    struct Link {
      T value;
      Link *next;
    };

    LinkedList<T>(); ///< Default constructor
    void addValue(T val); ///< prepends new value at beginning of list
    T popValue(); ///< returns first element and deletes Link.
    Link* peekLink(); ///< Looks at first value
  private:
    Link *head; // this is the private member variable. It is just a pointer to the first Node
};
const int ERRNUM = 0x8000000; ///<Error number used, as exceptions not supported
}
#endif /* LINKEDLIST_H_ */

EDIT
On request I have included my code for LinkedList.cpp
#include "LinkedList.h"
#include "Arduino.h"

namespace Structures {
  template<typename T>
  LinkedList<T>::LinkedList() {
    head = NULL; // set head to NULL
  }
  template<typename T>
  void LinkedList<T>::addValue(T val) {
    Link *n = new Link();   // create new Node
    n->value = val;             // set value]

    if (head == NULL) { //i.e. if list is empty
      n->next = head;         // make the node point to the next node or NULL
      head = n;    // last but not least, make the head point at the new node.
    } else {
      Link *it = head;
      Link *oldIt = NULL;
      //TODO check edge cases i.e. insertion at beginning and end of list
      while (n->value > it->value){ //until place in list is found, needs T to have > operator
        oldIt = it;
        it = it->next;
      }
      oldIt->next = n; //Set pointer to n
      n->next = it; //Set n pointer to next
    }
  }
  template<typename T>
  T LinkedList<T>::popValue() {
    T retval = ERRNUM;
    if (head != NULL) {
      Link *n = head;
      retval = head->value;
      head = head->next;
      delete n;
    }
    return retval;
  }
  template<typename T>
  typename LinkedList<T>::Link* LinkedList<T>::peekLink() {
    return head;
  }
}

Have you tried placing the H file in the same folder as you main cpp file.  This should prove beyond all doubt that there is nothing wrong with the code (I can't see anything wrong).
I suspect its a path issue.  You need to check that Eclipse is setup up properly to source the libraries from you custom location.  Also it needs to be passing this location on to the compiler.  I don't know how to do that in Eclipse but Google should point you in the right direction. Try this http://forum.arduino.cc/index.php?topic=39972.0 ?
Also you might find it easier to specify the include files in the order system, 3rd party libraries, local libraries and then local include files.  This means that duplicate definition faults are reported against the files nearest to the ones you have written.  If you define time_t using your ordering the fault will be reported against  rather than your header file.
Also a using namespace foo statement removes the benefits that namespaces provide, so its best not to do it.
EDIT
Doh - I should have spotted this sooner.  Template classes have to have the functions inline not in a CPP file.  This is because the CPP file can't change what T is at compile time, but because the H file is included in the file it is used in when it is preprocessed the object represented by T can change.
Basically inline your functions and it will work.

Unfortunately they are already both in the same path, and thank you for the tip on namespaces!

Sorry - The mistake is really obvious, but I had to compile it to realise what it was :)  You need the functions implementing.  You can't have a cpp file with a template so you need to inline the functions in the header file.  (I recreated the error on a PC with Visual Studio, so its not paths)

I have been reading up on this. As Matt states this seems to be a FAQ template issue. Have you read this? https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl

I've added the LinkedList.cpp file. Do I take it from this that to solve it I just need to inline all the functions into a single file?

@Matt This seems to be correct - inlining, or #include LinkedList.cpp seems to have worked! If you update your answer to reflect the problem?

The error you get is telling you that you have not implemented the method.
LinkedList<T>()

which you use in loop()
In other words: the header file is found and the correct references are made but when the linker tries to pack everything together he finds that he doesn't have an implementation.
The implementation is in LinkedList.cpp in your project but with templates this is not enough.You need to somehow explain the "toolchain" that your project needs a "instantiation of the template" of type int.
The fact you need to specify this is a "limitation" of the toolchain processong of templates and is well documented here https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl.
The same link contains solutions.
The article states "This solution may (or may not!) cause significant code bloat" which is probably one of the reasons why template classes are not so popular in embedded development.
In your case I would simply include LinkedList.cpp in my .ino file and rename the .ino to .cpp.
As I do not have the source code I can not tell you whether this will work.
note that including the LinkedList.cpp in the .ino doesn work because the LinkedList.cpp is included 2 times and there are no include gards in the LinkedList.cpp file

LinkedList is there (see the image), I just didn't include the listing as I though it was somewhat trivial?

As to the compiler the constructor LinkedList(); ///< Default constructor is not implemented

I updated the answer with the new insights I have on behalf of template classes

I updated the answer now the source has been provided.

authors: Алексей Щербаков


text:
Problem using IRremote library
I am using arduino pro micro 5v 16Mhz. I have built a simple IR transmitter circuit as shown.
The code i am using is
https://github.com/z3t0/Arduino-IRremote/blob/master/examples/IRsendDemo/IRsendDemo.ino
Although this worked yesterday, it doesn't seem to work now. I was able to turn on and off my TV yesterday but the led is not even blinking now. I checked led, its working.
After hours of trying to make it work I tried different library.
https://github.com/cyborg5/IRLib2/blob/master/IRLib2/examples/send/send.ino
Surprisingly this seems to work but the code is a bit complicated for receiver.
I want to use the first library. Any help is appreciated. Thank you.

I'm not sure what help anyone can give you here. You had it working, presumably changed nothing, and now it doesn't -- how can we debug that?

It seems the library got the timer pins wrong I changed them and its working now.

How did it ever work?

I used nrf24l01 module in between and maybe it changed timer settings.

The problem was with timer timer settings in library. I checked different timer configurations with different pins and its working now. I found out that timer4 uses pin 13 which is not used in Pro Micro board so I am now using timer 3.


text:
Where is PORTB defined?
On Arduino I can set digital pins by setting special variables PORTB and PORTD (or maybe they are not variables?). Where are those variables defined? I grepped /usr/share/arduino, but found nothing.
grep -r 'PORTB' /usr/share/arduino/

PORTB is defined by the "toolchain". It is not defined by Arduino.
For instance in my setup the Arduino Uno uses "toolchain" avr-gcc\4.9.2-amtel3.5.3-arduino2\avr.
If you grep that folder (location dependent on tool and installation options) you will find a file called iom328p.h that defines
#define PORTB _SFR_IO8(0x05)

This is a mapping to a physical address of the cpu.

Thank you. And how does this file gets included when my program is compiled and linked? Is it included by Arduino.h?

Arduino.h includes avr/io.h, which in turn includes the ioXXX.h file relevant to your specific MCU.

. Where are those variables defined?

In the device header file. Like other device specific macros.


text:
Problem burning bootloader on ATmega328P using internal clock
I'm trying to burn the arduino bootloader onto my ATmega328P so it uses the internal clock. I followed the tutorial in this page but I'm getting this error.
avrdude: Version 6.3, compiled on Dec 16 2016 at 13:33:19
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

I tried placing a cap from reset to ground but it doesn't wort either.
Any idea on what might be wrong with my procedure?
Thanks
[EDIT]

I followed the procedure described at the bottom of the page linked (Minimal Circuit (Eliminating the External Clock)).
I used the bootloader in "breadboard-1-6-x.zip"
I am using the Arduino IDE v1.8.1

It isn't clear from question+webpage what your procedure is, or what you want to do.  What  “internal clock” do you mean?  The built-in 8 MHz RC oscillator ?  If so, please edit question to say so.  Also edit question to include a schematic of how you have things hooked up.  Do you have a USBasp to program the  ATmega328P system, or what?

I followed precisely the instructions listed on the link I provided. And yes it is the internal 8MHz RC oscillator

You could edit the question and say what your programmer is, what fuse settings, which bootloader.  Or just let people guess.

I though providing a link of the tutorial which answers all of your questions was enough, but I'll edit it out.

The link describes several different procedures, and I think the details of what all was done aren't clear

Ok, i'll edit it.

Step 5 of the "Minimal Circuit (Eliminating the External Clock)" says, "Once you've done this, you can burn the bootloader and upload programs onto your ATmega328 as described above."  Which of the two methods shown did you use?  What  what what programmer are you using?

I'm using Arduino as ISP

Please run my chip detector sketch and report the results (copy/paste).

If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.

can I connect the ATmega Cristal pins to the arduino board?

According to this, it should be possible to share a crystal (or resonator in the case of most newer Arduino boards) : https://forum.arduino.cc/index.php?topic=78584.0

I tryed connecting to the board oscillator. Now it gives me this error:

avrdude: Device signature = 0x00ffff
avrdude: Expected signature for ATmega328P is 1E 95 0F
Double check chip, or use -F to override this check.

Also the device signature keeps changing every time I try to burn the bootloader. Does this mean the ATmega is broken?

As noted in 6v6gt's answer, if the ATmega328 has been set to use a crystal, thereafter a crystal (or an external oscillator) are required for programming, until the fuses have been set to use the internal RC oscillator.  Here are a few thoughts, unfortunately somewhat scattered, on the matter.
If you have a parallel programmer (that delivers high voltage to the Reset pin and uses 8-bit parallel data signalling) you can use it to reset the fuses, since with that programming mode the clock is irrelevant.
Also, USBasp programmers interact with Avrdude to generate a programming clock of some specified frequency,   100kHz by default, 8kHz with the “Slow Clock” jumper installed.  Also see § “Set the clock in software” within USBasp ICSP programmer quickstart guide at freetronics.com.au.  Unlike the Avrdude man page, that reference says the default programming frequency is 375kHz and says “Avrdude’s -B option allows you to set the programming clock speed from software”, while the man page says -B specifies bit clock period (in microseconds) for the JTAG interface or the ISP clock of the JTAG ICE only.  Anyhow, a USBasp can reprogram fuses away from the crystal setting if a crystal or external oscillator is used, without depending on serial port data rates.  I don't know for certain whether it will work without a crystal or oscillator.
Note, rather than “sharing” a crystal via wires from one board to another – a practice that will broadcast lots of RF noise and might not get the signal across anyway – you could instead write a program on one Arduino to toggle a pin at high frequency, and use that output as an external oscillator to drive one of the crystal pins on another chip.  For example, the program below should generate a 2.67 MHz square wave on pin PB0 of an Uno or a Nano.
void setup() {
  cli();    // Avoid timer interrupts
  pinMode (8, OUTPUT); // PB0 is pin 8 on Uno / Nano
  while (1) PINB = 1;
}
void loop() {}

In the ATmega328 data sheet, see §14.3.1, Alternate Functions of Port B, and Table 14-3, which lists PB7 as XTAL2 (Chip Clock Oscillator pin 2), and PB6 as XTAL1 (Chip Clock Oscillator pin 1 or External clock input), indicating external oscillator attaches to the PB6 pin.

I would cli() before the while, otherwise the timer interrupt would make long glitches.

After that, how I have to connect it. The pin PB0 of the "clock generator" board to XTAL1 or XTAL2?

@jagjordi, see last paragraph of edit

I did what you said (configured the UNO to output the clock, connect pin 8 to XTAL1 (PB6) but I still get the same error. Device signature keeps changing every time I try to burn the bootloader. Any ideas?

authors: ปรีชา ตุ้มโท


text:
Send commands to ESP8266 over WiFi
I want to send commands to ESP8266 over WiFi from my phone(I'm working on building an App using PhoneGap). I'm new to this module and WiFi. What I'm doing right now is that I communicate with the module by sending GET (or POST) commands. I'm sure there should be a better way but I can't seem to find how. What is the correct way to talk to ESP8266 over WiFi?

Could you clarify whether you are using the ESP8266 in the Arduino environment -- that is, you are compiling code (a sketch) that runs directly on the ESP8266 and responses to the GET/POST commands?

Forgot to mention that. Yes, I'm using Arduino IDE.

You could use websockets, I think there is a library for the ESP8266 around somewhere (I cant remember what its called)

fwiw, i've had better luck with http than sockets and mqtt; fewer resets/freezes, lower ping times, and more bandwidth, provided you keep responses under 4kb...

Depending on what best suits your needs, you could use:

http GET/POST commands
Websockets over http
MQTT protocol
Your own TCP or UDP socket protocol
etc.

In all cases, what you code into the ESP8266 processor/flash will need to receive and process the commands. The possibilities are near endless, since you are writing the App and the code for the module and can make those design decisions.

Thank you for your answer. Currently I'm using http GET/POST commands and on the ESP side I analyse the received string. I don't know how to use the other methods, what is the most common/reliable option? I would appreciate it if you could give me some practical references.

All of those methods listed above use IP (either TCP or UDP), so they are relatively the same reliability. MQTT requires a broker daemon to be running, so you don't talk directly to the ESP device from your app - that's an additional point of failure. I would say there is not a clear winner, however.