text:
rc522 RFID reader will only accept first tag after power up
I have an interesting problem using the Mifare rc522 device similar to http://www.ebay.com/itm/201415107836
I have this device connected to an arduino uno and drawing power from the 5V supply.
It reads cards and tags well.
Provided the card waved by it has previously been waved by it as the first card after power up.
It will recognise ALL the cards and tags I have with no problems but ONLY if each card has been at some time the FIRST card since the device was powered up.  Reset button does not help.  Once each card or tag has been used as the first after power up it will work every time thereafter.
I am using a very simple sketch which simply reads the RFID via serial link and then displays the data on an LCD.
Can anyone help explain this odd behaviour.
Is it something to do with the tags perhaps?
http://www.ebay.com/itm/201611365871 (bought from same seller who is, BTW very quick and cheap to mail parts)
I have tried running off a 12v supply (to the duino) and USB with same effect.  I have added a capacitor (47uf) across the power to the RFID - same issue.
/*
 Based on  LiquidCrystal Library - Hello World

 * LCD 4  RS pin to digital pin 12   Pin
 * LCD 6  Enable pin to digital pin 11
 * LCD 11 D4 pin to digital pin 5
 * LCD 12 D5 pin to digital pin 4
 * LCD 13 D6 pin to digital pin 3
 * LCD 14 D7 pin to digital pin 2
 * LCD  5 R/W pin to ground
 * LCD  1 VSS pin to ground
 * LCD  2 VCC pin to 5V

 */

// include the library code:
#include <LiquidCrystal.h>

char incomingByte = 0;
int cursorpos=0;

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int detonate=10;
int shownumber=0;
void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(24, 2);
  // Print a message to the LCD.
  lcd.print("Initialised");
  Serial.begin(115200);
}

void loop() {
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):

  lcd.autoscroll();
   if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = char(Serial.read());

                // say what you got:

                lcd.print (incomingByte, HEX);

        }

}

further edit:
I have now been able to get the thing to communicate using software serial - it seems to work out the baud rate quite well so despite the datasheet you are not limited to 115200 baud.  Still the same problem though as far as I can see it will now work with any 3 cards - any new card bumps one off the list of acceptables.  AAAARRRGGGGHHH
As requested, code change below - I basically lifted this directly off the arduino forum with changes only to make it work with an uno using software serial.  It does work, after a fashion but still the same problem with recognising only a few of the cards I have.
//emulate mega with software serial
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3);

unsigned char command, devnull;
unsigned int returnLength;

void setup() {

Serial.begin(9600);
mySerial.listen();
  Serial.println("Waiting for Card\n");
mySerial.begin(9600);

  mySerial.write(0x02); //Send the command to RFID, please refer to RFID manual

}

void loop() {
   if (mySerial.available())
    {
      Serial.print("\n\rCARD SERIAL: ");
      for (unsigned int i=0; i<4 ;i=i){
        //Serial.print("2");
        if (mySerial.available()) {
            //Serial.print("\n\ri is: ");Serial.print(i);Serial.print(" ");
            Serial.print(mySerial.read(),HEX); //Display the Serial Number in HEX
            i++;
          }
        }

       Serial.println("\n\rRead Card Make...");
       mySerial.write(0xAB);mySerial.write(0x02);mySerial.write(0x01);

       Get_Reply();

       mySerial.write(0x02); //Send the command to RFID, please refer to RFID manual
    }

}void Get_Reply() {
       while (!mySerial.available());
       devnull = mySerial.read();
       while (!mySerial.available());
       returnLength = mySerial.read() - 1;

       for (unsigned int i=0;i< returnLength;i=i){
         //Serial.print("2");
         if (mySerial.available()) {
            //Serial.print("\n\ri is: ");Serial.print(i);Serial.print(" ");
            Serial.print(mySerial.read(),HEX); //Display the Serial Number in HEX
            i++;
          }
        }
}

Please post the sketch. It might have an issue even if simple.

You could try to run some example sketches, to see if they have the same problem.

Thanks.  Added code as requested.  It's a head scratcher as there is no memory usage intended.

Can you try to send the in coming bytes to your PC via USB and possibly take out the LCD code? Or directly connect to the rfid-board using an USB-UART cable? It may be that the code is working just fine, but the cursor leaves your LCD screen or that the LCD gets stuck in some kind of loop.

It will recognise ALL the cards and tags I have with no problems but ONLY if each card has been at some time the FIRST card since the device was powered up. - sounds like a problem with the reader. Maybe you need to acknowledge that you have read the card, or something?

Thanks nick - was thinking along the same lines.  It reports a code for every tag every time but only if that tag has at some point been the first tag presented after power up.  I have thought it may be writing to the tags but there is very little info on this particular unit.  Should have bought a better one but have been enjoying the challenge.

I cannot use USB to get the info from an uno as the card reader uses the serial and requires 115200 baud which exceeds softwareserial capability.  I may try a mega, but that is overkill for all the projects I have in mind so I don't have one of those right now.

Update the code in your question.

My guess is that you have to do this in two steps, i.e. 1) read from mySerial to a buffer, 2) write to Serial.


text:
Serial Monitor stops printing data
I have an IMU sensor (MPU 6050) connected with arduino UNO. Pin maps are as follows:
MPU6050 --> Arduino
Vcc --> Vcc
Gnd --> Gnd
SCL --> A5
SDA --> A4
(Not using any pull up resistors)
I am using jeff rowberg's MPU6050 library to get data from sensor. To test the sensor, I am using the raw value example sketch from the library. I am getting readings for both the accelerometer and the gyroscopes.
The problem is after some time the serial monitor just stops printing data. I have tried to figure it out but have not succeeded in solving the problem. It could be due to one of two reasons:

The MPU6050 stops giving sensor values
There is a problem with the serial monitor

As far as I have figured, the sensor is giving values because when I restart the serial monitor, the data starts to print again on the serial monitor and stops printing after same duration of time as it did before restarting the monitor.
I have tried the serial monitor of the arduino IDE and hyperterminal. In both cases the data stops printing after some time.
Any idea, what causes the serial monitor to stop printing data? Is it the sensor or the serial monitor?
Help would be greatly appreciated. Thanks in advance.

Chances are it's I2C locking up whilst reading from the MPU6050. Re-opening the serial monitor resets the Arduino. Check your wires (I2C doesn't like long wires), and add 3.3KΩ pullups to the I2C wires (if not provided by the MPU6050 board). Internal Arduino pullups are not adequate for I2C.

Please post the sketch. It could also be a String/memory allocation problem.

@Majenko It worked. I can't believe it but changing the wire length actually worked. I was using really long wires before, I shortened the length but it didn't worked so I shortened the length even more. This time the serial monitor didn't  stop.
I can't understand what cause the wire length has on the communication process though. Seems illogical.
Thanks again for helping out.

Au contraire - it's perfectly logical. Long wires = big antenna = picks up noise. Weak pullups = noise easy to interfere with communications. Combine the two and you have a recipe for disaster. Fix one or both and you get it working.

Note that even with good wiring, I2C code that lacks a "give up and try over" timeout is risky - if it waits eternally for a slave acknowledgement, one single misinterpreted bit will hang the system.

@AhmadTariq What was the initial length of your cabling and what was the final one?.

@ChrisStratton I have a similar problem: when I connect two I2C devices to Arduino Mega, after some long execution time (several days), serial monitor stops working. Is there anyway to log an error message to check if the problem comes from this timeout thing?

I had exactly same situation.
I initially started to inspect on FIFO overflow of MPU6050, then experimented setting different clock speed for I2C communication, tried to tweak with pullup resistors as recommended.
Finally, here is the solution which worked for me. Basically, I just disconnected INT pin from MPU6050.
Now the schema is:
(MPU) -> (Arduino)
AD0 -> GND
SDA -> A4 (No pullup)
SCL -> A5 (No pullup)
GND -> GND
VCC -> 3.3V
I used this code as an example:
https://github.com/jarzebski/Arduino-MPU6050/blob/master/MPU6050_gyro_pitch_roll_yaw/MPU6050_gyro_pitch_roll_yaw.ino
from this library:
https://github.com/jarzebski/Arduino-MPU6050

source: Stack Exchange

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

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

sort: votes


text:
No power from Breadboard Power Supply Module
Components

Breadboard Power Supply Module IM120525004
1 kOhm resistor
Green LED
Arduino Nano
LiPo 7.4V battery

LED Lights Up Fine with USB power from the Arduino

LED Does Not Light Up with power from the Supply Module

What am I doing wrong?

The Lipo battery is brand new and is charged as the terminals showed about 7.6V on my multimeter. This is confirmed by the LED on the supply module itself lighting up fine.
I think I can smell just a little bit of burn whenever the supply module is connected and there is power in the circuit.
The positive jumper wire is connected to the 5V VCC pin on the Arduino, not the VIN pin on the Arduino, not that it matters, because if I remove the Arduino from the breadboard the LED still does not light up

I'm not surprised you can smell burning. You have the power supply connected backwards.
You see that little + and - symbol next to the ON/OFF jumper? That's the polarity of the two runs of pins. You have the + row connected to the - rail of your breadboard (blue) and the - row connected to the (red) positive rail.
Turn the power supply around 180° and connect it to the other end of the breadboard - the rails will be the other way around then.

hahaha, well spotted! it works now :D

Took me a while to notice that... ;)

"It works now", does everything still work? I won't be surprised if something is damaged (as per the burning smell)?

@Paul the components seem to have survived the ordeal as far as the LED and the Nano lighting up go, haven't done any programming test on that Nano yet ..

Too bad, if it was burning maybe it can be another question XD

You are not the first person to have made this mistake. ;)

Been there, done this. (Can't even claim to have only done it once.... dangit!)  But you know what... I check it EVERY time now.  'Tis how we learn!

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


text:
Serial communication between Arduino and Java NetBeans
I am new to this serial communication between Arduino and Java NetBeans.
I am doing some small project and I need to get data from external EEPROM 24LC256 which is connected to Arduino UNO and pass it to the Java NetBeans platform not the Eclipse. So far I am using RXTX driver to communicate with Arduino in Java and easily get the data from serial monitor of Arduino IDE.
So can anyone help me, on how can I serially communicate with this external EEPROM using Java?
import gnu.io.*;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class last extends javax.swing.JFrame implements SerialPortEventListener  {
    SerialPort serialPort;
    private static final String PORT_NAMES[] = {
        "COM3", // Windows
    };
    private BufferedReader input;
    private OutputStream output;   /** The output stream to the port */
    private static final int TIME_OUT = 2000; /** Milliseconds to block while waiting for port open */
    private static final int DATA_RATE = 9600;  /** Default bits per second for COM port. */
    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        while (portEnum.hasMoreElements()) {   //First, Find an instance of serial port as set in PORT_NAMES.
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }
        try {          // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
            serialPort.setSerialPortParams(DATA_RATE,  // set port parameters
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));   // open the streams
            output = serialPort.getOutputStream();
            serialPort.addEventListener(this);   // add event listeners
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }}

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }}

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println("the state of the led is  "+inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        last main = new last();
        main.initialize();
        Thread t = new Thread() {
            public void run() { //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

This is the code in Java NetBeans.

Perhaps you can attach your code for higher rate of getting a proper answer. Just a wild guess, have you try softserial?

here i wrote code

Your EEPROM has I2C interface, so first you shall program Arduino to access it: An I2C EEPROM Class for Arduino
Then implement some kind of communication protocol over serial, to send commands instructing Arduino to read/write from EEPROM. For example, with following commands:

for writing write:<address>,<count>,<data_as_hex_string>
for reading read:<address>,<count>
response for reading: <address>,<count>,<data_as_hex_string>

authors: นายช่าง จักร์กริช


text:
Arduino - Rural A-GPS Station
I'm trying to set up a GPS tracking solution in a rural area. The catch is the GPS trackers need to be lower cost (power and cash), because there will be a good amount of them.
So I'm trying to find a solution where I can benefit from A-GPS using a beacon of some sort to handle any cpu/server calculations while receiving GPS noise from the tracking devices (I think that's the idea). I've read up a bit on Mobile Station Assisted (MSA) GPS, but I'm not entirely sure what solutions there are to handle this.
Any help or advice is appreciated.
Example:
Arduino GPS tracker x 200 ---[RF comms/GPS noise]--->  Beacon/Tower  ---[Internet]---> GPS Server

I'm not sure I get what you want, but the A7 module of Ai-Thinker is a good GPRS module with GPS in it.

Thanks for the reply. I've already got GPS board solution (Simduino) but I'm just trying to find out how I can use Assisted GPS without having each tracker communicate with the GPS server. The solution I researched uses a single beacon to do all the grunt work for the Assisted server stuff and the trackers help it by sending low-power GPS noise.
I just don't know of any software solution to create this tracker->beacon->server communication

got it, sorry but i don't have any idea how to help you.


text:
Weird text when pressing a certain touch button
I have written a code that remaps the 16-Key touch keypad. When 2 key is pressed, it writes weird characters in the serial monitor even on my 16x2 LCD

But the other keys work fine.
Here's the code:
#define SCL_PIN 11
#define SDO_PIN 12

struct keymap {
    int     kCode;
    String  kValue;
  };

keymap keys[] = {
  {1, "1"},
  {2, "2"},
  {3, "3"},
  {5, "4"},
  {6, "5"},
  {7, "6"},
  {9, "7"},
  {10,"8"},
  {11,"9"},
  {14,"0"},
  {13,"CLEAR"},
  {15,"ENTER"}
  };

void setup()
{
  Serial.begin(9600);
  pinMode(SCL_PIN, OUTPUT);
  pinMode(SDO_PIN, INPUT);
}

void loop() {
  int Key = Read_Keypad();

  if (Key != 0) {
    for (int x = 0; x < 16; x++) {
      if (Key == keys[x].kCode) {
        Serial.println(keys[x].kValue);
      }
    }

    delay(300);
  }
}

byte Read_Keypad(void)
{
  byte Count;
  byte Key_State = 0;

  for (Count = 1; Count <= 16; Count++)
  {
    digitalWrite(SCL_PIN, LOW);
    if (!digitalRead(SDO_PIN))
      Key_State = Count;
    digitalWrite(SCL_PIN, HIGH);
  }
  return Key_State;
}

It seems by changing 16 to 12 on
for (int x = 0; x < 12; x++) {
      if (Key == keys[x].kCode) {
        lcd.print(keys[x].kValue);
      }
}

fixed it.

You might want to explicitly explain why this fix worked, in case it might help others.
Your keymap array had only 12 elements, and your loop was examining undefined memory beyond the bounds of the keymap array when it was accessing elements 12-15.
I think that the trigger on kepress of "2" was coincidence due to the undefined nature of the memory values you were checking every time through the loop.


text:
Measuring ADC sample rate - Arduino DUE
I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode. Hints are welcome, I really don't know where to start.

What do you mean by "conversion rate"? Time to perform an acquisition? The easiest way is to save the millis value, perform 1000 acquisitions, then save again the millis value and make a subtraction. If the value is small, increase the number of acquisitions to have a reasonable time (1-10 s). Then make the division. For instance, 10000 acquisitions -> 7.92s means that each acquisition is 0.792ms, so 1262 samples/s

... Or make it toggle a pin each time the acquisition is done, then measure with an oscilloscope... Or tell us what you want to achieve, so hints can arrive...

Hi! Thanks for your answer! What I need is to measure the sample rate of the ADC because I need to do an Antialiasing Filter.
My expectative is to achieve a sample rate of 400kHz. If this value is fixed, it would be a lot more easy to do the processing that I want to do (FFT, Correlation)

If you plan on doing a real analysis on it a freerunning adc is not the way to go... You need precise timings for this. If you want to know what is the maximum speed you can achieve, go with the pin toggle or the multiple adc conversions techniques, but even if you manage to achieve a 400kHz sample rate then you have to actually process each sample and present results in less than 2.5 us...

No answer, but I'd be interested in this as well.

Measure how many times per second was main loop called:
bool secondPassed()
{
  static long lastTick = 0;
  long now = millis();

  if (now <= lastTick + 1000)
    return false;

  lastTick = now;
  return true;
}

int counter = 0;
void loop()
{
  analogRead(A0);
  counter++;
  if (secondPassed())
  {
    Serial.println(counter);
    counter = 0;
  }
}


text:
Issues with analog microphone readings
I'm having issues with sampling audio with a microphone and NodeMCU v3. I realize this is the Arduino section so if NodeMCU running the Arduino IDE is not meant for this forum, let me know.
The problem: I am sampling audio for an sound reactive RGB LED strip with the NodeMCU v3. When I use USB power from my computer, everything works well. If I power the NodeMCU from a 7805 linear regulator (5v) to Vin, it works fine. "Silent" conditions hang around 0 volts and audio levels show up clearly. When I power the NodeMCU with a 3.3v switching regulator (with the microphone grounded on the NodeMCU and VCC coming from the 3v3 pin) this is where the problem starts. If I have the LED strip unconnected, it detects the sound find (although my "silent" conditions hover more around .1 volts but for my purposes that wouldn't be an issue).
The problem is powering the board and subsequent microphone from the switching regulator with the lights connected I get very erratic voltage readings that are all over the place. You might be asking why not just use the linear regulator then? Well, even at 12 volts the (12v-5v)*(a few hundred mA) is a decent amount of heat to dissipate but sure I could get a heat sink and control it, but the end goal for this project is to power my 10m strip, which is 24 volts, and the linear regulator would have to dissipate (24v-5v) * (a few hundred mA). I really do not think this is sustainable, which is why I got the switching regulator in the first place.
I was told that these switching regulators do not play nicely with microphones. Even with the LED strip unconnected it wasn't as consistent as USB or linear regulator power but it still worked perfectly fine.
Could anybody explain why this issue arises and hopefully a way to fix it? Are there tricks I can use to limit whatever interference is occurring? Should I give up on trying to make the switching regulator work? Would capacitors/resistors solve this?
I really would prefer to use the switching regulator for efficiency reasons. My second option wouldn't be the linear regulator, it would be powering the Node from a wall adapter and USB cable to be honest. This is getting quite frustrating. One problem's fix causes another, but I suppose that's how things go sometimes.
I am including a diagram of my setup. Please note the linear regulator should actually be a switching regulator and the board I am using is not the Huzzah, it's the NodeMCU v3.
Components:

NodeMCU v3
Adafruit Electret Mic (won't let me post more links... it's the adj. gain one)
Switching Regulator
N Type Mosfets
RGB LED strip (currently a 5 meter 12 volt 5050 leds, future: 10 meter 24 volt)

If there is something that will solve my issue, I am not worried that it costs $5 versus the linear regulator being

I would really really appreciate any help in solving this issue, this is pretty much the last part of a pretty big and feature-rich controller.
Hopefully I have included as much information as is needed.
Thank you and feel free to ask any questions!

The problems mentioned probably result from electrical interference, and as such might be better addressed in  Electronics Stackexchange.  But here is a quick overview of how to ameliorate the problem: add shielding and filtering.
For shielding, add a housing or braided-wire cable sleeves.  To shield against electrical fields, the housing should be conductive and have no openings larger than the wavelength of the  electrical interference you wish to suppress.  To shield against magnetic fields, it should be made of a ferromagnetic material.  You should have a housing around the switching supply, and can also add housings around any sensitive amplifier circuits.
For filtering, you can add an output filter with a few thousand microfarads of capacitance.  For better filtering, use several large capacitors, with a choke (inductor) to connect each capacitor to the next.  Add ferrite beads on each of the wires out of the power supply.  Besides the large capacitors, add a couple of small ones, eg 0.01 and 0.1 μF before the chain of large filter capacitors, ie, close to the output terminals of the switching supply.  Small capacitors generally have smaller self-inductance and can be more effective than large ones at suppressing high frequency hash.  The big capacitors effectively smooth out lower frequency ripple but if they have much self-inductance may fail to suppress high frequencies.

Thank you for the information! I will try to see if it helps!


text:
How to write an integer value to an RFID tag?
I'm working on a project in which two Arduinos are to be used. Each Arduino is connected to an RFID reader. The first RFID reader should write an integer value to the tag detected, whereas the second RFID reader will read the value that was written by Arduino 1.
I'm facing a problem writing an integer value to the tag. I've found many libraries that include functions that write only strings or characters to the tag. But I need to write an integer. Can anyone help me solve this issue?
Following is code that I found and I tried to edit, so that the write and read functions accept (integer values) as the blockContent. However as expected it didn't work because those functions are defined to accept arrays.
/******************************************
   PURPOSE:  Learn to use the MF522-AN RFID card reader
  Created by      Rudy Schlaf for www.makecourse.com
  DATE:   2/2014
*******************************************/

/*
  This sketch uses the MFRC522 Library to use ARDUINO RFID MODULE KIT   13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
  The library file MFRC522.h has a wealth of useful info. Please read it.
  The functions are documented in MFRC522.cpp.

  Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
  Created by Miguel Balboa (circuitito.com), Jan, 2012.
  Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013
  (Translation to English, refactored, comments, anti collision, cascade levels.)

           This library has been released into the public domain.
*/

#include <SPI.h>//include the SPI bus library
#include <MFRC522.h>//include the RFID reader library

#define SS_PIN 10  //slave select pin
#define RST_PIN 5  //reset pin

MFRC522 rfid(SS_PIN, RST_PIN);

MFRC522::MIFARE_Key key;
char order = 49;

void setup() {
  Serial.begin(9600);        // Initialize serial communications with   the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card (in case you wonder what PCD means: proximity coupling device)
  Serial.println("Scan a MIFARE Classic card");

  // Prepare the security key for the read and write functions - all six key bytes are set to 0xFF at chip delivery from the factory.
  // Since the cards in the kit are new and the keys were never defined, they are 0xFF
  // if we had a card that was programmed by someone else, we would need to know the key to be able to access it. This key would then need to be stored in 'key' instead.

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;//keyByte is defined in the "MIFARE_Key" 'struct' definition in the .h file of the library
  }

}

int block = 2; //this is the block number we will write into and then read. Do not write into 'sector trailer' block, since this can make the block unusable.

byte blockcontent[16] = {"SubScribe______"};//an array with 16 bytes to be written into one of the 64 card blocks is defined!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//byte blockcontent[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//all zeros. This can be used to delete a block.
byte readbackblock[18];//This array is used for reading out a block. The MIFARE_Read method requires a buffer that is at least 18 bytes to hold the 16 bytes of a block.

void loop() {
  /*****************************************establishing contact with a tag/card**********************************************************************/
  // Look for new cards (in case you wonder what PICC means: proximity integrated circuit card)
  if ( ! mfrc522.PICC_IsNewCardPresent()) {//if PICC_IsNewCardPresent returns 1, a new card has been found and we continue
    return;//if it did not find a new card is returns a '0' and we return to the start of the loop
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {//if PICC_ReadCardSerial returns 1, the "uid" struct (see MFRC522.h lines 238-45)) contains the ID of the read card.
    return;//if it returns a '0' something went wrong and we return to the start of the loop
  }

  // Among other things, the PICC_ReadCardSerial() method reads the UID and the SAK (Select acknowledge) into the mfrc522.uid struct, which is also instantiated
  // during this process.
  // The UID is needed during the authentication process
  //The Uid struct:
  //typedef struct {
  //byte    size;     // Number of bytes in the UID. 4, 7 or 10.
  //byte    uidByte[10];            //the user ID in 10 bytes.
  //byte    sak;      // The SAK (Select acknowledge) byte returned from the PICC after successful selection.
  //} Uid;

  Serial.println("card selected");

  /*****************************************writing and reading a block on the card**********************************************************************/
  writeBlock(block, blockcontent);//the blockcontent array is written into the card block
  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

  //The 'PICC_DumpToSerial' method 'dumps' the entire MIFARE data block into the serial monitor. Very useful while programming a sketch with the RFID reader...
  //Notes:
  //(1) MIFARE cards conceal key A in all trailer blocks, and shows 0x00 instead of 0xFF. This is a secutiry feature. Key B appears to be public by default.
  //(2) The card needs to be on the reader for the entire duration of the dump. If it is removed prematurely, the dump interrupts and an error message will appear.
  //(3) The dump takes longer than the time alloted for interaction per pairing between reader and card, i.e. the readBlock function below will produce a timeout if
  //    the dump is used.

  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));//uncomment this if you want to see the entire 1k memory with the block written into it.

  readBlock(block, readbackblock);//read the block back
  Serial.print("read block: ");
  for (int j = 0 ; j < 16 ; j++) {
    //print the block contents
    Serial.write (readbackblock[j]);//Serial.write() transmits the ASCII numbers as human readable characters to serial monitor
  }
  Serial.println("");
}

int writeBlock(int blockNumber, byte arrayAddress[]) {
  //this makes sure that we only write into data blocks. Every 4th block is a trailer block for the access/security info.
  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector
  if (blockNumber > 2 && (blockNumber + 1) % 4 == 0) {
    Serial.print(blockNumber);  //block number is a trailer block (modulo 4); quit and send error code 2
    Serial.println(" is a trailer block:");
    return 2;
  }
  Serial.print(blockNumber);
  Serial.println(" is a data block:");

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),    // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
    Serial.print("PCD_Authenticate() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************writing the block***********************************************************/

  status = mfrc522.MIFARE_Write(blockNumber, arrayAddress, 16);//valueBlockA is the block number, MIFARE_Write(block number (0-15), byte array containing 16 values, number of bytes in block (=16))
  //status = mfrc522.MIFARE_Write(9, value1Block, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print("MIFARE_Write() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 4;//return "4" as error message
  }
  Serial.println("block was written");
}

int readBlock(int blockNumber, byte arrayAddress[]) {
  int largestModulo4Number = blockNumber / 4 * 4;
  int trailerBlock = largestModulo4Number + 3; //determine trailer block for the sector

  /*****************************************authentication of the desired block for access***********************************************************/
  byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
  //byte PCD_Authenticate(byte command, byte blockAddr, MIFARE_Key *key, Uid *uid);
  //this method is used to authenticate a certain block for writing or reading
  //command: See enumerations above -> PICC_CMD_MF_AUTH_KEY_A = 0x60 (=1100000),
  // this command performs authentication with Key A
  //blockAddr is the number of the block from 0 to 15.
  //MIFARE_Key *key is a pointer to the MIFARE_Key struct defined above, this struct needs to be defined for each block. New cards have all A/B= FF FF FF FF FF FF
  //Uid *uid is a pointer to the UID struct that contains the user ID of the card.
  if (status != MFRC522::STATUS_OK) {
    Serial.print("PCD_Authenticate() failed (read): ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 3;//return "3" as error message
  }
  //it appears the authentication needs to be made before every block read/write within a specific sector.
  //If a different sector is being authenticated access to the previous one is lost.

  /*****************************************reading a block***********************************************************/

  byte buffersize = 18;//we need to define a variable with the read    buffer size, since the MIFARE_Read method below needs a pointer to the variable that contains the size...
  status = mfrc522.MIFARE_Read(blockNumber, arrayAddress, &buffersize);//&buffersize is a pointer to the buffersize variable;     MIFARE_Read requires a pointer instead of just a number
  if (status != MFRC522::STATUS_OK) {
    Serial.print("MIFARE_read() failed: ");
    Serial.println(mfrc522.GetStatusCodeName(status));
    return 4;//return "4" as error message
  }
  Serial.println("block was read");
}

It would be easier to show you how if you included a link to the library you are using. And a snippet of the code you are trying to get working.

@MikaelPatel I have attached the code I'm trying to edit.

As I have already said in the question, I need the code to be writing and reading integers as block content or if there's a way to represent integers as a string and still be able to increment them

Let's say you have an array and an int.
unsigned char blockcontent[16];
int number = 15;

To save the int at position 0 of blockcontent, you do this:
memcpy(blockcontent, &number, sizeof(int));

If you want it at another position, do blockcontent+offset.
If you want to read the int from blockcontent, do the reverse:
memcpy(&number, blockcontent, sizeof(int));

That's all there is to it.

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


text:
MATLAB+Arduino+LCD

I am trying to send some integers to an LCD. But it is not working. I have tried in Proteus. Please help. I have uploaded MATLAB and Arduino code below.
MATLAB code:
clear all
clc

 answer=1; % this is where we'll store the user's answer
 arduino=serial('COM1','BaudRate',9600); % create serial communication object on port COM4

fopen(arduino); % initiate arduino communication

while answer
fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): '); % ask user to enter value for variable answer
end

fclose(arduino); % end communication with arduino

Arduino code:
#include <LiquidCrystal.h>
int matlabData;
LiquidCrystal lcd(12,11,5,4,3,2);

void setup() {
  lcd.begin(16,2);
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()>0) {
    matlabData=Serial.read();
    lcd.print(matlabData);
  }
}

What exactly is not working? The LCD?  Setting up the COM port on the host? Receiving serial data on the arduino? What have you tried?

lcd shows nothing.I have given the input with the help of MATLAB but still lcd shows nothing.

Not a Matlab expert, but if you enter '1', doesn't `input' yield the int 1? If sou, you are trying to display not the character '1', but the byte 1.

First, try to write anything to the LCD. Not serial data, just 'hello world'. See if that works.

With the help of ARDUINO,it works.But if I use matlab,it doesn't work.I am gonna upload a pic,take a look....

With the help of ARDUINO,I have tried.It worked.The problem arises when i use MATLAB.

Sigh getting serial ports to work with Matlab is a nightmare. Are you sure that part is working correctly? Try hooking it up to a PC and use an app like RealTerm or TerraTerm to make sure that piece is working correctly.

You can use Matlab's Arduino support package, it allows you to control the Arduino directly without having to write code in the Arduino IDE. I never used it with an LCD though. Here is a link that might help.

I already have installed all the packages required for arduino.This is working for led only.With the help of matlab I can easily control a led.But in case of lcd,I am facing this problem.

while answer
  fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
  answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
  % ask user to enter value for variable answer
end

Is it just me or should asking the user to input something be before printing it?
Also, more importantly, isn't fprintf(arduino, '%s', char(answer)); printing raw bytes? In which case, you would be sending 0x01/0x02. Not a great idea... In your Arduino code, print out on Serial what you are receiving, in [hexa]decimal, not as char.
    matlabData=Serial.read();
    Serial.print("Received: [0x");
    if(matlabData<16)Serial.write('0');
    Serial.print(matlabData, HEX);
    Serial.println("]");

This should give you a better idea whether you received anything, and if so, what.


text:
error: too few arguments to function 'char* itoa(int, char*, int)' byte blockcontent= itoa(order); ^ In file include
I have this statement in my Arduino code :
 byte blockcontent [16] = itoa(order);

and it gives me an error saying:
"Too few arguments to function 'charitoa(int,char,int)'. Even though I've looked for the documentation of itoa function and I found that it accepts one input argument.
Can anyone help me fix this error?

Where did you find this documentation, out of interest? The very first hit I get with Google shows 3 arguments: char *  itoa ( int value, char * str, int base );

@NickGammon https://stackoverflow.com/a/5590395/539490

That "reference" is just a question on Stack Overflow. Underneath that question is the comment: How does option 1 even work for you at all? It's my understanding that itoa() takes three parameters - Questions are often asked because people are unsure about what they are doing.

itoa requires a minimum of 2 arguments.
Reference: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gaa571de9e773dde59b0550a5ca4bd2f00

Thank you, but is it possible to set an array pointer instead of character pointer?

You can probably set a char pointer inside an array of char pointer yes if that is what you mean.


text:
How do I lock out a push button input with a selectable delay?
I have a program i am working on where a relay is turned on -> waits a delay -> then turns off after either one of two things happen: 1) A set timer is reached OR 2) someone pushes a push button to trigger it.
Right now 90% of my code is working and i am stuck on how i go about "locking out" the push button from triggering the relay, for a select-able amount of delay time.
The timer portion of the code, with select-able times, is working. Depending on what analog 1 see's, it will trigger the relay appropriately after the selected time.
I tried to implement this same approach for the lock out timer, using analog 2 , to determine how long of a delay. I used a variable i called LOK to either read the button if it is unlocked (LOK = 0) or if it is locked (LOK =1) to wait the allotted delay time before unlocking and allowing the button to be read again.
I've tried all sorta of things and it still isn't functioning right. Maybe there is a better or simpler way to do this but I've racked my brain, and key word searching isn't helping.
Code below - please forgive random comments. I've been chopping up and moving things around i haven't edited any comments , so some may be from other snippets of codes from other projects.
int DUMP = 2; // Pin connected to big dump relay
int BUTTON = 3; // Pin connected to manual dump push button.
int BUTTONlight = 4; // Pin connected to push button light.

int BUTstate; // Current reading from BUTTON pin
int lastBUTstate = LOW; // Previous reading from BUTTON pin

long lastDebounce = 0; // Last time output was changed
long Delay = 50; // Debounce Time

unsigned long DUMPTIME;
unsigned long LOT;

unsigned long prevTIME;

int a=0;
int d=0;

int LOK = 0;

void setup()
{
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);

  pinMode (BUTTON, INPUT);
  pinMode (BUTTONlight, OUTPUT);
  pinMode (DUMP, OUTPUT);

  digitalWrite(DUMP, HIGH);
  delay(10000);
  digitalWrite(DUMP, LOW);
  digitalWrite(BUTTONlight, HIGH);
}

int readTselector(int pin)
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
{
  int b,c = 1;
  c=analogRead(pin); // get the analog value
  if (c>1000)
  {
    b=0; // buttons have not been pressed
  }
  else
    if (c<1000 && c>600)
    {
      b=1; // button 1 pressed
    }
    else
      if (c<520 && c>400)
      {
        b=2; // button 2 pressed
      }
      else
        if (c>100 && c<400)
        {
          b=3; // button 3 pressed
        }
        else
          if (c<100)
          {
            b=4; // button 4 pressed
          }
  return b;
  }

void loop()
{
  int DUMPTIME = DTselect();
  int LOT = LOselect();

  int reading = digitalRead(BUTTON);

  unsigned long currTIME = millis();

  if ((currTIME - prevTIME) >= DUMPTIME) // Count to 2 minutes
   {
     LOK = 1;
     digitalWrite(BUTTONlight, LOW);
     digitalWrite(DUMP, HIGH);
     delay(10000);
     digitalWrite(DUMP, LOW);
     prevTIME = currTIME;
   }

  if (reading != lastBUTstate)
  {
    lastDebounce = millis();
  }

  if (LOK == 1)
  {
    delay(LOT);
    digitalWrite(BUTTONlight, HIGH);
    LOK = 0;

  }
  if ((millis() - lastDebounce) > Delay && LOK == 0)
  {
    BUTstate = reading;
  }

  if (BUTstate == HIGH)
  {
    digitalWrite(BUTTONlight, LOW);
    digitalWrite(DUMP, HIGH);
    delay(10000);
    digitalWrite(DUMP, LOW);
    prevTIME = currTIME;
  }
  lastBUTstate = reading;
}

int DTselect()
{
  a=readTselector(1);
  if (a==0) // no buttons pressed
  {
    DUMPTIME = 210000;
  }
  else
    if (a==1) // someone pressed a button!
    {
      DUMPTIME = 180000;
    }
    else
     if (a==2) // someone pressed a button!
     {
       DUMPTIME = 150000;
     }
     else
      if (a==3) // someone pressed a button!
      {
        DUMPTIME = 120000;
      }
     else
       if (a==4) // someone pressed a button!
       {
         DUMPTIME = 90000;
       }
  return DUMPTIME;
 }

int LOselect()
{
  d=readTselector(2);
  if (d==0) // no buttons pressed
  {
    delay(20000);
  }
  else
    if (d==1) // someone pressed a button!
    {
      delay(15000);
    }
    else
     if (d==2) // someone pressed a button!
     {
       delay(10000);
     }
     else
      if (d==3) // someone pressed a button!
      {
        delay(5000);
      }
      else
       if (d==4) // someone pressed a button!
       {
         delay(0);
       }
 }

what happened to the account of the OP?

I took your code and did a bit of an edit. You had some useless variables and you where redefining DUMPTIME and LOT in a wierd way. I also define some of your constants as #define's because thats the way you should always do it.
#define DUMP 2          // Pin connected to big dump relay
#define BUTTON 3        // Pin connected to manual dump push button.
#define BUTTONlight 4   // Pin connected to push button light.
#define DELAY 50        // Debounce Time

int BUTstate;           // Current reading from BUTTON pin
int lastBUTstate = LOW; // Previous reading from BUTTON pin

long lastDebounce = 0;  // Last time output was changed

unsigned long DUMPTIME;
unsigned long LOT;
unsigned long prevTIME;

int LOK = 0;

int readTselector(int pin)
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
{
    int c = analogRead(pin); // get the analog value
    if (c > 1000){
        return 0; // buttons have not been pressed
    }
    else if (c<1000 && c>600){
        return 1; // button 1 pressed
    }
    else if (c<520 && c>400){
        return 2; // button 2 pressed
    }
    else if (c>100 && c<400){
        return 3; // button 3 pressed
    }
    else if (c<100){
        return 4; // button 4 pressed
    }
    else return 0; // just in case
    }

long DTselect()
{
    switch(readTselector(1)){
        case 0: return 210000; // no buttons pressed
            break;
        case 1: return 180000; // someone pressed a button!
            break;
        case 2: return 150000;
            break;
        case 3: return 120000;
            break;
        case 4: return 90000;
            break;
        default: return 210000; // default
            break;
    }
 }

int LOselect()
{
  switch( readTselector(2) ){
        case 0:  return 20000; // no buttons pressed
            break;
        case 1:  return 15000; // someone pressed a button!
            break;
        case 2:  return 10000;
            break;
        case 3:  return 5000;
            break;
        case 4:  return 0;
            break;
        default: return 20000; // default
            break;
    }
 }

void setup()
{
    pinMode(A1, INPUT);
    pinMode(A2, INPUT);

    pinMode (BUTTON, INPUT);
    pinMode (BUTTONlight, OUTPUT);
    pinMode (DUMP, OUTPUT);

    digitalWrite(DUMP, HIGH);
    delay(10000);
    digitalWrite(DUMP, LOW);
    digitalWrite(BUTTONlight, HIGH);
}

void loop()
{
    DUMPTIME = DTselect();
    LOT = LOselect();

    int reading = digitalRead(BUTTON);

    unsigned long currTIME = millis();

    if ((currTIME - prevTIME) >= DUMPTIME){// Count to 2 minutes
        LOK = 1;
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
    }

    if (reading != lastBUTstate){
        lastDebounce = millis();
    }

    if (LOK){
        delay(LOT);
        digitalWrite(BUTTONlight, HIGH);
        LOK = 0;
    }

    if ((millis() - lastDebounce) > DELAY && !LOK){
        BUTstate = reading;
    }

    if (BUTstate == HIGH){
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
    }
    lastBUTstate = reading;
}

A different version with a BUTflag variable to keep track of the button press and release. I have not dealt with the DUMPTIME variable but hopefully this will give you an idea of how to use flags so the logic doesn't fail.
#define DUMP 2          // Pin connected to big dump relay
#define BUTTON 3        // Pin connected to manual dump push button.
#define BUTTONlight 4   // Pin connected to push button light.
#define DELAY 50        // Debounce Time

int BUTstate;           // Current reading from BUTTON pin
int BUTflag = 0;
int go = 0;
long lastDebounce = 0;  // Last time output was changed

unsigned long DUMPTIME;
unsigned long LOT;
unsigned long prevTIME;

int LOK = 0;

int readTselector(int pin)
// returns the button number pressed, or zero for none pressed
// int pin is the analog pin number to read
{
    int c = analogRead(pin); // get the analog value
    if (c > 1000){
        return 0; // buttons have not been pressed
    }
    else if (c<1000 && c>600){
        return 1; // button 1 pressed
    }
    else if (c<520 && c>400){
        return 2; // button 2 pressed
    }
    else if (c>100 && c<400){
        return 3; // button 3 pressed
    }
    else if (c<100){
        return 4; // button 4 pressed
    }
    else return 0; // just in case
    }

long DTselect()
{
    switch(readTselector(1)){
        case 0: return 210000; // no buttons pressed
            break;
        case 1: return 180000; // someone pressed a button!
            break;
        case 2: return 150000;
            break;
        case 3: return 120000;
            break;
        case 4: return 90000;
            break;
        default: return 210000; // default
            break;
    }
 }

int LOselect()
{
  switch( readTselector(2) ){
        case 0:  return 20000; // no buttons pressed
            break;
        case 1:  return 15000; // someone pressed a button!
            break;
        case 2:  return 10000;
            break;
        case 3:  return 5000;
            break;
        case 4:  return 0;
            break;
        default: return 20000; // default
            break;
    }
 }

void setup()
{
    pinMode(A1, INPUT);
    pinMode(A2, INPUT);

    pinMode (BUTTON, INPUT);
    pinMode (BUTTONlight, OUTPUT);
    pinMode (DUMP, OUTPUT);

    digitalWrite(DUMP, HIGH);
    delay(10000);
    digitalWrite(DUMP, LOW);
    digitalWrite(BUTTONlight, HIGH);
}

void loop()
{
    DUMPTIME = DTselect();
    LOT = LOselect();

    BUTstate = digitalRead(BUTTON);

    unsigned long currTIME = millis();
/*
    if ((currTIME - prevTIME) >= DUMPTIME && !LOK){
        LOK = 1;
        digitalWrite(BUTTONlight, LOW);
        digitalWrite(DUMP, HIGH);
        delay(10000);
        digitalWrite(DUMP, LOW);
        prevTIME = currTIME;
    }
    else */
    if (LOK){
        delay(LOT);
        digitalWrite(BUTTONlight, HIGH);
        LOK = 0;
    }
    else if(!LOK){
        if(!go && BUTstate && !BUTflag){
            lastDebounce = millis();
            BUTflag = 1;
        }
        else if (!go && BUTstate && BUTflag==1 && (millis() - lastDebounce) > DELAY){
            BUTflag = 2;
        }
        else if (!go && !BUTstate && BUTflag==2){
            BUTflag = 0;
            go = 1;
        }
        else if (go){
            digitalWrite(BUTTONlight, LOW);
            digitalWrite(DUMP, HIGH);
            delay(10000);
            digitalWrite(DUMP, LOW);
            prevTIME = currTIME;
            go = 0;
            LOK = 1;
        }
    }
}

Thanks, but it still isn't functioning right when any other case but 0 on A2 is selected. It seems the push button locks out completely from being triggered at all.

What do you mean by A2? I didnt change any of the logic though. Just tidied up the functions and varibles. The code should look a little more compact now.

Ah ok, and what i meant by A2 was analog 2 input. Now what's happening is if any other value than 0 is read from A2 it seems to cycle through the process twice after each button press. So with LOT being 5000 or 5 seconds, it cycles, waits 5 secs, and instead of resetting the LED and waiting for a new button press, it cycles a second time, waits 5 secs, then resets the LED. Also it will sometimes keep getting stuck in the cycle and resetting.

@AdamAlexander I have added a different version

I can't thank you enough! I need to logically think the flag through a bit more to grasp the concept, but the flags work great! I was able to just editted the DUMPTIME logic a bit to use flags and it is now also working in conjuction with the LOT delay time! Kudos!

No problem. Using a state machine model is really the way to it though in the long run. You should look up state machine theory to get the idea. Don't forget to vote me up cheers.


text:
How do I squeeze code to fit onto an ATTiny
I am using an ATTiny85 for the first time and at compile I receive the following errors
Arduino: 1.6.11 (Windows 10), Board: "Digispark (Default - 16.5mhz)"

C:\Users\Steve\AppData\Local\Temp\build129e80c0e73568918bca55047472d138.tmp/Smoke_Auto-ATtiny.ino.ino.elf section `.text' will not fit in region `text'

c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: region `text' overflowed by 562 bytes

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Digispark (Default - 16.5mhz).

The chip is
Atmel 1344
Tiny85
20SF

I think what is happening is that my code is too big for the board.  Am I right?
Assuming so, ignoring any obvious programming errors (I can't debug for this board until I can upload :P ) how can I squeeze code like this onto an ATTiny?  I am not looking for someone to rewrite it for me, I am more interested in learning where there is any obvious bloat - I suspect the IR library (IRremote Version 2.0.1 June, 2015 by Ken Shirriff : 11Kb)
FWIW this is a project to convert a manually operated smoke machine into an automatic one and be able to manipulate the smoke time and delay via a remote. It works on a Mega, proof of concept complete, I want to shrink the board to fit into the mouse-sized controller if that is possible.
#include <IRremote.h>

long smokeTimeInit = 5000;  // initial smoke time
long smokeWaitInit = 60000;  // initial interval between smoke

long smokeIncrement = 1000; // timer increment value
long delayIncrement = 5000; // timer increment value

unsigned long previousMillis = 0; // this is our stored time
unsigned long currentMillis;  //where we keep count of time

const int smokeOnPin = 2;  // output to relay
int smokeStopped = false; // flag to stop smoke
const int LED = 0;
const long RECV_PIN = 1;  // input from IR receiver

IRrecv irrecv(RECV_PIN);

decode_results results;

long  smokeTime = smokeTimeInit;
long  smokeWait = smokeWaitInit;

void setup() {
  pinMode(smokeOnPin, OUTPUT);
  pinMode(LED, OUTPUT);

  irrecv.enableIRIn(); // Start the receiver

  digitalWrite(smokeOnPin, LOW);  // start with the smoke on
  digitalWrite(LED, HIGH);

}

void loop() {
  if (irrecv.decode(&results)) {

    switch(results.value){
      case 284157975 :
      //more smoke time
        smokeTime = smokeTime + smokeIncrement;
        smokeStopped = false; // smoke on

      break;
      case 284104935 :
      //less smoke time
        if(smokeTime > smokeIncrement){ // don't let the smoke time become less than the increment value i.e. negative
          smokeTime = smokeTime - smokeIncrement;
        }
        else{
          smokeTime = 1000;
        }
        smokeStopped = false;

      break;
      case 284125335 :
      //reduce interval
        if(smokeWait > delayIncrement){
          smokeWait = smokeWait - delayIncrement;
        }
        else{
          smokeWait = 1000;
        }
        smokeStopped = false;  // smoke on

      break;
      case 284141655 :
      // increase interval
        smokeWait = smokeWait + delayIncrement;
        smokeStopped = false;  // smoke on

      break;
      case 284140125 :
      // reset to initial time values
        smokeTime = smokeTimeInit;
        smokeWait = smokeWaitInit;
        smokeStopped = false;  // smoke on

      break;
      case 284148285 :
      // reset but with shorter smoke time
        smokeTime = 1000;
        smokeWait = 60000;
        smokeStopped = false;  // smoke on

      break;
      case 284123805 :
      // reset with short smoke and shorter interval
        smokeTime = 2000;
        smokeWait = 30000;
        smokeStopped = false;  // smoke on

      break;
      case 284131965 :
      // stop
        smokeStopped = true;
      break;

    }

    irrecv.resume();
  }
currentMillis = millis();

if(smokeStopped){  // don't even do this if smoke stopped
    if (currentMillis - previousMillis >= smokeTime && digitalRead(smokeOnPin)==0) {
      digitalWrite(smokeOnPin, HIGH); // turn the smoke on
      digitalWrite(LED, LOW);
      previousMillis = currentMillis;
    }
    else if (currentMillis - previousMillis >= smokeWait && digitalRead(smokeOnPin)==1 ) {
      digitalWrite(smokeOnPin, LOW); // turn the smoke off
      digitalWrite(LED, HIGH);
      previousMillis = currentMillis;
    }
}

}

Please edit your question to include which ATtiny -- memory sizes vary a lot, eg ATtiny13 at 1K Flash, vs 4K and 8K in ATtiny48 and 88.  Also say which IRremote.h library you have -- some on my system are 2670 bytes of source, vs  2844 and  4381 in other versions.

@jwpat7 thanks for that.  I have added that it is an ATTiny 85 and some info about the IRRemote library.

If dumping the Arduino libraries isn't viable then you could try using a 16kB tinyAVR instead.

I just compiled it for a Leonardo and this:
Sketch uses 10,562 bytes (36%) of program storage space. Maximum is 28,672 bytes.
Global variables use 401 bytes (15%) of dynamic memory, leaving 2,159 bytes for local variables. Maximum is 2,560 bytes.

Yes, the message “... Smoke_Auto-ATtiny.ino.ino.elf section .text' will not fit in regiontext'” suggests the code is too big to fit in the 8K available on the ATtiny85.
[In a .elf file, the TEXT section contains executable code.]
In IRremote.h from  Ken Shirriff et al, some comments at line 28 say to disable protocols you don't need:
// Supported IR protocols
// Each protocol you include costs memory and, during decode, costs time
// Disable (set to 0) all the protocols you do not need/want!

By default, about 13 protocols are enabled and three disabled.  If you only use one or two kinds of remotes, you can  disable a bunch of the protocols.
Here are a couple of minor things for reducing memory, etc.:
• Instead of switching on  results.value, a long, you could compute an unsigned int equal to results.value-284100000, since all of your case values start with 2841 and the largest is 284157975.
• Instead of having smokeStopped = false; // smoke on seven times within various cases, and smokeStopped = true; in one of them, set smokeStopped to false before the switch, and drop the seven settings-to-false from within the switch.
• Some of your time-related variables would be better as unsigned long instead of just long variables.
Generally, your code looks clean enough except for those items.  Also, the IRremote code doesn't look bloated; but its tables can take a lot of memory.
Edit 1–
Addressing crowie's comment about using #define instead of const int, one can use #define's, but in general the modern thought is that const int is preferable for type safety.  Typically there is no difference in generated code – aside from type checking, the compiler treats a const int the same way as a #define, ie does not allocate memory for it if it isn't used, or if the value is small, may use a load-immediate instead of fetching a value from memory.
My own preference is to use enum { ... } to declare integer constants.  For example, instead of
const int smokeOnPin = 2;  // output to relay
const long RECV_PIN = 1;  // input from IR receiver

I'd write
enum { smokeOnPin=2, IRinPin=1 }; // Pin# for smoke on and IR input

This is great, learned a lot before I even try to implement it.  With the smokeStopped flags, my thinking was that if the smoke was stopped and I then changed one of the values with the remote, the smoke would start.  But perhaps that is a luxury I can't afford and I will have to have a 'start' button.

Wow...each of the IR protocols uses 500 bytes, chopping the ones I don't need reduced the size dramatically.

and another thing if you have a constant dont use const variables instead use #define and put the variable nmae in all caps . This a convention of c programming ie #define SMOKEONPIN 2

@crowie, see edit 1

@jwpat7 yes thats a good point I tend to use define because I like sticking to pure C. Arduino is different because it blurs the line between C++ and C and they are different languages even though they look the same. But with #define you can still add the type tag onto the end ie. 100U or 100UL or 100.0f, if you want to be specific about type

@crowie, yes, that's true (re type tags)

Or you could switch on (uint16_t) results.value, since all the codes have the same two significant bytes. Or, if you do not expect invalid codes, on (uint8_t) results.value, since the LSB is enough to tell all the valid codes apart.

The avr-nm tool is great for figuring out what is using up all your memory.
You need to get to a command-line in the temporary directory where your program is compiled. You can find this directory by looking at the scrolling bottom window when you compile your program.
You run the tool like this...

C:\Users\passp\AppData\Local\Temp\arduino_build_965235>"C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\avr-nm" -S --size-sort blink.ino.elf

...where in my case...
C:\Users\passp\AppData\Local\Temp\arduino_build_965235 is  the temporary directory that the Arduino was using
C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\ and the directory where the Arduino toolchain was installed
blink.ino.elf is the output generated from compiling my blink.ino sketch.
The -S parameter tells the tool to output the sizes of the symbols listed. By looking at these sizes, we can figure out what is using up all the memory and where to focus our reduction efforts.
The --size-sort shorts the symbols in size order so we can easily see which are the biggest.
The output of the tool on my program looks like...

0080010b 00000001 b click
0080008e 00000001 B datLen
00800088 00000001 b IRcount.1978
00800089 00000001 B msgNum
00800086 00000001 b prevVals.1995
0080008f 00000001 B progDir
00800087 00000001 b sendState.1979
00800109 00000001 b state
0080010a 00000001 b sync
00800092 00000001 B wake
00800066 00000002 D buttonCB
00800068 00000002 D clickCB
0080010c 00000002 B comBuf
00800115 00000002 B datBuf
0000006a 00000002 T emptyCB
00800075 00000002 D holdoff
0080008c 00000002 B ledMode
00800062 00000002 D longButtonCB
0080006f 00000002 d longPressTime
00800090 00000002 b longPressTimer
00000068 00000002 T loop
0080006a 00000002 D mode
00000d00 00000002 T setPort
00800064 00000002 D timerCB
0080008a 00000002 B timerCBcount
00800060 00000002 D timerCBtime
0080007d 00000003 D black
0080007a 00000003 D dark
0080006c 00000003 D outColor
00800077 00000003 D wakeColor
00000da6 00000004 T __mulsidi3
00800093 00000004 b powerDownTimer
00800131 00000004 B prevTimer
00800097 00000004 B sleepTimer
0080009b 00000004 b startTime
00800071 00000004 D timeout
00800105 00000004 b timer
00000a7a 00000006 T disAD
00800080 00000006 b pulseCount.1996
0080009f 00000006 b timeBuf
0080010e 00000007 B blinking
00800117 00000007 B pulsing
00000a80 00000008 T enAD
000000d4 0000000c T setColorRGB
00000a88 0000000e T initTimer
0000005a 0000000e T setup
00000044 00000010 T __do_clear_bss
0080011e 00000013 B fading
0000002e 00000016 T __do_copy_data
00000d66 00000018 T __udivmodqi4
00000a5c 0000001e T initIO
00000ce0 00000020 t sendByte
00000d44 00000022 T __mulhi3
00000822 00000022 T __vector_3
0000006c 00000022 T getTimer
00000d7e 00000028 T __udivmodhi4
00000e18 00000036 T __epilogue_restores__
00000daa 00000036 T __umulsidi3
00000de0 00000038 T __prologue_saves__
000003e8 00000038 T updateLed
0000027c 0000003a T blink
00000d02 00000042 T sendColor
0000008e 00000046 T tileSetup
00000e4e 0000005c T __muldi3
008000a5 00000060 b times
0000035e 0000008a T pulsingUpdate
000002b6 000000a8 T blinkUpdate
00000a96 000000d4 T hsv2rgb
00000b6a 00000176 T main
000000e0 0000019c T fadeUpdate
00000844 00000218 T __vector_2
00000420 00000402 T __vector_9

The second column is the amount of space used by the symbol.
So just looking at the bottom of our list, we can see that much of the space is being used by the functions main, fadeUpdate, __vector_2 , and __vector_9.
main and fadeUpdate are obvious, but the __vector_x functions are actualy interrupt service routines. The actual mapping of numbers to interrupt sources can be different for different chips, so probably the easiest way to figure out what a given vector is would be to comment out the ISR in your code and then do the above process and see which vector evaporates in size.
You will have to look at each function carefully and individually to see how to possible reduce its size, but at least with this procedure  you know where too look!

thats neat I didn't know about that tool


text:
Storing latitude and longitude floats as chars with specified precision
I am receiving lat and long data from a GPS and want to store these numbers in the middle of a sequence of chars.
E.g. lat = -23.123456
long = 135.123456
I am after something like "Your coordinates are -23.123456,135.123456" as an array of chars.
I have tried:
float latitude = -23.123456;
float longitude = 135.123456;

String one = "Your coordinates are ";
String two = ","
String message = one + latitude + two + longitude;

// Convert String to char array
int str_len = message.length() + 1;
char textmessage[str_len];
message.toCharArray(textmessage,str_len);

Serial.println(textmessage);

but the result is: Your coordinates are -023.12,0135.12
How can I correct this?
Thanks in advance!

Does your GPS actually give you floats?  Most output text on a serial port; if you do not need to do numeric operations on the values, perhaps you should just treat them as text all the way through.  Note that if you do use floats, their precision is limited, which may well be the cause of what you are seeing with your fake test data.

Are you sure about your result? I'm trying your code and I get "Your coordinates are -23.123456,135.123456". Just in case you didn't notice, you missing one ;

Regarding the limited precision of the float32 format: for numbers in the range [128, 256) (like your longitude), the unit in the last place is about 1.53e-5, which translates to a resolution of 1.7 m on the surface of the Earth. Assigning the longitude to a float can incur a rounding error as large as half an ulp, or about 85 cm.

Why not simply use the String member function c_str() to access the char array? message.c_str() https://www.arduino.cc/en/Reference/CStr

When formatting serial output is a concern, it's worthwhile to download and use the Streaming.h contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, you can get Streaming5.zip from arduiniana.org.
At present, Streaming.h doesn't support setw() and setfill(), which in ordinary C++ set a field width and a fill character.
However, it does support  four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and endl.
Thus, to print  “Your coordinates are -23.123456, 135.123456” one would write:
Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

Note that unlike the String class, use of Streaming.h does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary .print() and .println() calls.  It should result in somewhat smaller, faster, and more-robust code, by avoidance of String.  Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

Edit 1a: As Chris Stratton points out, Arduino floats don't support 9-digit precision.  I think Arduino floating-point arithmetic is intended to comply with IEEE 754, which sets out standards to be used on modern computers that support floating-point arithmetic.
In the binary32 format used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits.  That equates to about 7.22 decimal digits (ie, 24*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

[Part of] Edit 1b:  In the larger scheme of things perhaps there's no need to create and save a formatted string like that.  It is not useful for computing – the float values are better for that.  It is not needed for communication – another streaming write can be done.

Edit 2 [replaces most of 1b]: Streaming.h  doesn't build any strings, but just delivers the text of its <<-arguments character-by-character to a stream.  However, a PString class at arduiniana can build strings from stream inputs, as in the following example code.
#include <Streaming.h>
#include <PString.h>

char buffer[28];
PString pstr(buffer, sizeof(buffer));

void setup() {
  Serial.begin(115200);
  pstr.begin();     // Empty the buffer
}

void loop() {
  int first=50, second=100;
  pstr.begin();     // Empty the buffer
  pstr << 'X' << first << 'Y' << second << 'T';
  pstr += " hihi ";
  pstr << millis() << endl;
  Serial << pstr;
  delay(1000);
}

Here's what some of its output to Serial looks like:
X50Y100T hihi 263198
X50Y100T hihi 264199
X50Y100T hihi 265199
X50Y100T hihi 266201
X50Y100T hihi 267201
X50Y100T hihi 268201

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator <<, then part of it using concatenation, then some more with <<, then print the string.  Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.

It is possible you may do better than the code in the question, but you will not get the desired precision from an ATmega-based Arduino Uno's float.

Thanks! However I need to save this printed sequence as an array of chars to be used later in the code. Can this be done from the printed Serial <<... ?

@ChrisStratton, reflected in Edit 1a

@Anwar, please see Edit 1b

Although the streaming library is a nice syntax candy, you do not need it to specify the number of digits to print. You can also Serial.print(latitude, 6);.

@EdgarBonet, true.   But if one is doing a bunch of formatting (ie, the “When formatting serial output is a concern” case), Streaming.h helps keep the code compact and more clear than a long series of prints.  (My initial read of the question, possibly wrong, suggested formatting issues rather than getting-a-string issues.)

Thanks for all the input guys. However I am after a solution that does not read the string from the Serial window (as suggested in Edit 1b) as I will eventually use this module without being connected to a computer.

@Anwar, edit 2 explains how to build a string, using PString class.  In any case, 1a and 1b were about how to send data via Serial, with no suggestion about "read the string from the Serial window"


text:
Measuring ADC sample rate - Arduino DUE
I want to measure the conversion rate of an arduino DUE. I know I could just take it from the datasheet but I need to measure it because I am running the ADC in free running mode.
Hints are welcome, I really don't know where to start.

If you have an oscilloscope or frequency counter, toggle a pin at each conversion and measure the frequency with your 'scope (and multiply by two).

Hi! Why I must multiply it by two?

Because toggling will give you one change- one 'edge'- per conversion and you need two edges to make a complete cycle, so the toggling acts as a divide-by-two flip-flop.

I think using an interrupt controlled measurement might provide the best results for you.
Note: you might get more complete feedback using the Arduino forum.
In general the process would look like this:

Set up an interrupt vector for the ADC peripheral (in this case support for ID37).
Setup ADC registers (res, clock etc)
Set up a timer to time the conversion.
Create Active flag and Timer variables for processing inbound timer values.
Start timer and ADC conversion.
Loop waiting for active flag to set (it gets set in the ISR), when detected do average or store timer values, then clear active flag.

This methodology times each individual conversion using a high speed timer, which could mean a lot of values to process. You could equally not time each conversion, but simply set up say a 1 second timer, and count the total number of conversions in 1 second for your particular ADC configuration.
Peripheral ISR

Waiting for Interrupt.
In peripheral ISR, read and store timer value, reset timer, set active flag
Return from ISR

To expand on Jack Creasey's answer, timestamping the samples as they are taken is the most direct way to do it. If you have a block of N samples, the average sample period is simply
$$\frac{Time_{last} - Time_{first}}{N - 1}$$
(Note that there are N-1 time intervals between N samples.)
If you want the sample rate, just invert the expression:
$$\frac{N - 1}{Time_{last} - Time_{first}}$$

However, you can also infer the sample rate from a known signal. For example, you can feed a tone signal into the ADC and count the number of samples between some well-defined feature of the waveform, such as rising zero crossings. If you count N samples, then the sample rate is N times the tone frequency. Averaging over multiple cycles of the tone will give you a more precise measurement.

Apparently MathJax is not enabled here.


text:
ATtiny Mapping PPM Inputs to Move Servo Issue
Short Version:
Not able to get a servo to move to mapped input from RC remote control PPM signal.
Detailed Verison:
I am trying to take an input signal from a hobby RC radio (D4RII receiver ppm stream/one wire) signal and map the values 1000-2000 into 0-180 for a value that is useful for a servo. Initially, I had an issue simply reading the values stored within the array from the TinyPpmReader.h library from DigisparkArduinoIntegration on github.
For background, I am using tiny cores. This was the fist issue that was solved:
Accessing Values From Array Within a Library
Second Issue solved:
Mapping PPM Signals to Servo Values
Now, the last part of the battle is to get the servos the actually move. I have successfully (with help)
1.Made the single array values available to be read via serial console (Uno to ATtiny85) like this - Serial.println(TinyPpmReader.width_us(3));
2.Successfully mapped the values within the ppm array to 0-180 and validated the values are correctly mapped and printed to the serial console like this - Serial.println(mappedval0);
Couple of questions. Is it possible that since the ATtiny 85 only has Timer0 and Timer1 available that pwm wont work? ATtiny 85 datasheet here.  If I understand it correctly, the tinyppmreader library does use an interupt driven process.
I chose to go with the SoftwareSerial library since I don't think it is using any timers (Not really sure).  Or, is this just a simple coding issue? What is my mistake? This will compile and the servo does seem to glitch around but not move according to the mapped ppm stream.
Since my search results are now coming up with my previous questions I am hoping this will help others be able to use ppm / servos with the ATiny 85 since it is so small and perfect for many RC related projects.
CODE:
#include <TinyPinChange.h>
#include <TinyPpmReader.h>
#include <Rcul.h>
#include <SoftwareServo.h>
//#include <TinyServo.h>

int val0;                    // integer to store value
int mappedval0;
#define PPM_INPUT_PIN  4

SoftwareServo myservo;

const int PPM_max_value = 2000; //put the max value of PPM reading result
const int PPM_min_value = 980; //put the min value of PPM reading result

//const byte SERVOS = 1; // how many servos do you have? up to 5 on ATTiny85 and 8 on ATtiny84/2313
//const byte servoPin[SERVOS] = { 1 }; // what pins are your servos on?
// you have the option to give your servos nice names. 0 refers to the first servo pin above, 1 to the second, etc

//#define RIGHTLEGSERVO 0

void setup()
{
  Serial.begin(38400);//attiny tx - rx uno does not work at 9600 baud. Set to 38400 @ attiny 1mhz and uno serial console to 38400 baud
  TinyPpmReader.attach(PPM_INPUT_PIN); /* Attach TinyPpmReader to PPM_INPUT_PIN pin */
  //setupServos();
    myservo.attach(0);
}

void loop()
{
   val0 =TinyPpmReader.width_us(3);   //get PPM reading result from index 4
   mappedval0= map(val0, PPM_min_value, PPM_max_value, 0, 180);
   myservo.write(mappedval0);
   //moveServo(RIGHTLEGSERVO, mappedval0);
   //Serial.println(mappedval0);
   SoftwareServo::refresh();
   delay(50);

}

I have commented out the tinyservo library parts while testing the SoftwareServo library.

Does your Tiny have a crystal? That would provider beter timing, but i'm not sure if that is the real problem here. It may indeed be re-using some of the hardware peripherals. And why not use an Atmega328P?

Have you tried contrilling a servo withouth all the other parts of the code? Basically running the servo libraries examples and doing some sweeps. And do you know if you're using a 1mhz (using prescaler) internal clock or 8mhz?

As Paul suggested in 2nd comment, see if you can get the servos to sweep back and forth.   ¶ If you get them to work with numbers in range 0 to 180, next try out your numbers 1000 to 2000 as the argument to myservo.write.  Look at the code for servo::write and you will see that parameter values above 544 are treated as microseconds and used without translation.

Yes, I used a 10k pot to test before moving to the ppm stream. jwpat, why would I need to try 1000-2000 if the values should be 0-180 for the servo?

Another little detail about the behavior is that the servo twitches in sync with the delay(50) variable.


text:
Control the "TV remote"
My idea is to use Arduino to control the TV remote. Not make the Arduino become a TV remote, I want to make an Arduino that can touch button of a remote control.
Any ideas?

A few more details? Physically touch the buttons? Electrically close them? Which remote?

Please read How do I ask a good question? - people are likely to vote to close this as too broad. Asking if anyone has "any ideas" is a rather broad question. Try to narrow it down to something more answerable.

Sending the signals directly will be a far better idea.

I agree with Chris, if you've got a (unconventional) design choice or limitation, you may want to expand on it and explain why. There may be other options which fit your limitations. In order to solve a problem, we'll first need to know what problem (and why).

My rather fancy solution would be to make a 3 axis device with x and y controlled by stepper motors and z a simple solenoid to press the buttons.
For extra marks you could add a camera and try to recognise the buttons in software so any remote would work.
How do you plan to control the arduino?  Perhaps with a remote controller?

Nice answer. Using a remote to control the Arduino that controls the remote certainly is an interesting idea.


text:
How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser?
We are trying to make an app that generates an Arduino sketch (.ino) using Google's Blockly and node.js, and uploads it to Arduino.
Even after searching a lot, I am unable to find how to build and upload the generated code to the board. Is there any tool or API available for node.js to do the same?
Or could I call some binary for this function. Please help.

The tool for uploading to an Arduino is "avrdude", it's a command line application that Arduino uses in the background. I'm quote dure you can invoke/run it from nodejs

There is also arduino-builder.exe command line tool in Arduino IDE (since 1.6.6) so you can build and upload sketch programmatically.

Or you can install Sudar Muthu's Arduino Makefile (package arduino-mk on Debian-bases OSes), then just require("child_process").exec("make upload", callback);.

There are two things you need to do:

Compile the sketch into a .HEX file
Upload the sketch to the board

The first part can be done with arduino-builder which is part of the IDE since 1.6.6, or you can use one of various Makefile projects on a platform that supports make, or you can manually script it yourself calling the correct avr-gcc and avr-g++ commands. You can check the output of the IDE for what those are.
The second part is done, usually, using avrdude - again see the output of the IDE for the correct command format.

Thanks a lot.. Also can I package only the required files/folders from the Arduino IDE into my software (without any license issues)?


text:
shiftOut using SPI isn't working
I made a sample using two of them using Arduino UNO.
So I did that like this:

(There aren't any resistor on that image, but there are 220ohm resistor on every LEDs.)
And uploaded this code.
//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))

int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0] );
    SPI.transfer( data[1] );
    sbi(PORTB, 4);
}

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

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
}

void loop() {
    _595_out();
}

And this worked as I expected. But, when I changed sketch like this,
//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))
#define CHIPNO 2
int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0]);
    SPI.transfer(data[1]);
    sbi(PORTB, 4);
}

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

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
    Serial.begin(9600);
}

void loop() {
    for(unsigned int z = 0; z < 65535; z++) {
        data[0] = z & 255;
        data[1] = (z & 65280) >> 8;
        Serial.println("A");
        Serial.print(data[0]);
        Serial.print("/");
        Serial.println(data[1]);
        Serial.println("B");
        _595_out();
        Serial.println("C");
        delay(500);
    }
}

74HC595s aren't working. Any LEDs aren't on.
Printing Serial works well. Only 74HC595s aren't working.
And Removing all Serial-related thing doesn't solved this problem.
Where did I do wrong?

Did you do a Serial.begin()? Please post the entire sketch that doesn't work.

shiftOut using SPI isn't working - And this worked as I expected. - so SPI is in fact working?

@NickGammon I just changed the loop function like that and added Serial.begin(9600); ath the end of the setup function. Everything except these is same as the first code, so that's why I didn't upload the entire sketch... And shiftOut using SPI is working when I use first code, but isn't working when I change the code as I said.

@NickGammon What I trying to do is changing outputs of 74HC595 every 0.5sec at very fast speed and that's why I'm using SPI. On first code, it's sending same outputs every loop, and it worked so I just changed that code to send different value every loop. But now it doesn't work. That's what it happened :-P

Why are you wanting to drive AY-3-8910 chips with shift registers...? It sounds like you are thinking of having one AY-3-8910 per shift register pair, which is just plain silly. Do some research about how these kind of chips interface to a CPU bus, which is what they are designed to do.

http://playground.arduino.cc/Main/AY38910 ?

@Majenko Umm...as I know, AY-3-8910 uses 8bit bus for input/output(see this datasheet 36, 41, 43 page), and that's why I am thinking of having one AY-3-8910 per shift register pair. Can I get any information of that research? I'm just a noob to here and don't know about that :-(

The clue here is the word bus. All the AY-3-8910 chips can share the same bus. The only thing that needs to be unique is the equivalent of the address decoding (A8 and /A9 on the chip).

@MikaelPatel Yeah, but I am planning to control 10 of them, so I used 74HC595, just like this. And that above thing is for testing and isn't working :-(

@Majenko Wait for a sec, I couldn't understand yet and got "shock and awe". Can you give me a detail?

An AY-3-8910 chip is only active when A8 is HIGH and A9 is LOW. By only having one chip active at a time all the other signals can be shared. That's 8 data signals, plus BDIR and CLOCK that are common. That's 10 pins for the bus, and a number of pins for selecting chips. That could be one pin attached to A8 and another attached to A9, which gives you 4 AY-3-8910 chips on 12 pins. Add a 2-to-4 decoder in place of the direct A9 connection and you get 8 chips off 13 pins. Change that to a 3-to-8 decoder and you get 16 chips off 14 pins. The Arduino can do that without needing any shift registers.

@Majenko The reason why I paired one shift register per AY-3-8910 is to control multiple chip with different data at one loop. And I'm trying to control AY using two pins, BC1 and BDIR, which are also controlled by another 74HC595 lane(not a paired shift registor lane), so I can control 10 AY-3-8910 using only 6 pins of Arduino. So maybe I can't use that way right now.

Anyway, I really want to solve this shift out problem because I want to use this on another project.

Where does  AY-3-8910 comes from in the comments? There is no mention of it in the question.

@NickGammon Actually it was, but i thought that isn't necessary on my question so i removed that. Sorry for the confusion...

int latchPin = 12;

You use pin 12 as the latch pin. Once you activate SPI the hardware takes over control of the pins MOSI, MISO and SCK. Pin 12 is MISO and thus attempting to change it in your code will have no effect.
You should use some other pin as the latch pin (pin 10 is often used).

And shiftOut using SPI is working when I use first code

shiftOut is a software-based method of clocking out bits. It doesn't use hardware and thus it doesn't take control of pin 12.

Note: Answered originally on the Arduino Forum


text:
Peak counting in serial Arduino
I want to count peak of photocell data with serial communication in Arduino.
Here is the question. My problem is when I count one of the peaks it continues the counting and doesn't stop counting. My project is count Michelson Morley fringes with a photocell and Arduino.
If somebody can help me with the coding part I would appreciate it.
Here is the code that I used:
int count=0;
int val;
int data;

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

void loop() {
  data=analogRead(A0);
  val=map(data,0,1023,1000,0);
  if(val>700) {
   count++;
  }
  Serial.println(count);
  delay(100);
}

This picture shows what I am trying to achieve:

Example Michelson Morley fringes:

keep in mind that since you used
delay(100)

your 'loop' code runs in 10HZ (10 times a second)
So, every time you are lighting on your sensor, if its for longer than 1/10 of a second, you are likely going through several instances of 'loop', in which the condition
(val>700)

is satisfied.
If you know that your peaks are going to take several loops, and only want to count each peak once- a simple way would be to make sure you dropped from the previous peak before incrementing the counter. you can achieve that with something like:
int count=0;
int val;
int data;
bool inPeak = false;

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

void loop() {
  data=analogRead(A0);
  val=map(data,0,1023,1000,0);
  if(val>700) {
     if (!inPeak)
     {
        count ++;
        inPeak = true;
     }
  }
  else
  {
      inPeak = false;
  }

  Serial.println(count);
  delay(100);
}


text:
Help: convert Arduino code to avr-gcc code
I need to convert Arduino code to avr-gcc code. This is code:
#include <Servo.h>

Servo myservo;

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

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

I use Arduino Mega.

I'm voting to close this question as off-topic because this is not a "gimme tha codez" site.

Possible duplicate of Will a .ino Arduino Sketch compile directly on GCC-AVR?

You didn't actually ask a question, you might have asked: "how can I re-implement the servo library in avr-gcc", but that will require quite some effort and a little knowledge from your side.

Try this:
#include <Servo.h>

extern "C" void init(void);

Servo myservo;

int main()
{
    init();
    myservo.attach(11);
    for (;;) {
        myservo.write(67);
    }
}

Note that this still needs the Arduino core library, as the Servo
library depends on it, which means all this is an exercise in futility.
If you are using the Arduino core, the simplest thing is to use it the
Arduino way. If you do not want to use Arduino core, then you will have
to partially re-implement the Servo library.

@user29971: oops, forgot an include, fixed. Do not forget to add all the relevant -I, -L and -l options to the compile command.

compiler code in avr-gcc comand line in linux no include Arduino.h include avr/io.h. thanks Edgar Bonet

i use standard library and registers.

@user29971: If you do not want to #include <Arduino.h>, you can just declare init() yourself, see amended answer.


text:
Possibility of getting a UID on Arduino
Im working on a project where I will be using multiple Arduino (pro mini)'s which emit sensordata through LoRa.
The problem I am currently facing is, when I have multiple sensors, how do I know what data is coming from which Arduino (given they all have exactly the same source-code)?

Does the arduino have a UID like some sort of MAC code?
What could be a solution to give the Arduino a UID?
Do you guys have any other solutions for my issue?

In order to answer #2, I could add a random number calculator to create, but this doesn't feel right to me.

What LoRa modules are you using?

For now Im not using any, but I should be going to use the SX1276 Inair9b. Currently the data comes in over USB, but having no UID will be a problem.

Some LoRa modules contain a UID that you can use, but that one doesn't appear to. You have 4 main options: 1. hard code a UID in the firmware, 2. Provide an interface (UART?) to set the UID in EEPROM, 3. use external configuration switches or jumpers to set the UID, or 4. use an external UUID chip.

Generate a random number and store it in the EEPROM (if after reading the EEPROM returns zero). Or have the base station generate I'd that you can get through Lora.

Add a 1-Wire device such as DS18B20 to your design and use the ROM identity from that.

Possible duplicate of How can I get a unique ID for all my Arduino boards?

@jfpoilpret It is basically the same question, but it did get other answers. And the answers given to the other question didn't 'solve' my problem right away. Also no answer was accepted.
This is one of these questions with multiple answers and therefore I can't really say the other question has the correct answer.

You could use a small silicon serial chip like the Maxim DS2401 (http://pdfserv.maximintegrated.com/en/ds/DS2401.pdf)
An other method is to use good old dipswitches. That way you set each of your 'transmitter' to different address using the dipswitch. On boot the Arduino reads the switches to know it's address and uses that.


text:
How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?
I'm using a Genuino MKR1000 and I want to use the SPI interface, which I've seen that there is no Slave Select (SS)/Chip Select(CS) pin usage.
How can I use the SPI interface with multiple slaves then?

What doesn't have a slave select pin?

I don't know... (question edited to see that there is no SS/CS pin)

Question: how do you use SPI with just one slave...?

I want to use with multiple slaves.

I know, you said. Answer my question first: How do you use SPI with just one slave?

connecting SCK, MISO, MOSI and...SS/CS from master to slave.

SS/CS from master to slave. ... So, if you have no SS pin where do you connect that on the Arduino for ONE slave?

By the way - these are all questions which are intended for you to end up realising the answer for yourself. You should get a penny-drop moment when the answer becomes obvious.

How can I connect multiple SPI devices if I only have one SS pin? The Arduino doesn't need to have a slave pin, since it's the master. You can use any pin to connect to a devices SS pin.

@Majenko thanks. But my slave have SS pin, so I should follow up what Gerben said and choose any pin available for the SS pin, right?

Damn you, @Gerben ;) I was trying to make him answer it himself.

@Gerben I can choose any pin available than, right? Like D3 for instance? And I will need to set this up on the code, right?

@waas1919 Yes, the Arduino doesn't care what pin you use for SS since you just use digitalWrite() on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

@Majenko right:)thanks! You should say that on the answer so I can close this topic:p

Some libraries require a specific pin, but on most you can specify your own.

The Arduino doesn't care what pin you use for SS since you just use digitalWrite() on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.
The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.

How does SPI.transfer knows where to send data?

It sends it out through the SPI port.

If a slave is connected to pin 3, we can set it to low and transfer data. But what if other pins say 4, 5 are also low. Now how does spi knows which is slave select?

Slave select is the pin that is low that is connected to the chip select pin of a slave. SPI neither knows nor cares what it is. If the slave's chip select pin is low then the slave is listening to the bus.

If the number of slaves is large, consider using a multiplexed arrangement for select lines.  As an example, the 16-pin 74LS138 Decoder/Demultiplexer pulls one of eight lines low depending on the state of its three address lines, while the 24-pin 74LS154 pulls one of sixteen lines low depending on the state of its four address lines.  Both of these chips have two or three enable lines, allowing use of two to four of them together to multiply the number of output lines by two to four via use of one or two more address lines.


text:
Graphical programing language for Arduino
I am looking for a graphical programming language for a project of mine, where I am using an Arduino.
It HAS to meet the following conditions:

It supports uploaing sketches to ATmega328 (Arduino Uno/Nano)
New functions can be defined inside the programming enviroment (I am trying to use a motor connected to an H-bridge with a single command block)
The program can run on Windows 7
Libraries can be used inside the code
C++ can also be used to write the code inside the same program
Sketches can be uploaded via Bluetooth 4.0

It would be nice if it met the following condition:

The programming enviroment is easy to use
The graphical programming language is somewhat similar to Scratch
The program can be understood by 10-14 year olds with no programming experience

There is a Scratch extension for Arduino.  I have not used it and I do not know if it satisfies all of your criteria.  http://playground.arduino.cc/Interfacing/Scratch

The most full featured Scratch-like environment for Arduino, to my knowledge that is close to your listed criteria is http://www.mblock.cc/
It's currently in beta development for enabling bluetooth uploads and supports a range of "extension" plugins.  I believe you can also add functionality by writing your own extensions if you have sufficient programming knowledge.
The software has more features if you use their mblock hardware, while offering a reduced set of commands for other boards such as the Uno.

I'm sure you can add library's to your code but at the expense of the scratch-like interface.  A children's visual design tool being able to provide graphical API to libraries written by an open source community is quite a coding challenge.  You can get a feel for this by trying to use any reverse engineering C++ to UML diagram tools.
I recommend perhaps using one of these scratch tools to build simple firmware as a learning tool with the idea of progressing to an actual programming language soon after.
In any case I hope you find what you're looking for among these options for your project.

http://www.mblock.cc/
http://s4a.cat/
http://blog.minibloq.org/p/documentation.html
http://blog.ardublock.com/engetting-started-ardublockzhardublock/
https://www.visuino.com/

Give Visuino a look, they are making noise lately: https://www.visuino.com/

Can you add extensions to it or define functions?