text:
Arithmetic types in Arduino
I'm looking for a complete list of the arithmetic types in the Arduino framework.
On the Internet I found various incomplete lists: sometimes there is short, sometimes word, but other types are missing.
Could someone please provide an exhaustive list of the arithmetic data types in Arduino, including the C/C++ types and the Arduino-defined types (or aliases, e.g. the one created among others in Arduino.h with typedef uint8_t byte;) with a short description? If two types are identical please include both names in the list but making clear that they are the same.

You have integers in 8, 16, 32 and 64 bits, both signed and unsigned. You have float and double, which can be the same thing on some systems.
There are many names given to those variable types, some standard or ubiquitous, some vague or unique, or change depending on which type of CPU you are working with.
The names aren't important, since they only exist in the source code. All that matters is the underlying size. Names of the same underlying size and signedness are interchangeable at will.
For example:

uint8_t = unsigned char
int32_t = long = int on 32 but systems
uint16_t = unsigned short = int on 8 bit systems

As you can see int changes depending on the system you are on. So it is best to stick to specifically named types. I always use the [u]int[N]_t types.
So you have:

uint8_t
int8_t
uint16_t
int16_t
uint32_t
int32_t
uint64_t
int64_t

And:

float
double (if the compiler supports double on the platform you are compiling for, otherwise it is just float).

Arduino itself provides some more unique variable names that are completely nonstandard, such as byte for unsigned char.
In short (pun intended), stick to variables that specifically define their type if you are worried about how big they all are, and avoid all the rest.
For overloading the compiler will automatically "upscale" the variables to the best fitting available function (known as type promotion) unless functions are flagged as explicit, so you can have a function with a long parameter and pass any integer variable up to and including a long in size. The same with float / double types - if your function takes a double you can pass it a float. Useful when you don't know if the target provides a real double or not - just use double and it will work regardless with either double or float.

And all the _Fract and _Accum types in avr-gcc 4.8+.

GCC has introduced all sorts of weird and wonderful types for special jobs. I have never seen any of them actually be used. People tend to use assembly or DSP instructions for optimisation instead of strange types.

The Arduino "language" is actually C/C++. GNU GCC and tool chain are used. The Arduino IDE uses a preprocessor to make it easier for beginners by removing some of the C/C++ requirements such as forward declaration of functions.
The GNU AVR GCC data types and representation, and the answer to your question can be found on the project Wiki page; https://gcc.gnu.org/wiki/avr-gcc
For C/C++ there are build-in data types but also a set of standards. One of the standard header files with data types is stdint.h. http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html
Arduino.h and additional header files within the Arduino core libary contains the extensions or redefinitions made. The complete reference list; https://www.arduino.cc/en/Reference/HomePage
Cheers!


text:
Programming Leonardo with TTL to USB cable
I have wired my Arduino as seen in the picture, with the RX of the cable plugged into the TX (D1) of the Leonardo and the TX of the cable plugged into the RX(D0) of the Leonardo. I then have the ground plugged into GND and the power into 5V. The driver is installed correctly and the IDE recognizes the port, however, whenever I try and upload any sketch, I get the error:
Programmer Type : butterfly
         Description     : Atmel AppNote AVR109 Boot Loader
Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
I can upload sketches fine via usb, is it just unable to do so via a USB to TTL cable?

Thanks in advance

The bootloader on the Leonardo operates through the native USB port of the ATMega32U2 chip, not the UART.
You cannot treat it like an Uno because it isn't an Uno.
You can only program it through the USB port or through the ICSP connector.
If you want to use UART to upload you will need to replace the bootloader with a suitable UART based alternative. (Before you ask, no I don't know if one even exists or where to get it if it does).

That would make sense. I am assuming that the Leonardo can still communicate with other serial devices via the UART correct? I am not very familiar with bootloaders, hence my ignorance...

Yes, that is down to the sketch, not the bootloader.

source: Stack Exchange

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

sort: votes


text:
Using Raspberry Pi to Receive Float from Arduino using NRF24L01
Good day. I've been learning on how to transfer data from Arduino to Raspberry Pi wirelessly using NRF24L01 based on the following reference:
Raspberry Pi 3 Tutorial 14 – Wireless Pi to Arduino Communication with NRF24L01+.
The reason why I want to do this is to log temperature and humidity data wirelessly using DHT22 sensors.
The Arduino code is shown below:
//SendReceive.ino

#include<SPI.h>
#include<RF24.h>

// CE, CSN pins
RF24 radio(9, 10);

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

    radio.begin();
    radio.setPALevel(RF24_PA_MAX);
    radio.setChannel(0x76);
    radio.openWritingPipe(0xF0F0F0F0E1LL);
    const uint64_t pipe = (0xE8E8F0F0E1LL);
    radio.openReadingPipe(1, pipe);

    radio.enableDynamicPayloads();
    radio.powerUp();

}

void loop(void){
    radio.startListening();
    Serial.println("Starting loop. Radio on.");
    char receivedMessage[32] = {0};
    if(radio.available()){
        radio.read(receivedMessage, sizeof(receivedMessage));
        Serial.println(receivedMessage);
        Serial.println("Turning off the radio.");
        radio.stopListening();

        String stringMessage(receivedMessage);

        if(stringMessage == "GETSTRING"){
            Serial.println("Looks like they want a string!");
            const char text[] = "Yo wassup, haha";
            radio.write(text, sizeof(text));
            Serial.println("We sent our message.");
        }
    }
    delay(100);

}

Meanwhile, the Raspberry Pi code is shown below:
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)

pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
# radio.startListening()

message = list("GETSTRING")
while len(message) < 32:
    message.append(0)

while(1):
    start = time.time()
    radio.write(message)
    print("Sent the message: {}".format(message))
    radio.startListening()

    while not radio.available(0):
        time.sleep(1 / 100)
        if time.time() - start > 2:
            print("Timed out.")
            break

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating the receivedMessage into unicode characters")
    string = ""
    for n in receivedMessage:
        # Decode into standard unicode set
        if (n >= 32 and n <= 126):
            string += chr(n)
    print("Out received message decodes to: {}".format(string))

    radio.stopListening()
    time.sleep(1)

Based on the Arduino code above, the code that shows the data that is transmitted is shown below:
const char text[] = "Yo wassup, haha";

Based on the Raspberry code above, the codes that decode the received data from Arduino are shown below:
for n in receivedMessage:
    # Decode into standard unicode set
    if (n >= 32 and n <= 126):
        string += chr(n)

However, these decoding code only works if I transmit string or integer from Arduino to Raspberry Pi. It doesn't work if I transmit float. Since DHT22 records temperature and humidity up until 1 decimal point, it is required for me to transmit float. Can anyone here please teach me how to decode the float values?
Thank you very much.

If you say you only need one digit, why not multiplying your value with 10 (with rounding), transmit it as a 4 byte (unsigned?) integer, and divide by 10 after receiving.
You only need to check if you have little or big endian conversion needed (swapping MSB/LSB 2 byte or single byte). But you see this very fast if you print the values in hex format.

Yes, but keep in mind that an Arduino's unsigned int is 16 bits while a pi's is 32 - you want an unsigned long, or better yet a portable type like uint32_t

@ChrisStratton Fully agree, whenever I want to control my type lengths, I always use (u)int8/16/32_t. This mostly is to reduce space (longer arrays) and sending data to other devices.

But now you used float?

Agree. I was also considering about multiplying the float by 10 in arduino, then transmit the value from arduino to pi, then divide back the value by 10 in raspberry pi. I also need some time to try doing this & will update you guys with my progress later. Thank you very much.

Somebody suggested me to convert the float to string in Arduino, then transmit the string from Arduino to Raspberry Pi throught NRF24L01, then convert back the string to float in Raspberry Pi. I think I will also try that. Below are some of my references:
Arduino - StringConstructor
https://www.arduino.cc/en/Reference/StringConstructor
Parse String to Float or Int
https://stackoverflow.com/questions/379906/parse-string-to-float-or-int
I will inform the result once I tried this.

Note that a string cost more bytes than an integer. E.g. "1234.4" would cost 6 bytes and 12344 2 bytes (assuming the max value can be 65535 and unsigned or -32768..32767 signed).

Instead of converting float to string in Arduino, I think I need to convert the float to char because the example that I refer transmit char from Arduino to Raspberry Pi through NRF24L01. However, I still don't know how to convert the float value to char at this moment.

@foxfaisal dtostrf might help: http://forum.arduino.cc/index.php?topic=85523.0

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


text:
Getting BPM from the given code
I have found code that can blink an LED on Arduino according to Heart Beat. I am using AD8232 as a sensor for Heart Rate.
Code for it is:
//  Variables
int PulseSensorPurplePin = 0; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED13 = 13; // The on-board Arduino LED
int Signal; // holds the incoming raw data. Signal value can range from 0-1024
int Threshold = 550; // Determine which Signal to "count as a beat", and which to ingore.

void setup() {
  pinMode(LED13, OUTPUT); // pin that will blink to your heartbeat
  Serial.begin(9600); // Sets up Serial Communication at certain speed.
}

void loop() {
  Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor's value.
  // Assign this value to the "Signal" variable.
  Serial.println(Signal); // Send the Signal value to Serial Plotter.
  if(Signal > Threshold) {
    // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
    digitalWrite(LED13, HIGH);
  } else {
    digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
  }
  delay(10);
}

My question is: How can I get BPM?
Edited below:
Is this code for BPM correct?
int x = 0;
int LastTime = 0;
bool BPMTiming = false;
bool BeatComplete = false;
int BPM = 0;
#define UpperThreshold 518
#define LowerThreshold 490
int LED13 = 44; // The on-board Arduino LED
int Signal; // holds the incoming raw data. Signal value can range from 0-1024

void setup() {
  pinMode(LED13, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int value = analogRead(0);
  if (value > UpperThreshold) {
    if (BeatComplete) {
      BPM = millis() - LastTime;
      BPM = int(60 / (float(BPM) / 1000));
      BPMTiming = false;
      BeatComplete = false;
    }
    if (BPMTiming == false) {
      LastTime = millis();
      BPMTiming = true;
    }
  }
  if ((value < LowerThreshold) & (BPMTiming))
    BeatComplete = true;
    // display bpm
  Serial.print(BPM);
  Serial.println(" BPM");
  x++;
  Signal = analogRead(0); // Read the PulseSensor's value.
  // Assign this value to the "Signal" variable.
  if (Signal > UpperThreshold) {
    // If the signal is above "550", then "turn-on" Arduino's on-Board LED.
    digitalWrite(LED13, HIGH);
  } else {
    digitalWrite(LED13, LOW); //  Else, the signal must be below "550", so "turn-off" this LED.
  }
}

If you know the interval between heart beats, you can calculate the frequency using the formula: frequency = 1 / time. Now if you take the frequency and multiply it by 60, you should get BPM.
I don't have one of the sensors you are using so I connected a potentiometer to pin A0 to test this code.
    int UpperThreshold = 518;
    int LowerThreshold = 490;
    int reading = 0;
    float BPM = 0.0;
    bool IgnoreReading = false;
    bool FirstPulseDetected = false;
    unsigned long FirstPulseTime = 0;
    unsigned long SecondPulseTime = 0;
    unsigned long PulseInterval = 0;

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

    void loop(){

      reading = analogRead(0);

      // Heart beat leading edge detected.
      if(reading > UpperThreshold && IgnoreReading == false){
        if(FirstPulseDetected == false){
          FirstPulseTime = millis();
          FirstPulseDetected = true;
        }
        else{
          SecondPulseTime = millis();
          PulseInterval = SecondPulseTime - FirstPulseTime;
          FirstPulseTime = SecondPulseTime;
        }
        IgnoreReading = true;
      }

      // Heart beat trailing edge detected.
      if(reading < LowerThreshold){
        IgnoreReading = false;
      }

      BPM = (1.0/PulseInterval) * 60.0 * 1000;

      Serial.print(reading);
      Serial.print("\t");
      Serial.print(PulseInterval);
      Serial.print("\t");
      Serial.print(BPM);
      Serial.println(" BPM");
      Serial.flush();

      // Please don't use delay() - this is just for testing purposes.
      delay(50);
    }

Updated answer in response to your comments below:
The sketch is reading the data and sending the data to the serial monitor every 50ms because of the delay(50). What if we changed that to 1000 ms? The serial monitor would update once per second which would be more "human readable". The problem with that idea is for heart rates faster than 60 BPM, the reading would be inaccurate. I don't have a sensor to test with but I'm guessing a 1 second delay would make the code inoperable.
Before we add more complexity to this sketch we really should get rid of that delay. It would be nice to have one "timer" that we could use to update the BPM calculation and a second "timer" to update the serial monitor every second, or half second, or what ever you want it to be.
We can do that without any libraries using millis(). Here is an updated sketch using millis() for timers. This sketch has the blinking of the on board LED added to it. I'm using an Uno so you'll have to change LED_BUILTIN to what ever pin number you are using.
int UpperThreshold = 518;
int LowerThreshold = 490;
int reading = 0;
float BPM = 0.0;
bool IgnoreReading = false;
bool FirstPulseDetected = false;
unsigned long FirstPulseTime = 0;
unsigned long SecondPulseTime = 0;
unsigned long PulseInterval = 0;
const unsigned long delayTime = 10;
const unsigned long delayTime2 = 1000;
const unsigned long baudRate = 9600;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;

void setup(){
  Serial.begin(baudRate);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop(){

  // Get current time
  unsigned long currentMillis = millis();

  // First event
  if(myTimer1(delayTime, currentMillis) == 1){

    reading = analogRead(0);

    // Heart beat leading edge detected.
    if(reading > UpperThreshold && IgnoreReading == false){
      if(FirstPulseDetected == false){
        FirstPulseTime = millis();
        FirstPulseDetected = true;
      }
      else{
        SecondPulseTime = millis();
        PulseInterval = SecondPulseTime - FirstPulseTime;
        FirstPulseTime = SecondPulseTime;
      }
      IgnoreReading = true;
      digitalWrite(LED_BUILTIN, HIGH);
    }

    // Heart beat trailing edge detected.
    if(reading < LowerThreshold && IgnoreReading == true){
      IgnoreReading = false;
      digitalWrite(LED_BUILTIN, LOW);
    }

    // Calculate Beats Per Minute.
    BPM = (1.0/PulseInterval) * 60.0 * 1000;
  }

  // Second event
  if(myTimer2(delayTime2, currentMillis) == 1){
    Serial.print(reading);
    Serial.print("\t");
    Serial.print(PulseInterval);
    Serial.print("\t");
    Serial.print(BPM);
    Serial.println(" BPM");
    Serial.flush();
  }
}

// First event timer
int myTimer1(long delayTime, long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

// Second event timer
int myTimer2(long delayTime2, long currentMillis){
  if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
  else{return 0;}
}

The code compile size with delay is 4,732 vs the millis timers at 4,682 (with the LED code removed). Two timers for less than the price of one delay :)
The LED will remain on for the duration of the heart beat reading above the LowerThreshold. If you want to have it on longer or decide how long it should be on for, I won't write the code for you but I will give you a hint. You can copy myTimer1() again and make a third timer.

Thank you very much for reply and for editing my question, the code you provided works flawlessly, but i have a LED connected to pin 44, I want to indicate that LED for every Heart Beat, that means when beat happens that LED should blink..
and another thing is : for the first few seconds in the Serial monitor, BPM is showing more than 500 of values - Sometimes it's going to 1000's as well, how to avoid this.?
See my Edit..

See this http://s44.photobucket.com/user/beingmachine/media/Screen%20Shot%202017-08-23%20at%204.00.08%20PM_zpshktk2ucq.png.html


text:
How can I have the user instantiate an object?
So I'm building a MIDI controller. It has a 16-positions selector that lets the user select a "program": a playlist of commands to send to a MIDI instrument.
A push-switch allows the user to scroll through that playlist, running each command in sequence, one at a time.
The way I'm trying to implement this is as follows:
Playlist is a pure abstract class and each Program is derived from it. Each Program would have their own methods for each step, an array of pointers to these functions and a public playNext() method that loop() could call whenever the push-button is pressed with program.playNext()
I'm stuck at the selection of a program stage. I guess I could have an array of pointers to each program and call *arrayOfPrograms[currentProgram]->playNext()
but that would mean I would have to instantiate all the programs in setup() and keep them alive at all times...
Is there a way I could only instantiate the selected program and still call its playNext() method easily?
Sorry for the noob question. I'm fairly new to this and it gets confusing very quickly ;-) Thanks for your help.
Max

You want to be very careful using dynamic objects on such a tiny system.  Do you actually need distinct behavior from these objects?  If not, consider having just one eternal one and passing it some data.  It's not that this is impossible, but on such a tiny system there is very little tolerance for any sequence of operations that could push the memory allocator into fragmentation.  This is a world where you have to code with a mind to how things actually work, not just what is most expressive of ideas.

I could indeed have one single "command runner" and pass it data from arrays but then those arrays should exist in RAM at all time, right? I don't know how big these arrays could become, nor how many should be used. I figured that storing each one in its own object would allow for better RAM usage (provided objects get deleted appropriately of course)

Where is the data coming from?   If internal program flash, you should avoid copying it to RAM at all.  If an external source, you should try to load it only some buffering ahead of as you need it.  You only have 2K of ram, and that needs to handle everything.

You seem like you are almost there. Allocate the objects using new and free with delete.
// Abstract parent
class Playlist {
    public:
    virtual void playNext() = 0;
    // etc.
};
// Derived classes
class Something : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
class SomethingElse : public Playlist
    public:
    void playNext() {
        // your code here
    }
};
// More derived classes......

// A pointer of the current program
Playlist *play_list = nullptr;

// A factory function to create a Playlist while also freeing previous
Playlist * create_playlist(int which_program) {
    // Important - delete old
    delete play_list;
    play_list = nullptr;
    // There are only 16 types, use a switch or if
    switch (which_program) {
        case 1:
            // Create a new one and save in global ptr
            play_list = new Something;
            break;
        case 2:
            play_list = new SomethingElse;
            break;
        // More cases here.....
    }
    return play_list;
}

[edit]--------------------------
Ok. The issue is that C++ does not have a lot of reflection options. So you can't create a class only by its name (as a string). Here's another solution I came up with. It's not completely automatic as it involves registering each class in setup. But I think it's close to what you want:
class Playlist;  //Forward declaration

// Each class will have a function to create itself
typedef Playlist * (*CreateFunc)();

// The parent class. It also holds a list of all child classes
// Could probably refactor into 2 separate classes
class Playlist{
  public:
  // Need virtual dtor
  virtual ~Playlist() {
    delete last_created;
  }

  // Put all the overridable function declarations here
  virtual void playNext() = 0;

  // This has to be called for each child. (See macro below)
  static void register_class(int id, CreateFunc f) {
    all_maps[num_maps].id = id;
    all_maps[num_maps++].f = f;
  }

  // Factory method to instantiate an object
  static Playlist * create_playlist(int id) {
      // Delete old pointer
      if (nullptr != last_created) {
          delete last_created;
          last_created = nullptr;
      }
      for (int i = 0; i < num_maps; i++) {
          // Search the list for name match
          if (id == all_maps[i].id) {
              // Call the creation func
              return all_maps[i].f();
          }
      }
      return nullptr;
  }
  protected:
  // A struct to hold the class name and a pointer to the creation function
  struct Map {
    int id;
    CreateFunc f;
  };
  static Map all_maps[32];
  static int num_maps;
  static Playlist* last_created;
};
// Static declarations
Playlist::Map Playlist::all_maps[32] = {{0, nullptr}};
int Playlist::num_maps = 0;
Playlist* Playlist::last_created = nullptr;

// Example child class
class Child1 : public Playlist{
  public:
  void playNext() {Serial.println("Child1");}

  // Must have this function and it must be static
  static Playlist * create() {return new Child1;}
};
// Another example
class Child2 : public Playlist{
  public:
  void playNext() {Serial.println("Child2");}
  static Playlist * create() {return new Child2;}
};

// Helper macro to simplify registering
#define REGISTER_PLAYLIST(id, name) Playlist::register_class(id, &name::create)

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

  // This must be done for all classes
  REGISTER_PLAYLIST(0, Child1);
  REGISTER_PLAYLIST(1, Child2);

  // Example usage
  Playlist*p = Playlist::create_playlist(0);
  p->playNext();
  p = Playlist::create_playlist(1);
  p->playNext();
}

void loop() {

}

I just whipped this up. Probably room for improvement....

Thanks Johnny! That clears it up a bit. But I'm still stuck with a switch or an if. That'll be a pita when I implement more playlists.
I'd love it if I could find something more convenient...

@Max C++ does not have much in the way of reflection (finding all classes of a certain type, for example). I've updated with another example I think is closer to what you want. Personally, I prefer the first example for its simplicity.

Great! Thx a lot. I'll investigate that.

Well your first suggestion worked great while I was toying around with it and I got to learn quite a lot in the process. Thanks for that ;-) But then I hit another roadblock: because I need the user to select playlists whenever he/she wants, I wrote the switch and therefore the object instantiation in loop()... and I can't find a way to keep the object alive longer than the loop it has been created in. I wish I could just add 'static' to the create_playlist function...

@Max Not sure I understand. The play_list should be a global variable. Once you create it, it exists until you delete it and should be accessible by all parts of your sketch.

...Maybe it is confusing because the function returns a pointer. That's just a copy of the global variable. You can ignore that, and just use the play_list global variable.

You're right, Johnny. I had messed up my code but now it's all fixed and working fine. Thanks to you and the others for your input. Learned a lot, which always a great feeling. ;

I'm not fully understanding the way your sketch should work.
However, I think what you need is some kind of Controller object.
The controller object instantiates one program. The controller also keeps a Boolean to play the next one (playNext). Once the program finishes, the controller can delete the just played program, checks if the Boolean is set to play the next, instantiate the next program to play and play it.
This results that programs are not depending on each other.

Yes that makes sense. Thanks for the idea.

But my problem is even noobier: I don't know how to code it! How do you instantiate an object when you only know which one at runtime?

I don't fully understand ... you can instantiate an object at runtime depending on the switch (or state).

I'm sure I can. I just don't know how to do it efficiently. A switch case would work for now but isn't there a better way? Later, I'll probably implement a way to select more than 16 programs (more like 99) and the switch will be cumbersome to say the least...

In that case I would need more about how it works ...  you have a 16 knob selector for the programs. And each program has commands. And the knob is to loop the current command? So e.g. suppose program 12 is selected. Program 12 has 20 commands, running command 0, than command 1, etc. When you press the button during command 10, command 10 loops until depressed and command 11 is continued? And what happens after command 19? Command 0 is started again of the same program?

Yes except that the commands don't loop. You just run them once and next you press the button, the next command runs, and so on.

The knob lets you select which 'list' of commands you want to run through with the button.


text:
Digital Music Player (SD to USB)
I own a couple of digital in-ear headphones that connect to my phone using USB (some micro, some type C), i.e. they have a built-in DAC and amp. Now instead of having to carry my phone along to listen to music, I'd like to build a portable music player - think of it as an iPod Shuffle minus the DAC+AMP - and I think the Arduino platform should be well-suited for a first prototype(?).
So if I understand correctly, then all I need is the following:

an Arduino board
some storage (i.e. a micro-SD card module)
a serial to USB-C module
some code that streams the files to serial

then "optionally":

a battery
some controls

Am I on the right track?
The headphones connect as USB OTG slave devices, so the Arduino will need to be the master - is that an issue? Also, is it possible to output serial data through the Arduino's own USB port? I've looked around, but my findings are somewhat inconclusive. On the other hand, this might not matter since I will need to power it somehow anyway...
As you may have guessed, this is my first Arduino project, so please be kind ^.^
Thanks!

I think you need to research more about how USB Type-C Audio works, because it most certainly isn't the most standard serial connection people use with Arduinos. One is for sure, you'd have to use either an expensive shield or an 32bit (fast) Arduino to even have USB.

Errrr... no.  Just no.  For a first Arduino project do something else. This will not be possible for you. It won't even be possible for me using an Arduino and I am (as some people say) a demigod.

Haha, alright, only a fool wouldn't trust the word of a demigod. I guess sometimes things aren't quite as simple as they may appear - it's simple to drive an actual speaker, andI assumed taking away the dac shouldn't make things harder. But I guess USB comes with its own set of challenges...thanks for the feedback!


text:
strcat appending multiple times when called in loop
The strcat function is working fine when called for the first time but when the broker goes down and it's attempting to reconnect it is appending the value twice. I am not able to figure out the problem as i am writing C code for the first time.
void reconnect() {

  while (!client.connected()) {
    const char* cid = clientID.c_str();
    if (client.connect(cid)) {
       const char* sTopic = strcat("clm/",cid);
       client.publish(outTopic, sTopic);
       client.subscribe(sTopic);
    } else {
    // Wait 5 seconds before retrying
    for(int i = 0; i<5000; i++){
      delay(1);
    }
  }
}

}
It is called in the loop method
void loop() {
  if (!client.connected()) {
    reconnect();
  }
}

The value of sTopic for the first time is clm/5C:CF:7F:3D:5B:F6 but when the broker restarts and the client connects again it is clm/5C:CF:7F:3D:5B:F65C:CF:7F:3D:5B:F6
What could be the reason for the same ?

strcat won't allocate any memory for the new string. So what really happens is that the location where the string constant "clm/" is stored gets the id appended.
In other words the second time around it's as if you passed "clm/5C:CF:7F:3D:5B:F6" as first parameter.
To fix that you need to supply a proper buffer for strcat to do its work:
if (client.connect(cid)) {
   char[64] sTopic ={0};
   strcat(sTopic , "clm/");
   strcat(sTopic , cid);

Appends a copy of the source string to the destination string.

source
Congratulations, you've broken your string literal. Either stick to using String or make sure you allocate a string properly and then concatenate into that.

You have to cat only one string per time. Your assumption is that it performs
dest = strcat(string_1, string_2)

However, it is:
dest = strcat(dest, string_1)

So you should use
char sTopic[256]; // Max possible length

...

strcpy(dest, "clm/");
strcat(dest, cid);

This will first copy "clm/" to dest, than cid will be concatenated.
(code not tested)
See reference: reference


text:
Can I read two PWM signals and output two square waves on an UNO?
My system requires that I read two independent PWM signals (60hz) and output two corresponding square waves. These output square waves vary in frequency according to their corresponding input duty cycle. The output frequencies will vary between 1-60Hz. (outside of tone() range)
I'm planning out the best way to approach this project.
My initial thought is to use the two available external interrupts set to CHANGE to measure the inputs. I believe I'll also need to reference a timer in this routine, to determine the time since the last change.
Unless I'm mistaken, it looks like I will also need a timer interrupt for each output, to control the frequency properly.
The Arduino UNO has 3 timers. timer0: 8bit (used internally), timer1: 16bit, and timer2: 8bit. In short, can I run all of these interrupts in the same code? Will I run out of timers, or can I multitask the timers between my requirements?
Thanks!

I never used timers/interrupts directly on an Arduino, and it is possible the best way. However, for so slow rates (upto 60 Hz), polling the 2 sensors and even use a delay would still be valid (1000 ms / 60 hz) = 16 ms. That is a lot of time , even for an Arduino.

If I approach it that way, I suppose I could probably read/write all the information with a timer interrupt every 100us or so, as long as I keep the code brief. Resolution isn't a large problem for me here, so that could work - thanks.

You can even not using a timer at all ... if resolution is not a problem, even polling (maybe with one ms delay) could work. But if you want to learn more about a better way, use timers/interrupts.

Your signals are slow enough that you may not need any timer. You can
just use the Arduino micros() function to handle all your timings. Of
course, micros() itself relies on Timer 0, but you don't need to
access any timer directly.
I would use the external interrupts in CHANGE mode to measure the duty
cycle. For example:
const uint8_t INPUT_0_PIN  = 2;  // digital 2 is also INT0
const uint8_t OUTPUT_0_PIN = 4;

// Measured duration of the HIGH level of input 0.
static volatile uint32_t input_0_high_time;

// Interrupt handler invoked when input 0 toggles.
static void on_input_0_change()
{
    static uint32_t time_rise;             // last time the signal rose
    uint32_t now = micros();
    if (digitalRead(INPUT_0_PIN) == HIGH)  // detected rising edge
        time_rise = now;
    else                                   // detected falling edge
        input_0_high_time = now - time_rise;
}

void setup()
{
    pinMode(INPUT_0_PIN, INPUT);
    pinMode(OUTPUT_0_PIN, OUTPUT);
    attachInterrupt(0, on_input_0_change, CHANGE);
}

For handling two inputs, you can duplicate everything that has a 0 in
its name and name it with a 1. If your signal is no slower than
60 Hz, you can also replace all uint32_t by uint16_t to make
the code slightly faster.
For generating the outputs, do something similar to the Blink Without
Delay example:
void loop()
{
    uint32_t now = micros();

    // Determine suitable period for output 0.
    uint32_t input_0_high_time_copy;
    noInterrupts();  // avoid race condition while reading
    input_0_high_time_copy = input_0_high_time;
    interrupts();
    uint32_t output_0_half_period =
            map(input_0_high_time_copy, 0, 16666, 8333, 500e3);

    // Toggle output 0 when needed.
    static uint32_t time_output_0_toggle;
    static uint8_t output_0_state;
    if (now - time_output_0_toggle >= output_0_half_period) {
        time_output_0_toggle += output_0_half_period;
        output_0_state = !output_0_state;  // toggle state
        digitalWrite(OUTPUT_0_PIN, output_0_state);
    }
}

Again, you can handle two outputs by duplicating the code and replacing
0 with 1. Note that you cannot replace uint32_t by uint16_t,
as it would not work for the slowest frequencies.
Edit: Now we may ask the question whether it is possible to use some
timers to make all this more accurate. The answer is yes, you could
achieve maximum accuracy by using four 16-bit timers:

You could use the input capture function of a 16-bit timer, with the
prescaler set to 8, to measure the transitions of one of your
inputs with a resolution of 0.5 µs.
You could use a 16-bit timer in CTC mode, with the prescaler set
to 256, to toggle one of your outputs at the desired frequency, with a
16 µs resolution.

For reference, micros() has a resolution of 4 µs. The 16 µs
resolution of the timer-generated output seems poor in comparison, but
the timer has the advantage of having zero jitter.
Now, for doing that that, you would need an Arduino Mega 2560. The Uno
has only one 16-bit timer, so it could help with only one of your two
channels.
There is still something you can do with a single 16-bit timer. Set it
to normal counting mode, with the prescaler at 8, and use it
instead of micros() for timing your inputs: in setup()
// Configure Timer 1.
TCCR1A = 0;          // normal counting mode
TCCR1B = _BV(CS11);  // clock at F_CPU/8

and in the interrupt handler, you replace uint32_t now = micros(); by
uint16_t now = TCNT1;

And now you have input_0_high_time (which should also be uint16_t)
in units of 0.5 µs.

Your approach is generally sound.
Depending on the square waves you are generating, one timer can generate two pulse train with independent duty cycles but dependent phases.
That leaves two times for measuring the duty cycles of the input pulse train.
But replicating the input pulse trains makes zero practical sense.


text:
Urgent need of help splitting a JSON formatted string received by UDP
I guess that my problems are because I'm new to C, but after spending three evenings without success I thought I'd give it a try to ask here!
I receive a JSON-formatted string in a UDP message. It contains several values that I would like to catch and convert to variables. The string format is like this:
{
  "U1": 224,
  "U2": 227,
  "U3": 224,
  "I1": 0,
  "I2": 0,
  "I3": 0,
  "P": 0,
  "PF": 0,
  "E pres": 639,
  "E total": 69901578,
  "Serial": "16889379",
  "Sec": 393833
}

Actually I really only need to get values U1, U2, U3 and I1, I2, I3. I'm grateful for all the help I can get solving this!
Best regards
Per

Have you tried iterating over the string?

Two possible approaches:

Tokenize the string using strtok(), probably a few levels deep.
This may require you learning quite a bit more about C++, pointers, and character arrays as strings.
An excellent opportunity to use an existing library, such as ArduinoJSON, which abstracts out the difficulties you may encounter if the fields in your JSON string arrive in a different order, etc.

An example of using ArduinoJSON for your case is shown in the documentation (excerpted/adapted from Decoding JSON)
#include <ArduinoJson.h>

// [...] other code

char json[] = "{ \"U1\": 224, \"U2\": 227, \"U3\": 224, \"I1\": 0, \"I2\": 0, \"I3\": 0, \"P\": 0, \"PF\": 0, \"E pres\": 639, \"E total\": 69901578, \"Serial\": "16889379", \"Sec\": 393833 }";

//
// Step 1: Reserve memory space
//
StaticJsonBuffer<200> jsonBuffer;

//
// Step 2: Deserialize the JSON string
//
JsonObject& root = jsonBuffer.parseObject(json);

if (!root.success())
{
  Serial.println("parseObject() failed");
  return;
}

//
// Step 3: Retrieve the values
//
uint16_t    u1 = root["U1"];
uint16_t    u2 = root["U2"];
uint16_t    u3 = root["U3"];
uint16_t    i1 = root["I1"];
uint16_t    i2 = root["I2"];
uint16_t    i3 = root["I3"];


text:
Using Serial as boolean function argument
The following program compiles in the Arduino IDE.
void doSomething(bool) {}

void setup() {
  doSomething(Serial);
}

void loop() {}

But, as expected, this one doesn't:
class MyClass {};

void doSomething(bool) {}

void setup() {
  MyClass myClass;
  doSomething(myClass);
}

void loop() {}

The compiler returns the error cannot convert 'MyClass' to 'bool' for argument '1' to 'void doSomething(bool)'

Why is it possible to compile the former? Isn't Serial a normal class instance (of HardwareSerial)? Does it makes any sense to interpret Serial as a bool?

HardwareSerial defines operator bool(), which allows it to be used in a boolean context.

And what is the purpose of the bool() operator?

Classes define whether and how their instances can be converted to bool, and what the resulting bool means. In the specific case of HardwareSerial, it means the serial port is ready: "This will only return false if querying the Leonardo's USB CDC serial connection before it is ready." — https://www.arduino.cc/en/Serial/IfSerial


text:
Send HTTP get request from GSM SIM800c and Arduino
I am trying to send Get request from my GSM Module but after connecting to server it is not responding any thing
#include <SoftwareSerial.h>
SoftwareSerial myGsm(2,3);
void setup()
{
myGsm.begin(9600);
Serial.begin(9600);
delay(500);
myGsm.println("AT+CGATT=1");
delay(200);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");//setting the SAPBR,connection type is GPRS
delay(1000);
printSerialData();
myGsm.println("AT+SAPBR=3,1,\"APN\",\"wap.mobilinkworld.com\"");//setting the APN,2nd parameter empty works for all networks
delay(5000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=1,1");
delay(10000);
printSerialData();
myGsm.println();
myGsm.println("AT+SAPBR=2,1");
delay(10000);
printSerialData();
myGsm.println("AT+HTTPINIT");
delay(2000);
printSerialData();
myGsm.println("AT+HTTPPARA=\"URL\",\"http://sensor.somee.com/api/Data/GetData?SensorID=1\"");// setting the httppara,
delay(1000);
printSerialData();
myGsm.println();
delay(10000);//the delay is important if the return datas are very large, the time required longer.
printSerialData();
delay(9000);
printSerialData();
delay(1000);
Serial.println("done ");
printSerialData();
}
void loop()
{
}
void printSerialData()
{
while(myGsm.available()!=0)
Serial.write(myGsm.read());
}

and the Out put is
AT+CGATT=1

OK
AT+SAPBR=3,1,"CONTYPE","GPRS"

OK
AT+SAPBR=3,1,"APN","wap.mobilinkworld.com"

OK

AT+SAPBR=1,1

OK

AT+SAPBR=2,1

+SAPBR: 1,1,"10.209.122.68"

OK
AT+HTTPINIT

OK
AT+HTTPPARA="URL","http://sensor.somee.com/api/Data/GetData?Sen
done

Could you solve this problem?

You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send
AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using
AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format
+HTTPACTION: <Method>,<StatusCode>,<DataLen>

this will happen after the module will actually do the request and will have the response.

You should place the code to communicate (which is a recurring task) into the loop (and do this without blocking delay()s. Using delay stops the CPU so whatever comes to the buffer is probably not processed.
Read about the difference of placing code in the setup and the loop in the Arduino basic documentation.Never use delay in communiction scenarios (except for intializing hardware in setup) see example blinkwithoutdelay in ArduinoIDE

Calling webservice in a loop :| ?! What do you mean?

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


text:
Arduino crashing during serial print for no obvious reason
I've written some Arduino Code which kept crashing and i couldn't find out why. Then i reduced the code as much as i could in order to see the problem.
The reduced code currently doesn't do anything extraordinary except printing some strings over the serial line.
This is the reduced code:
void setup()
{
  Serial.begin(9600);
  Serial.print("Begin\r\n");
  send_wifi_beacon();
}
void loop()
{
  delay(1000);
}
void send_wifi_beacon()
{
  send_wlan_chip_command("AT+CIFSR");
  Serial.print("notreached"); // this part is never reached
  send_data_over_network(); // can't remove this line otherwise the crash won't happen which is weird since this is never called
}
void read_response_from_serial()
{
  delay(2000);
  Serial.print("==-1\r\n"); // crashes here
}
void send_wlan_chip_command(char* command)
{
  Serial.print("Sending command to wifi module: ");
  Serial.print(command);
  read_response_from_serial();
  Serial.print("Command response: ");
}
// this function is never called, since the crash happens before the call, but it can't be removed otherwise the crash won't happen
// also it can't  be altered then, the crash also will not happen.
void send_data_over_network()
{
  char number[3] = "12";
  //char number[3] = "";
  char length_of_payload[20] = "0123456789012345678"; // 20 digits if assuming 64 bit integer is the maximum this code will ever run on
//  char length_of_payload[20] = "";
  char *command;

  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);
  free(command);
}

This is the according output:

Begin Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin
  Sending command to wifi module: AT+CIFSR==Begin

Which means that the arduino keeps crashing and resetting. This goes on forever.
The weird thing is, if I change the following two lines to: (in the"send_data_over_network" function as in example above)
char number[3] = "1"; // changed from => char number[3] = "";
char length_of_payload[20] = "123"; // changed from => char length_of_payload[20] = "0123456789012345678";

The output now changes to :

I call this behaviour weird since it shouldn't have any influence on the result because this function(send_data_over_network) is never called in the crash example from before.
Troubleshooting options i already tried:

Reinstalling Arduino IDE , i tried with mutliple versions 1.8 , 1.6, 1.4. 1.0
Different Arduino Boards (Arduino Uno and Arduino Mega)
Different Laptops (since i thought maybe it's related to power issues of my laptop)

Maybe it's something obvious and i just can't see it, but i already spent +16h debugging, so help would be really appreciated.

This code looks wrong:
  command = malloc(26);
  command = "AT+CIPSSEND";
  strcat(command, number);
  strcat(command, ",");
  strcat(command, length_of_payload);
  send_wlan_chip_command(command);

First you allocate 26 bytes, then a new string is created, which you strcat to it. This happens in memory that is not allocated (or overwrites other data).
Instead of
  command = "AT+CIPSSEND";

use
  strcpy(command, "AT+CIPSSEND");

Also check that 26 bytes is enough, change it to 128 bytes to be sure (check the correct amount you need later).

If you choose to use malloc() and strings, be sure to initialize the memory to zeros, or strcat will not function as expected.

Not "suspicious". It's "wrong". One can't append to a string constant....Also, you want strcpy, not strcat in your correction.

Ah i wasn't aware that i can't append to a string contant. But it makes sense since it's in a different memory area.
One thing i still don't understand is how this resulted in a crash exactly, since the function was actually never reached. Or was it ? Therefore i would assume that it would crash afterwards, not before the function call.
Can anyone explain this ?
Could this be due to some compiler optimization ?
I accepted your answer as the solution but the upvote doesn't count yet.
Thanks to both of you.

@JohnnyMopp Thanks for the good remarks, I improved the answer.

@KoKIA are you sure the function was not called? The easiest way is to add a print statement before and after the wrong code ... and preferably add a bit after each print command to be sure the information got flushed (not sure if the delay is absolutely necessary). But print statements help a lot (if debugging is not possible like in Arduino).

@KoKlA Also, even if your code worked, you would end up with a memory leak as you immediately re-assign the value returned from malloc. That memory is lost. Also because of the reassignment, you would error on the free().

@MichelKeijzers awesome. you are right, i simply added a delay(x)  between my serial outputs and now i could see that it's actually crashing in the function and the function is in fact called. This means that the Arduino was crashing faster then the serial could print it's characters. Now everything makes sense, i would have never thought of this. Thank you very much

Consider using alloca() instead of malloc(). It allocates on the stack instead of the heap and is automatically freed when the function exits and the stack frame is discarded.

@KoKIA You are welcome ... it takes mostly time to add print statements, but it can make the difference between guessing and knowing.

@Majenko thank you for the alloca() tip, I will definitely use it.

@Majenko and @KoKlA: alloca() is most useful when you do not know beforehand the required size. If that size is a compile-time constant, it's simpler to just declare char command[26].

You are almost certainly running out of memory and have a stack collision with the heap. Dynamic memory allocation and de-allocation is not a good idea when you have less than 2K RAM to work with. If you use malloc() use it only to allocate buffer space and then reuse the buffers. Put your test code entirely in setup and see what happens. Also check the amount of RAM allocated at compile time it may be more than you think.
char *buf1;
char *buf2;

void setup() {
   buf1 = (char *) malloc(10);
   buf2 = (char *) malloc(10);
   .
   .
   // test code here
}


text:
Reason for warning "avr:build doesn't define a 'build.board' preference" when build.board is explicitly set in boards.txt?
I am trying to set up a custom board under the Arduino IDE, but I can not figure out why I am getting the warning...
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt
My "vendor/maintainer" is move38 and my platform is avr, so the path to the boards.txt is...
Arduino\hardware\Move38\avr\boards.txt

Here is my boards.txt that defines the blink board...
blink.name=Blinks Tile
blink.upload.tool=avrdude
blink.upload.protocol=avrisp
blink.upload.maximum_size=15872
blink.upload.maximum_data_size=1024

blink.build.core=blinks
blink.build.board=AVR_Blink

blink.build.mcu=atmega168pb

blink.c.extra_flags=-Wextra -flto
blink.c.elf.extra_flags=-w -flto
blink.cpp.extra_flags=-Wextra -flto
blink.ltoarcmd=avr-gcc-ar

# set F_CPU to 1Mhz for all boards on this platform
build.f_cpu=1000000L

...which would seem to define build.board as AVR_BLINKS.
I think am following the recommendations and template in the official spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification#boardstxt
...but nonetheless the warning persists.
I am using Arduino IDE version 1.8.3 on Windows.
What am I missing here? Is there something special about the value, format, or position of the build.board key that I am missing here?
Thanks!
More notes
Adding the following lines to a working boards.txt file...
build.name=testname
build.f_cpu=4000000L
build.core=blinks
build.board=AVR_BOARD

Will create a menu entry for a new phantom board called testname, but this is not a real board with usable keys. If you compile while that board is selected, you get the warning...
Using board 'build' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Using core 'arduino' from platform in folder: C:\Users\passp\Documents\Arduino\hardware\Move38\avr
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

...despite the fact that the key build.board is explicitly defined.

Do you have a board called Move38 in there too?

Which version of the Arduino IDE are you using? Is that your full boards.txt? I can't reproduce the issue with Arduino IDE 1.8.4.

@Majenko There is no board named Move38. There is only one board in the boards.txt and is is the blink board. The Move38 is the "vendor/maintainer" as per the spec and so is the name of the parent directory- the boards.txt path is Arduino\hardware\Move38\avr\boards.txt. Thanks!

@per1234 I've posed a full boards.txt above, and also the (hard earned!) answer. Thanks for offering to help!

It appears that you can no longer set a global property in the boards.txt file. You must set every property individually inside each board ID, even if they are the same for every board in the file. This seems to contradict the documentation that states that...

The other properties will override the corresponding global properties
  of the IDE when the user selects the board.

Further, if any global key is set directly, then both the board specific keys  and the global keys are ignored.
So in my above boards.txt, setting the the global key build.f_cpu at the end of the file seems to cover the blink.build.board key and prevent it from being copied to build.board when the board is selected. Even if you set the global key build.board directly, this setting is ignored.

In my case: I erase the board configurations that was with problem in the file boards.txt.
These configurations appears between #### ... board configurations... #####.

The line in your boards.txt:
build.f_cpu=1000000L

created a separate board entry with the board ID build, thus the error message:
Warning: Board Move38:avr:build doesn't define a 'build.board' preference. Auto-set to: AVR_BUILD

From your comment:
# set F_CPU to 1Mhz for all boards on this platform

and your answer I see that you expected that line to define a global value for the build.f_cpu property but the Arduino IDE has no mechanism for doing this in boards.txt and I don't believe it ever has. You need to define the properties for each board individually in boards.txt, where they will override previously defined properties of the same name. However, you can define default property values for the hardware package in your platform.txt just as you attempted to do in boards.txt.

With the "build.f_cpu" key defined, I do not see a new board named "build" under the boards menu, and all the keys defined for the "blinks" board (which is properly selected from the boards menu) disappear when the "build.f_cpu" key is defined so even if there was a phantom "build" board now defined, why should it suppress some of the selected board's keys? Thanks!

Also, when I read the line "A configuration file is a list of "key=value" properties" in the spec, I expect that I can set any key to any value in any config file. This does not seem to be true - setting global keys in boards.txt does not actually set the global key. The section on boards.txt says that keys can be set on individual boards, not that they can not be set globally. I think either a bug or a documentation issue or both. – bigjosh 1 min ago

"I do not see a new board named "build" under the boards menu". That's because the board is missing a required property. Try adding the line: build.name=bigjosh.

"why should it suppress some of the selected board's keys". What do you mean by keys?

Adding a name does create a phantom entry in the menu, but does not actually create a board with keys. See new added notes above.Thanks!

Key is anything to the left of the = in one of the prefs files (like boards.txt) as per the spec.

That's because you're setting the key incorrectly. Remember, the first part of the key is the board ID. You need to do it like this: build.build.board=AVR_BOARD.


text:
Specifying port in Ciao.write
As far as I know, Ciao uses port 80 as the default and I haven't found a way of changing the port it attempts to connect to.
I tried using "192.168.0.23:8080" but the Ciao.write() seems to timeout after a while. Is there a way to specify the port to use?
P.S I'm using an Arduino Uno WiFi DevEd

You can't. The factory firmware of Uno Wifi is discontinued.
Uno WiFi and WiFi Link doc


text:
Problems Writing and Clearing 24FC512 EEPROM using Arduino Uno
Solution:
Majenko properly pointed out that I was trying to write across page boundaries and either overwriting or skipping blocks of the EEPROM when I did. This updated write function checks for a page boundary and splits the write into two writes if it is going to write over one.
void writeEEPROMPage(long eeAddress)    {
  int writes = incr;
  bool overflow = false;

  //check for page overrun, adjust writes to fill page and set flag if overrun
  if((eeAddress % 128 + incr) > 127)    {
    writes = 128 - eeAddress % 128;
    overflow = true;
  }
  Wire.beginTransmission(EEPROM_ADR);

  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, writes); //Write the data
  Wire.endTransmission(); //Send stop condition
  eeAddress += writes;

  if(overflow)  {
    delay(5);
    Wire.beginTransmission(EEPROM_ADR);

    Wire.write((int)(eeAddress >> 8)); // MSB
    Wire.write((int)(eeAddress & 0xFF)); // LSB

    //Write remaining data to new page
    Wire.write(rwBuffer + writes, incr - writes);

    Wire.endTransmission();
    eeAddress += incr - writes;
  }
}

Problem:
I am currently working on a project to record sensor readings to a 24FC512 512kb I2C EEPROM and have been teaching myself to read and write properly to this chip using an Arduino Uno. I am having a problem: when I write too many bytes in one I2C cycle, some bytes of data are skipped and not written.
In theory, I believe I should be able to write up to a 128-byte page to the EEPROM and the buffer in the Arduino Wire library should allow me to write up to 32 bytes (including address) in one transmission without modification. However, when I write more than a certain number of bytes, typically 16, and then read back the data from the EEPROM, I notice that the write commands seem to have skipped part of the write.
For instance, when trying to clear pages of 20 bytes at a time using 0xF0 to fill the space I get this result in the first few lines in blocks of 20:
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  55  66  77  88  99  AA  BB  CC
+12 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  99  AA  BB  CC  DD  EE  FF  00
+5 lines of F0
F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  F0  11  22  33  44  55  66  77  88

The section that has not been cleared matches the original pattern in that location. When I reduce the page size to 16 bytes, the problem goes away and everything is written correctly. The uncleared pattern is also periodic after the first three lines, running 12 lines, error, 12 lines, error, 5 lines, error for the rest of the data. When tried with 30 bytes per transmission, it's periodic by 3-8-3 when organized in lines of 30. In all cases the errors have been at the end of each page of transmission.
This has become very frustrating because I'd like to get the data written to the EEPROM in as little time as possible so I can get a good sensor sample rate (currently 24 bytes per sample) and have time to run other functions. Ideally I'd be able to write every 5 ms to increase the sampling rate to the maximum supported by the EEPROM, so I need to solve this problem.
Here is the code I am using to clear and read the contents of the EEPROM. The variable incr holds the size of the writes I want to make, and pin 12 decides whether the program will read the EEPROM (high) or clear the EEPROM (low). I write data to the EEPROM with the commented out array to run my tests. It is based on example programs for EEPROM from Sparkfun.
#include <Wire.h>

#define EEPROM_ADR 0x54

const int incr = 30;
byte rwBuffer[] = {
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0,
  0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0
};

void setup() {
  pinMode(13, OUTPUT);
  pinMode(12, INPUT);
  Wire.begin();
  Wire.setClock(400000);
  long currentSpot = 0;
  if (digitalRead(12)) {
    dumpEEPROM();
  } else {
    while (currentSpot < 64000) {
      writeEEPROMPage(currentSpot);
      currentSpot += incr;
      delay(7);
    }
  }
}

void loop() {
  digitalWrite(13, !digitalRead(13));
  delay(500);
}

void writeEEPROMPage(long eeAddress) {
  Wire.beginTransmission(EEPROM_ADR);
  Wire.write((int)(eeAddress >> 8)); // MSB
  Wire.write((int)(eeAddress & 0xFF)); // LSB
  //Write bytes to EEPROM
  Wire.write(rwBuffer, incr); //Write the data
  Wire.endTransmission(); //Send stop condition
}

void dumpEEPROM() {
  long i;
  int j, readnum, timer = 0;
  Serial.begin(115200);
  timer = millis();
  for (i = 0 ; i < 64000 ; i += incr) {
    //Read all bytes from EERPOM
    readnum = readToBuffer(i);
    for (j = 0; j < incr; j++) {
      if (rwBuffer[j] < 0x10)
        Serial.print("0");
      Serial.print(rwBuffer[j], HEX);
      Serial.print("  ");
    }
    Serial.println();
  }
  timer = millis() - timer;
  Serial.print("Full data dump took ");
  Serial.print((float)timer / 1000, 3);
  Serial.println(" seconds.");
  Serial.end();
}

int readToBuffer(long address) {
  int i = 0;
  Wire.beginTransmission(EEPROM_ADR);
  Wire.write((int)(address >> 8)); // MSB
  Wire.write((int)(address & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(EEPROM_ADR, incr);
  for (i = 0; i < incr && Wire.available(); i++) {
    rwBuffer[i] = Wire.read();
  }
  return i;
}

You are trying to do a page write across a page boundary.

The write control byte, word address and the first data
  byte are transmitted to the 24XX512 in the same way
  as in a byte write. But instead of generating a Stop
  condition, the master transmits up to 127 additional
  bytes, which are temporarily stored in the on-chip page
  buffer and will be written into memory after the master
  has transmitted a Stop condition. After receipt of each
  word, the seven lower Address Pointer bits are internally
  incremented by one. If the master should transmit
  more than 128 bytes prior to generating the Stop condition,
  the address counter will roll over and the previously
  received data will be overwritten. As with the byte
  write operation, once the Stop condition is received, an
  internal write cycle will begin

You are sending blocks of 30 bytes (incr = 30). You have 128 byte pages.

128 / 30 = 4.267 writes per page. The 5th write spans pages. But, in a big bold NOTE in the datasheet:

Page write operations are limited to writing
  bytes within a single physical page,
  regardless of the number of bytes
  actually being written. Physical page
  boundaries start at addresses that are
  integer multiples of the page buffer size (or
  ‘page size’) and end at addresses that are
  integer multiples of [page size – 1]. If a
  Page Write command attempts to write
  across a physical page boundary, the
  result is that the data wraps around to the
  beginning of the current page (overwriting
  data previously stored there), instead of
  being written to the next page as might be
  expected. It is therefore necessary for the
  application software to prevent page write
  operations that would attempt to cross a
  page boundary.

So you write 4 blocks to the first page, then the 5th block fills in the end of the first page then goes back to the start of that page and overwrites what has already been written earlier. Your next page then starts part way through the next block skipping a chunk that you cannot now get to.
You must either do your writes in blocks of an integer division of 128 (so 16 bytes is the largest you can do) or manually detect a page boundary and split your block write into two separate writes - one to finish filling the first page and the next to start filling the next page.

Thank you for correcting my understanding of how pages work and don't work. I'm not sure what I was(n't) thinking when I read that part of the datasheet. I'll update the main post with proper code for handling page boundaries.

Right after each Wire.endTransmission(); you need to insert a delay(5);. The errors you see could be write-related, and/or read related too. You have to let the EEPROM chip process the address request before you start dumping/reading.

I have the line delay(7); in the main program rather than the write function, as I intend to be able to use the writeEEPROMPage function in a program based around a timer interrupt so as to not tie up the processor when it needs to be doing other work.

And you don't have it, at all, for readToBuffer(). It is not only safer, but necessary, to put it right after every Wire.endTransmission();. Try it and see if that influences things. The delay is not optional, and it's there for a reason.

readToBuffer() is reading the EEPROM and to my understanding does not need to wait 5mS to then read or write to the EEPROM.

You seem to know everything and still you come with questions... As I said, try it. You might learn something.


text:
How to "break" a function we made?
This is code about a keypad lock. The user can unlock the device by entering the secret code. To lock it again they press "#" or "*".
I want to let the green LED turn on for about 0.5 seconds then return to the first line of the loop: char key = keypad.getKey();.
The problem is that this code makes the green LED turn on forever after we enter the correct secret code or until we enter "#" or "*".
void loop() {
  char key = keypad.getKey();
  if (key=='*'||key=='#') {
    position = 0;
    setLocked(true);
  }
  if (key==secretCode[position]) {
    position ++;
  }
  if (position ==3) {
    setLocked(false);
  }
  delay(100);
}

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
  }
}

Use bool locked instead of int locked in setLocked it's a waste of space.

@Avamander, doesn't gcc/gpp promote booleans to integers anyway?

@sa_leinad But by declaring it "bool" you let others know that it's either true or false. But if your point is right, it does indeed take away the "waste of space" argument. But by that logic you could better use a unsigned char, since it's an 8-bit platform.

Indeed, I forgot that a Leonardo is 8-bit, so indeed no space will be saved by using bool instead of int this time but it's not a bad habit to have, to try and not waste space. @sa_leinad Yeah, both false and true have integer values and are treated in most cases as such.

I may be missing something, but couldn't you just modify your setLocked function?
void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  }
  return;
}

I tried , but it returns to setLocked function, not ordinary loop.

@AntonyPossible I amended my answer. I'd put the return statement inside the else clause!

I was looking at your loop() and it have some problems, like not counting how many digits did the user input and locking upon receiving a single "#" a
Here is some better way:
char secretCode[] = "1234";
char inputCode[] = "xxxx";
int position = 0;

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

void loop() {
  char key = keypad.getKey();

  if (key == '*' || key=='#') {
    int i = 0;
    //  With 4 input digits, now we compare against secret code.
    while (i < sizeof(inputCode) && inputCode[i] == secretCode[i]) {
      i++;
      }
    //  Set locked only if 4 digits are the same.
    setLocked(i == sizeof(inputCode));
    //  Reset input code array.
    position = 0;
  } else {
    //  Key adding digits to the input code.
    inputCode[position++] = key;
    if (position == sizeof(inputCode)) {
      position = 0;
    }
  }
  delay(100);
}

void setLocked(int locked) {
  if (locked) {
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  } else {
    digitalWrite(redpin, LOW);
    digitalWrite(greenpin, HIGH);
    delay(500);
    digitalWrite(redpin, HIGH);
    digitalWrite(greenpin, LOW);
  }
  return;
}

The problem is that when the device is unlocked with the correct code, you turn the green LED on wait for 0.5 seconds and then you don't turn it off again. So the simple answer would be sempaiscuba's answer.
Personally, I like the fact that the red LED indicates that the device is locked and the green LED indicates that it is unlocked.
The problem that I see with your code is that if the user enters an incorrect number, it doesn't reset, allowing any amount of wrong numbers until it sees the right number. This means that I could come along and press the keypay randomly and after a while I would have pressed every digit in the secret code and it would unlock.
Think of the problem as a state machine. You start with 0 digits correct (ie position==0). If at any time the user presses an incorrect digit (or the * or #), the state machine will reset back to 0 digits correct state. If the user enters the first digit correctly then it progresses to the 1 digit correct state (ie position==1). And so on until all of the digits are correct and the device is unlocked. Due to the simplicity of this state diagram it can be accomplished using a few if statements.
int position = 0;
char secretCode[] = "7890";
char inputCode[] = "????";      // This can be any character and just acts as a placeholder
boolean newKey = false;

void setup()
{
    setLocked(true);
}

void loop()
{
    char key = keypad.getKey();

    // Only process when a new key has been pressed
    if ((key != NO_KEY) && newKey)
    {
      newKey = false;  // Don't enter this if statement again if the key is being held down (used for debounce)

      if ((key == secretCode[position]) && (position < 3))
      {
          // The correct key has been pressed
          position ++;
          if (position == 3)
          {
            // Correct code has been entered (all 4 digits)
            setLocked(false);
          }
      }
      else
      {
        // It must be a wrong key (including * & #)
        // Or the device is unlocked and the user is locking it again.
        setLocked(true);
      }
    }
    else
    {
        // Key has been released (used for debounce)
        newKey = true;
    }
}

void setLocked(boolean locked)
{
    if (locked)
    {
        position = 0;
        digitalWrite(redpin, HIGH);
        digitalWrite(greenpin, LOW);
    }
    else
    {
        digitalWrite(redpin, LOW);
        digitalWrite(greenpin, HIGH);
    }
}

Once unlocked, all you have to do is press any key to lock it again.
Resources:
http://playground.arduino.cc/Code/Keypad

This is wide-open to powerline/timing attacks. Don't  "grade" the pin until all 4 digits have been received. as is, I can quickly tell if the left-most digit is correct, then work my way over to the right in under 36 guesses.

Agreed, however the OP is a beginner and I wanted to keep it simple and as close to his original code as possible.


text:
Arduino - Getting error - 'TCCR2' was not declared in this scope
This code below:
void setup() {
  #if defined(__AVR_ATmega168__)
    // 62.5KHz PWM for the ATMega168 -> only on Arduino pins 9 and 10

    // set prescaler to 1
    // (sbi means "set bit register", cbi means "clear bit register")
    cbi(TCCR1B, CS12);
    cbi(TCCR1B, CS11);
    sbi(TCCR1B, CS10);

    // set fast PWM
    cbi(TCCR1B, WGM13);
    sbi(TCCR1B, WGM12);
    // with fast PWM, the frequency is (CLK/256*prescaler) = 16MHz/256 = 62.5KHz
    // with slow PWM, it is half that speed (31KHz)
  #else
    // 22KHz for the ATMega8 (this is a low frequency)
    TCCR2 = ((TCCR2 & ~0x07) | 0x01); //<ERROR POINTS HERE!
    TCCR1B = ((TCCR1B & ~0x07) | 0x01);
  #endif
}

when verify, generates an error:
In function 'void setup()':
pwm-control-1:185: error: 'TCCR2' was not declared in this scope
TCCR2 = ((TCCR2 & ~0x07) | 0x01);
^
exit status 1
'TCCR2' was not declared in this scope

So far i know this code generates pwm at pin 9 or 10, and designed for ATmega168 or ATmega8. The code came with a .pde extension and I opened it on 'Arduino: 1.8.3' and saved as an .ino file.
Can any one please tell me how to convert this code to work with 'ATmega328P-PU' and for the latest Arduino IDE. And also if there anything else to consider running with this code
I'm not an expert in pwm and timer/controls in micros... just started to learn..
Note: I've only shown the necessary part of the code

Since your problem is with the software delivered with Arduino, this question belongs on Arduino.SE

This issue can happen if you select the wrong board in the Arduino IDE.

Looks like this code is pretty old. It's assuming that any Arduino that isn't using an ATmega168 is using an ATmega8. In reality, the ATmega8 hasn't been used on any Arduino boards in the last ten years or so -- it's pretty much obsolete.
The easiest fix will be to remove the non-'168 branch (between #else and #endif), and make the '168 branch default (remove the #if line). This will probably still fail on ATmega32U4 boards, but at least it'll now work on ATmega328 hardware.

The problem is because TCCR2 is not declared, as there is no register with that name. Maybe you wanted to configure the timer 2, i.e. you meant TCCR2A or TCCR2B instead of TCCR2.
EDIT: analyzing your code, you should definitely write TCCR2B.

Check the datasheet to see if there is a tccrb. Maybe for your device, it is tccra, tccrb, or teerc, ....


text:
GPS and Arduino
I am working on a project with an Arduino Uno. I want to know if the latitudes and longitudes can be input to the Arduino for the Arduino to move to that particular location. If it's possible then which sensors or actuators are to be used? Please also mention some references for me to read and collect the required information.

Try this: http://bfy.tw/DbBj

OK, notwithstanding Majenko's excellent suggestion in the comments above, I played around with Arduino and GPS, so I can probably offer a few pointers.

First, GPS:
All the GPS modules that I have played with give out a series of standard strings of information or "sentences". These sentences are defined by the National Marine Electronics Association (NMEA) protocol. You are going to want to spend some time learning how to use this information.
The most commonly used string in an NMEA sentence is $GPRMC. From this you can extract date, time and position. But there is a lot more useful information in an NMEA sentence, so do your research.
When you have decided which GPS module you want to use, just use Google to search for sample Arduino code specific to that module. That should be enough to get you started.

On the subject of GPS Modules:
There are many available. Just Google search for "Arduino GPS module".
They vary in price from a few GB pounds to well over a hundred GB pounds. It all depends on what you need from it, and what you can afford. Personally, I got very good results from cheap (~ £5 GB) Neo-6M modules (like the one shown here) with some mobile robots I was experimenting with.

Now, I've just typed "Neo-6m GPS Arduino" into Google, and one of the first sites was this Instructable, which has more than enough information to get you going with this combination.

Path planning
Yes, you could give a robot a GPS and a target location and have it plan a route and move to the new location.
Sounds easy doesn't it?
It isn't.
It really, really isn't!
Path planning is a complicated discipline. There is an introductory course on Computational Motion Planning available (free to audit last time I looked) on Coursera if you are interested. It's part of a Robotics "Speciality", so depending on your existing skills, you might want to work through the modules in sequence.
[If you do decide to do all the modules in the Speciality, I shared my notes for some of the modules via my Scribd account. Some of these also contain elements on motion planning. (Be warned, some of them also contain a lot of maths!)]
The best practical advice I can give is to start small.
I tested my robots in a local park, over distances measured in tens, rather than hundreds of metres. I then introduced obstacles (trees) in a different part of the park, and things got a whole lot more interesting! (Not least, of course, because GPS really doesn't like trees! So you have to use other sensors when the robot isn't receiving data from the GPS ...).
And if you think that's complicated, just wait until you introduce "moving obstacles", like people, dogs, cars, bicycles, ...!

Hopefully that will give you some pointers to get you started. When you hit problems with your code (and you're almost certainly going to hit problems with your code!), sites like this will be a godsend.
I really wish Arduino: SE had been around back when I was banging my head against the proverbial wall trying to work out why my code wasn't doing what I expected it to!

See this site, for a practical example:
http://www.instructables.com/id/Arduino-Powered-Autonomous-Vehicle/


text:
Transfer byte-buffer with ENC28J60
How do I transfer a series of byte[256]-buffers to a server with an ENC28J60 Ethernet adapter? I get blocks of uint8_t from an Arducam camera module and I'd like to transfer them to a host. Does somebody have an idea how to solve that? I asked a previous question regarding that topic but now new issues arrived.
This is how the array is filled:
uint8_t temp = 0, temp_last = 0;
byte buf[256];
length = myCAM.read_fifo_length();
while (length--) {
  temp_last = temp;
  temp =  SPI.transfer(0x00);
  if ((temp == 0xD9) && (temp_last == 0xFF)) {
    buf[i++] = temp;
    is_header = false;
    i = 0;
  }
  if (is_header == true) {
    //Write image data to buffer if not full
    if (i < 256)
      buf[i++] = temp;
    else {
      i = 0;
      buf[i++] = temp;
    }
  }
}

What protocol does your "host" use?

UDP, too. But probably I'm bad at writingn a proper receiver. Do you have an advice how this could look like?

Assuming you are using the EtherCard library you can send a UDP packet with:
ether.sendUdp(packet_data, length, srcPort, hisip, dstPort );

Assuming you have already set up your source port and have the destination IP address and port in hisip and dstPort.
The prototype for the function is:
void sendUdp (char *data,uint8_t len,uint16_t sport, uint8_t *dip, uint16_t dport);

The example udpClientSendOnly.ino with the library shows you UDP sending in action.

Thank you, I already did that. But only trash arrives at the receiver-side.

How do you know it is trash? Have you examined the actual data you are getting from the camera to make sure that you are actually sending what you think you are sending?

Yes, when I look at my console on arduino-side I get eg the JFIF-header. But when I make a plain plot of the incoming data from UDP than I cannot find that certain header.

This is what I tried: ether.sendUdp(buf, 256, srcPort, hostip, dstPort);

And you are sure that buf contains that JFIF header at the point of sending?

Well, if I do it in another way, that means, I add the line ether.sendUdp(temp, 1, srcPort, hostip, dstPort); directly behind temp = SPI.transfer(0x00); I'd expect at least the header (which I could recognize) to arrive. But it doesn't.

What OS are you using to receive it?

Right now: Mac OS X, node-js UDP-Server. I can switch to linux, though.

OS X may be fine - not sure what tools are available. Use tcpdump -s0 -X <portno> (that's what I use on Linux) to look at the raw data as it arrives on the computer to see if it's the same as your program says it is.

pktap_filter_packet: pcap_add_if_info(en5, 1) failed: pcap_add_if_info: pcap_compile_nopcap() failed

Do it as root...?

Actually, I missed the word "port" from there too - sudo tcpdump -s0 -X port <portno>

0x0000:  38c9 8624 db62 4c5e 0c90 9e16 0800 4500  8..$.bL^......E.
0x0010:  001d 0000 4000 3f11 0a0e c0a8 583e c0a8  ....@.?.....X>..
0x0020:  5833 10e1 0539 0009 b2ff 0500 0000 0000  X3...9..........
0x0030:  0000 0000 0000 0000 0000 0000            ............

I need to check if that is equivalent to what I've sended.

Also the buffer is maybe to big with 256. I lowered it to 32 for debugging.

I found the header!!!! 0x0000:  38c9 8624 db62 4c5e 0c90 9e16 0800 4500  8..$.bL^......E.
0x0010:  003c 0000 4000 3f11 09ef c0a8 583e c0a8  .<..@.?.....X>..
0x0020:  5833 10e1 0539 0028 143d 04d8 ffe0 0010  X3...9.(.=......
0x0030:  4a46 4946 0001 0101 0000 0000 0000 ffdb  JFIF............
0x0040:  0043 0004 0303 0403 0304                 .C........

Let us continue this discussion in chat.


text:
Linux SSH command for Arduino Console
I have a Leonardo with a Yun shield, and I would like to be able to control the arduino with a windows form app, but thats besides the point for now at least. Currently, I am using putty and the commands Telnet Localhost 6571. However, I would like to avoid doing that and I was wondering if anybody new how to communicate with the arduino from port 22 at the yun's IP, rather than connecting to the yun and then to the remote local machine. That or I am missing something entirely!
This is the code I am using to try and access the console port of the Leonardo:
namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //connect to arduino
            ConnectionInfo ConnNfo = new ConnectionInfo("10.1.1.211", 22, "root", new AuthenticationMethod[] { new PasswordAuthenticationMethod("root", "123456789") });
            using (var sshclient = new SshClient(ConnNfo))
            {
                sshclient.Connect();
                //connect to console port of arduino
                TcpClient tcp = new TcpClient("localhost", 5671);
                sshclient.Disconnect();
            }
            Console.ReadKey();
        }
    }
}

Thank you

The console port is only listening on 127.0.0.1 (for security), so only the Yun itself can connect to the console.
You can weaken security and open the port up to the entire local network by editing the file /usr/lib/python2.7/bridge/console.py and change the value 127.0.0.1 to 0.0.0.0.
Any machine on your local network will then be able to connect directly to port 6571.

Thanks for the help, how would I connect to that port via my pc without using Telnet, I edited the file as per your instructions.

You can use putty in telnet mode to connect direct to the port.

Alternatively you can write your own software in whatever language you prefer to open a TCP connection directly and use it as if it were a serial port.


text:
Coding for a stop button
I'll like to code for a game, and it'll come with a stop option that allows the player to exit/restart the game.
How should I code for that stop button? Do I put it in a separate while loop under the void loop?

You can use an interrupt function.
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

One of the easiest ways to restart your game is to use the inbuilt reset line. The Arduino Uno/Due/M0/101 has a physical reset button next to the USB connector. For some of the other baords like the Arduino Mega, it is closer to the chip in the middle of the board.
The reset line is held high by a pull up resistor. This button shorts the reset pin to Gnd, resetting the microcontroller.
Once reset, the microcontroller starts up again as if it has just been powered on. This has the advantage of saving on adding code to handle the game being reset.

Note that the reset line is also available on a pin header, which can be handy if the OP prefers to wire his own button.

There are lots of possible approaches. One possibility would be to set up your code something like this:
enum { STOPPED, PLAYING } flag;

void setup() {
  // setup stuff ...
  flag = STOPPED;
}

void loop() {
  while (flag == STOPPED)
  {
    // wait for start button
    if (start button pressed)
    {
      // initialise the game ...
      flag = PLAYING;
    }
  }

  while (flag == PLAYING)
  {
    // play the game
    if (stop button pressed)
    {
      flag = STOPPED;
    }
  }
}

And I need to put this code at the beginning of loop()..?

If you code your loop without delay() or busy loops then it is pretty easy:
void loop(){

    if(DigitalRead(RESET_BUTTON)){
       // Reinitialize game state

    }

    //rest of game logic.

}


text:
Problem reading in Arduino serial port with 5K potentiometer
I have written code to see values of a 5K potentiometer from 0 to 1023. Whenever I rotate the knob, the value should change from 0 to 1023. I have connected the potentiometer to the Arduino's pin A1, but there is a problem with readings. Whenever I am rotating the potentiometer's knob, the serial port is only showing 1023. Please help.
void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A1);
  Serial.println(sensorValue);
  delay(500);
}

Please show your actual wiring.

It sounds like it might be a wiring problem. Check that you have the potentiometer connected correctly. Your circuit should look something like this:

I have checked connections there is no problem with them . i dont have an idea why its only showing 1023 value .i interchanged the voltage and gnd then it showed 0 in serial port.

@shwetashrama: If your wiring is correct (which I doubt), then your potentiometer is broken.

is there any specification which one has to keep in mind while choosing a potentiometer like current rating etc.

@shwetashrama Not for applications like this. Try connecting a multi-meter across the terminals of the potentiometer to check the resistance, and verify that it changes as expected when you rotate the knob.

i have checked resistance and voltage both ,there is no problem with them

Disconnect the pot and take some readings. You should get some random values near zero. That would mean you're not connecting the leads right or the swinger is stuck at one end.


text:
Arduino Nano + RFID RC522 + Ethernet shield W5100
I have this Arduino Nano, Ethernet shield W5100 and RC522 as card reader. They are sharing pins D13, D12, D11, D10 is SS pin for W5100 D8 is SS pin for RC522. Problem is with pin D12, like it doesn't share it.
For example if I unplug D12 from W5100 RC522 reader works, if I wire it back it doesn't work anymore. W5100 works no matter if RC522 is wired or not, so problem would be somehow with pin D12.
Does anybody have some ideas, what I'm doing wrong right here?

I had almost exactly this situation with one of my projects.
The problem is that some Serial Peripheral Interface (SPI) devices don't properly put the MISO pin into high-impedance when SS is pulled high. I eventually resolved this by placing a tri-state buffer in the MISO line for each of the SPI devices.
I used a 74HC125 (4-channel tri-state buffer).
This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

Can you tell me little bit more, because I don't understand it very well. I'm kind a new into Arduino and IoT projects and also in electronic's part.

@noname I'm just looking for the page the got me on the right direction. Bear with me for a few minutes ...

@noname I've added the link. Hope that helps you out.

Does this change contains also any hardware changes?

@noname That depends on whether your RFID & Ethernet shield already have tri-state buffers on the MISO line. Mine didn't, so I had to add the 74HC125.

This doesn't help me really a lot...


text:
How to restart USB subsystem?
I'm developing on the Arduino platform (ESP8266 with USB -> serial) and sometimes the USB port that is being used stops working and gets frozen. Then I need to plug the device into another USB port. It happens again and once all the USB ports stop working I have to restart the machine, which is really annoying.
As far as I remember there is a command that can restart the USB subsystem individually, but I can't remember. How to restart USBs without restarting the entire system? Thanks.
I'm using Mac OS X Sierra.

Is that the same problem that was being reported here?

I'm using a USB to serial converter, not an Arduino board. Also, the device disappears from /dev/cu.SLAB_USBtoUART and not even a USB drive can be connected from that point on.

I see you asked the question here: https://apple.stackexchange.com/questions/295993/how-to-restart-usb-subsystem and they sent you to Arduino.SE. Did you try the USB Prober.app?

You are using a USB to UART adaptor. The Arduino has no concept of what that is - it just sends and receives UART data. The adaptor is completely separate and the Arduino can do absolutely noting at all with it.
If you are powering the whole circuit through that adaptor it may well be that it only requests 50mA from the computer. If you draw more than that (which you most likely are) the computer is free to shut the port down. It sounds like that may be what is happening.
What can you do? Well, two things:

Use an adaptor that requests enough current for your needs (may be hard to find)
Power your circuit separately using another power source.

Of the two I would suggest external power.

Thanks, I'll try your suggestion and come back with the result.

You're probably thinking of kext[un]load.
sudo kextunload /Library/Extensions/SiLabsUSBDriver.kext
sudo kextload /Library/Extensions/SiLabsUSBDriver.kext


text:
Switching between SPI Devices when one is an SD card
I'm using a USB Barcode scanner connected via a USB shield, I'm able to get the readings from the barcode using this example, After getting this readings, I'd like to save it to an SD card but the SD card won't initialize since the barcode also uses SPI, how can I deactivate the ICSP in order to activate the SD card? Or how to switch between multiple SPI slaves?

Possible duplicate of How to access multiple SPI interfaces on Arduino

@LookAlterno If someone can answers how to tristate a buffer or use a multiplexer to circumvent the SD problem, it might be a useful addition and not fully a duplicate.

with SPI there is an implicit slave select pin on each device that must be pulled low to enable the device.
Connect each slave select pin of the SPI device to their own unused digital pin on your arduino and keep it pulled high until you want to talk to the slave.
However not all SPI devices will properly put the MISO pin into high impedance when SS is pulled high so you may need to use a tristate buffer on that pin or use a multiplexer.
When adding your own tristate buffer (for example a HS125) you need to connect each MISO pin of the SPI device to the input of a buffer, the slave select is then connected to the output enable pin of the tristate. The outputs of the buffers can be connected together along with the MISO pins of the devices that do properly go high impedance to the MISO of the master.
When using multiplexers there are 2 options:

You can daisy chain 2:1 multiplexers by connecting the MISO of the device to the 0-input of the mux and the Slave select to the select input pin of the mux.
you can use a >2 multiplexer to select the correct MISO line based on the address of a set of S lines. Then with a decoder you can provide the actual SS signal to the SPI device. This way you only need 2 SS pins for 4 SPI devices.

SD cards are notoriously bad at playing nicely with other devices on the same bus. Especially with some adaptors with poor logic level shifting circuits.

I can confirm this ... I had so many problems using a (cheap) SD break card and (SPI) SRAM together, that I eventually bought a separate SD logging card. But I wonder how to implement that 'buffer' or what multiplexer (and how to use it) ... Can you explain this a bit plase?

Refer to the schematic below for a visual explanation of what is explained in this thread regarding a tri-state buffer.  I have used this circuit successfully on a PCB.
I got this schematic from:
© 2017 Vishnu M Aiea. www.vishnumaiea.in


text:
Analog output low voltage issue, how to troubleshoot
I have connected my arduino according to the schematics in the image, with a few additions.
The setup

A DC motor (water pump) drawing power from Vin, going to ground via a transistor based in A0 analog output. Between the transistor and A0 is a 270 ohm resistor. In parallel to the motors poles is a diode, for protection.
A 3,1" (4x20) LCD screen with an I^2C chip (draws 5V, A4 and A5 and GND)
A Potentiometer directly on the I^2C chip LED pins (replacing the jumper) - for control of the light intensity. (Vin and middle pin of pot, gnd unconnected)
A Potentiometer connected to A1, 3,3V and GND.

Code description:
Using the Timer and the LiquidCrystal_I2C library,
Once every other second the LCD is refreshed
Once every day the water pump is started with an analogWrite(A0, HIGH) and it runs for 1-60 seconds based on the potentiometer setting.
The issue.
It seems the output of A0 does not deliver enough voltage to trigger the pump. This is a new error, before I got the screen, it ran the pump fine.
I suspect one of three things. 1: I have broken something in the arduino power regulator, and the voltage outputs on analog pins are lower than they should be (or their ability to supply current) -> Must get new arduino. 2: I have somehow saturated the ground pin or there is a connection issue. 3: The LCD display is drawing too much current. (Leading to either 2 or 1, but won't be fixed by getting a new arduino)
What have I already tried
I have tried, with the arduino connected via mains to short it between 3,3V and the transistor base, and then it runs. So the transistor is OK, the pump is OK. I have tried to map the output to another analog pin to display the value of this pin while the program is running, and it does display a value while the pump is supposed to be running, so it is doing something. I have used a multimeter to measure the pins, but I really don't know what "normal" is so I decided to stop fiddling around with that. I have also tried using other analog outputs (excepting 4 and 5, they are claimed by the lcd I^2C logics)
Can anyone of you please give me some pointers in the right direction, to help me to determine the error in question? What should I try?
Disclaimer, due to having the normal issues of life, love and the fact that a day only has 1440 minutes, I usually only have time to work on my pet projects during weekends...
If this question is not relevant or poorly written, please let me know, I'll try to clarify (or delete it).

Looks to me like your transistor is wired backwards...

@majenko It is drawn backwards then. I am not entirely sure which side of the icon is e and c.... The circuit works.

The arrow is on the emitter. It should be flipped left/right.

The analog pins are for analog input not output. You can only use them for digital output.
Change
analogWrite(A0, HIGH)

to:
digitalWrite(A0, HIGH)

analogWrite() can only be used on PWM capable pins (the ones marked with ~). On any other pin it sets the pin HIGH if the analog value > 127 and LOW if the analog value <= 127.
Since you are writing HIGH, which is equal to 1, the output is LOW because 1 < 127.

Thanks for the clarification. I was under the illusion that digitalwrite only produced a pulse. I will test this at the earliest possibility and report back.

No, digitalWrite sets a HIGH or LOW output. To send a pulse you have to use two digitalWrite calls - one to set it HIGH and then one to set it LOW. Where did you get the idea that digitalWrite creates a pulse?

Confirmed as solution, thank you to both juraj and @Majenko. I learned something new and useful! (and let's not mention eff'ing obvious, slightly shameful about it ;-)

Don't be. There's nothing wrong with being wrong or lacking some knowledge. Unless you're wrong sometimes how can you learn how to be right in the future?

Shameful because such an error, I should have found while researching, not asking high skilled people to answer a low skill question. But thank you again, it is all the more appreciated.

why analogWrite? analogWrite parameter values are 0 to 255 (or 1023) so analogWrite(pin, 1) is close to 0.
analogWrite is PWM on digital ports and doesn't work on analog ports
analogWrite reference
use digitalWrite

I thought digitalwrite was only a single pulse... I will try that asap, if my mistake is this silly I am going to feel ashamed... Thanks for the info in any case!